code:
def checkio(array):
    listSum = 0

    if array:

        for i in range(0, len(array), 2):
            listSum += array[i]

        finalValue = listSum * array[-1]

        return finalValue
    else:
        return 0

rawDescription: Trouble with Basic Python exercise involving lists and indexes


code:
def moveRight(mylist):
    return ['0'] + myList[:-1]

def moveLeft(mylist):
    return myList[1:] + ['0']

rawDescription: How would I move all the elements in a list left or right in Python?


code:
from collections import defaultdict, Counter

users = defaultdict(Counter)

users['Tom']['Count'] += 1
users['Tom']['New'] += 1

rawDescription: Can Python dictionaries to be as handy as PHP array?


code: f = open('file.asm', 'rU')

rawDescription: How to read text file with 1Ah char in it?

description: Read text file with 1Ah char in it


code:
import itertools
from matplotlib import pyplot

colors = ['b', 'r', 'g', 'c']
cc = itertools.cycle(colors)
plot_lines = []
for p in parameters:

    d1 = algo1(p)
    d2 = algo2(p)
    d3 = algo3(p)

    pyplot.hold(True)
    c = next(cc)
    l1, = pyplot.plot(d1, '-', color=c)
    l2, = pyplot.plot(d2, '--', color=c)
    l3, = pyplot.plot(d3, '.-', color=c)

    plot_lines.append([l1, l2, l3])

legend1 = pyplot.legend(plot_lines[0], ["algo1", "algo2", "algo3"], loc=1)
pyplot.legend([l[0] for l in plot_lines], parameters, loc=4)
pyplot.gca().add_artist(legend1)

rawDescription: matplotlib: 2 different legends on same graph

description: Matplotlib: 2 different legends on same graph


code:
with self._group():
    with self._choice():
        with self._option():
            self._token('nameguard')
        with self._option():
            self._token('ignorecase')
        with self._option():
            self._token('left_recursion')
        self._error('expecting one of: ignorecase left_recursion nameguard')

rawDescription: Is it possible to use a with grako generated parser without grako?


code:
import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.hold(False)

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

rawDescription: How to embed matplotib in pyqt - for Dummies

description: Embed matplotib in pyqt - for Dummies


code:
words_num_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
num = int(input('Enter a number (2-5): '))
count = 2
while count <= num:
    if num > 5:
        print('invalid.')
        num = int(input('Enter a number (2-5): '))
    print(words_num_dict[count])
    count = count + 1

rawDescription: I need help changing integers to words in Python 3.4.3


code:
def main():
    print('hello')
    return

if __name__ == "__main__": # Avoid running main function when this file is imported instead of run directly.
    main()

rawDescription: Can you call the main function at the top in python like perl?

description: Call the main function at the top in python like perl


code: [', '.join(reversed(name.split(', '))) for name in names]

rawDescription: Change order of elements in a list

description: Change order of elements in a list


code:
from tkinter import *
import random
##
from tkinter.messagebox import showinfo

class BubbleFrame:

    def __init__(self, root):
        root.title("Math Bubbles")
        self.bubbles = {}
        self.score = 0
        Button(root, text="Start", width=8, command=self.initialize_bubbles).pack()  # This button starts the game, making the bubbles move across the screen
        Button(root, text="Quit", width=8, command=quit).pack()
        self.canvas = Canvas(root, width=800, height=650, bg='#afeeee')
        self.canvas.create_text(400, 30, fill="darkblue", font="Times 20 italic bold", text="Click the bubbles that are multiples of two.")
        ##
        self.current_score = self.canvas.create_text(200, 60, fill="darkblue", font="Times 15 italic bold", text="Your score is:")
        self.canvas.pack()

    def initialize_bubbles(self):
        for each_no in range(1, 21):
            xval = random.randint(5, 765)
            yval = random.randint(5, 615)
            oval_id = self.canvas.create_oval(xval, yval, xval + 30, yval + 30,fill="#00ffff", outline="#00bfff", width=5, tags="bubble")
            text_id = self.canvas.create_text(xval + 15, yval + 15, text=each_no, tags="bubble")
            self.canvas.tag_bind("bubble", "<Button-1>", lambda x: self.click(x))
            self.bubbles[oval_id] = (xval, yval, 0, 0, each_no, text_id)

    def click(self, event):
        if self.canvas.find_withtag(CURRENT):
            item_uid = event.widget.find_closest(event.x, event.y)[0]
            is_even = False
            try:
                self.bubbles[item_uid]
            except KeyError:
                for key, value in self.bubbles.iteritems():
                    if item_uid == value[5]:
                        if value[4] % 2 == 0:
                            is_even = True
                        self.canvas.delete(key)
                        self.canvas.delete(item_uid)
            else:
                if self.bubbles[item_uid][4] % 2 == 0:
                    is_even = True
                self.canvas.delete(item_uid)
                self.canvas.delete(self.bubbles[item_uid][5])
            if is_even:
                self.score += 1
            else:
                self.score -= 1

            if self.score == 10:
                ##
                showinfo("Winner", "You won!")
        ##
        self.canvas.delete(self.current_score)
        ##
        self.current_score = self.canvas.create_text(200, 60, fill="darkblue", font="Times 15 italic bold", text="Your score is: %s"%self.score)

    def loop(self, root):
        for oval_id, (x, y, dx, dy, each_no, text_id) in self.bubbles.items():
            dx += random.randint(-1, 1)
            dy += random.randint(-1, 1)
            dx, dy = max(-5, min(dx, 5)), max(-5, min(dy, 5))
            if not 0 < x < 770:
                dx = -dx
            if not 0 < y < 620:
                dy = -dy
            self.canvas.move(oval_id, dx, dy)
            self.canvas.move(text_id, dx, dy)
            self.bubbles[oval_id] = (x + dx, y + dy, dx, dy, each_no, text_id)
        root.after(100, self.loop, root)

if __name__ == "__main__":
    root = Tk()
    frame = BubbleFrame(root)
    frame.loop(root)
    root.mainloop()

rawDescription: Python: How to get score board on canvas


code:
#!/usr/bin/env python2

from threading import Thread
from pygtk import gtk, gobject

class Window(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        self.connect('delete-event', gtk.main_quit)
        self.label = gtk.Label('1')
        self.add(self.label)
        gobject.timeout_add_seconds(1, self.threaded)

    def threaded(self):
        thread = Thread(target=self.updateValues)
        thread.start()
        return True

    def updateValues(self):
        # urllib.urlopen calls
        n = int(self.label.get_text())
        gobject.idle_add(self.label.set_text, str(n + 1))

win = Window()
win.show_all()
gobject.threads_init()
gtk.main()

rawDescription: Cyclic label update in Python

description: Cyclic label update in Python


code:
import logging

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

rawDescription: How to get number of SQL queries made?

description: Get number of SQL queries made


code: new_list = [(name, value) + extra_info(name) for name, value in old_list]

rawDescription: Python create tuples using function returning multiple values


code: [(i, a, b) for i, a in lst1 for j, b in lst2 if i==j]

rawDescription: Python zip by key

description: Python zip by key


rawDescription: No cmp keyword for max function in python


code:
from PIL import Image
import images2gif as i2g
images = i2g.readGif('Animated.gif', False)
watermark = Image.open("Watermark.gif")
for i in images: i.paste(watermark, (1, 1))

i2g.writeGif('Out.gif', images, 0.5) # You may wish to play with the timing, etc.
exit()

rawDescription: Watermark GIF with Python PIL

description: Watermark GIF with Python PIL


code:
from django.confs.urls.defaults import *
from my_app import one_time_startup

urlpatterns = ...

one_time_startup()

rawDescription: Execute code when Django starts ONCE only?


code:
def phone_request(request):
    user_id = request.user.id
    uuid = request.GET.get('uuid')
    profile_id = profiles.objects.get(uuid=uuid).user_id
    p,created = Photo_request_list.objects.get_or_create(who=user_id)
    p.whose.add(profiles.objects.get(uuid=uuid))
    p.save()

rawDescription: Django get_or_create and ManytoManyField


code:
from StringIO import StringIO
import gzip

request = urllib2.Request('http://example.com/')
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO( response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()

rawDescription: Does python urllib2 automatically uncompress gzip data fetched from webpage?


code:
def update_in_place(self, request, original_bundle, new_data):
    """
    Update the object in original_bundle in-place using new_data.
    """

    """Right here I am checking if the parameter flaggedUserID is in the
    request (PATCH saves request data to request.body).  If this is false then
    copy the new data into the query, otherwise jump to
    alter_deserialized_detail_data where I am handling the appending of the data
    from the request. """

    if 'flaggedUserID' not in request.body:
        original_bundle.data.update(**dict_strip_unicode_keys(new_data))

    # Now we've got a bundle with the new data sitting in it and we're
    # we're basically in the same spot as a PUT request. SO the rest of this
    # function is cribbed from put_detail.
    self.alter_deserialized_detail_data(request, original_bundle.data)
    kwargs = {
        self._meta.detail_uri_name: self.get_bundle_detail_data(original_bundle),
        'request': request,
    }
    return self.obj_update(bundle=original_bundle, **kwargs)

rawDescription: Tastypie Accessing Query Before Data Gets Replaced by Request


code: [a*b for a,b in zip(lista,listb)]

rawDescription: python element-wise multiplication of two lists

description: Python element-wise multiplication of two lists


code:
def surround_by_quote(a_list):
    return ['"%s"' % an_element for an_element in a_list]

env.filters["surround_by_quote"] = surround_by_quote

rawDescription: Add quota around each string in a list in jinja2?


code:
my_tag = session.query(Tag).get(1)

# option-1: if data is already loaded into memory
posts = [post for post in my_tag.posts if post.id > 10]

# option-2: query database with filter if you have "my_tag" instance
posts = session.query(Post).with_parent(my_tag).filter(Post.id > 10).all()

# option-3: query database with filter if you have slug value
posts = session.query(Post).join(Tag, Post.tags).filter(Tag.slug == "my_slug").filter(Post.id > 10).all()

rawDescription: sqlalchemy many-to-many relationship, how to filter the collection

description: Sqlalchemy many-to-many relationship, how to filter the collection


code:
import uinput
# set up keystroke input
device = uinput.Device([uinput.KEY_TAB])
while True:
    triggered_sensor = get_sensor_method()
    if triggered_sensor:
        device.emit_click(uinput.KEY_TAB)

rawDescription: Python to simulate keyboard strokes

description: Python to simulate keyboard strokes


code: i = sorted(random.sample(range(1, 53), 5))

rawDescription: Powerball number generator:

description: Powerball number generator:


code:
class ComplexClassStub(ComplexClass):
  def __init__(self):
    self.lots = None
    self.the_rest_of_the_args = None # Now your complex class isn't so complex.

class ComplexClassTest(unittest.TestCase):
  def Setup(self):
    self.helper = ComplexClassStub()

  def testStartThing(self):
    with mock.patch.object(self.helper, 'SomethingToMock') as something_mocked:
      expected = 'Fake value'
      actual = self.helper.start_thing()
      self.assertEqual(expected, actual)
      something_mocked.assert_called_once_with()

rawDescription: Python unittest Mock patch object not methods


code:
import nltk # pip install nltk
nltk.download('gutenberg')
words = nltk.corpus.gutenberg.words('carroll-alice.txt')
max(words, key=len) # find the longest word

rawDescription: Converting a Text File to a String in Python


code:
def parse(hr, mn, sec, yearday, yr):
          date_string = ' '.join([yr, yearday, hr, mn, sec])
          return dt.datetime.strptime(date_string, "%Y %j %H %M %S")

rawDescription: Reading CSV data with yearday column into Pandas as datetime


code: a = itertools.repeat(0, n)

rawDescription: Complexity of initialize list of size n?

description: Complexity of initialize list of size n


code: return render(request, 'cart.html', {'key': value})

rawDescription: Default RequestContext in Django

description: Default RequestContext in Django


code: zip(dev, phone, carrier)

rawDescription: Python: How to create 2D array using existing lists


rawDescription: Extract the last information of url in Python


code:
import json

@app.route('/test', methods = ['POST'])
@inlineCallbacks
def test(request):
    output = dd()
    data = json.loads(request.content.read())  # <=== This will work

rawDescription: Access json content of http post request with Klein in python


rawDescription: How to make a function that applies different formulas to any length of tuple?

description: Make a function that applies different formulas to any length of tuple


code:
array = (ctypes.c_ubyte * frameInfo.lHeight * frameInfo.lWidth * 1
          ).from_address(ctypes.addressof(pBuffer.contents))
pBufY = np.ndarray(buffer=array, dtype=np.uint8,
                   shape=(frameInfo.lHeight, frameInfo.lWidth, 1))

rawDescription: Numpy Array Operation Too Slow np.asarray()


code:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference('startup.homepage_welcome_url.additional', '')
browser = webdriver.Firefox(profile)

rawDescription: Python Selenium: getting rid of Firefox first run screen


code:
for sublist in mylist:
    sublist.sort()

mylist.sort()

rawDescription: How do I make each list in the list of lists sort in ascending order?

description: Make each list in the list of lists sort in ascending order


code:
infile = open('file.txt', 'r')
outfile = open('outfile.txt', 'w')
for l in infile:
    outfile.write(l.split()[-1] + '\n')

infile.close()
outfile.close()

rawDescription: Extract data from text file in Python and write to new file


code:
import inspect
import re
import textwrap

import bs4.element

def replace_code_lines(source, start_token, end_token,
                       replacement, escape_tokens=True):
    """Replace the source code between `start_token` and `end_token`
    in `source` with `replacement`. The `start_token` portion is included
    in the replaced code. If `escape_tokens` is True (default),
    escape the tokens to avoid them being treated as a regular expression."""

    if escape_tokens:
        start_token = re.escape(start_token)
        end_token = re.escape(end_token)

    def replace_with_indent(match):
        indent = match.group(1)
        return textwrap.indent(replacement, indent)

    return re.sub(r"^(\s+)({}[\s\S]+?)(?=^\1{})".format(start_token, end_token),
                  replace_with_indent, source, flags=re.MULTILINE)

# Get the source code of the Tag.select() method
src = textwrap.dedent(inspect.getsource(bs4.element.Tag.select))

# Replace the relevant part of the method
start_token = "if pseudo_type == 'nth-of-type':"
end_token = "else"
replacement = """\
if pseudo_type == 'nth-of-type':
    try:
        if pseudo_value in ("even", "odd"):
            pass
        else:
            pseudo_value = int(pseudo_value)
    except:
        raise NotImplementedError(
            'Only numeric values, "even" and "odd" are currently '
            'supported for the nth-of-type pseudo-class.')
    if isinstance(pseudo_value, int) and pseudo_value < 1:
        raise ValueError(
            'nth-of-type pseudo-class value must be at least 1.')
    class Counter(object):
        def __init__(self, destination):
            self.count = 0
            self.destination = destination

        def nth_child_of_type(self, tag):
            self.count += 1
            if pseudo_value == "even":
                return not bool(self.count % 2)
            elif pseudo_value == "odd":
                return bool(self.count % 2)
            elif self.count == self.destination:
                return True
            elif self.count > self.destination:
                # Stop the generator that's sending us
                # these things.
                raise StopIteration()
            return False
    checker = Counter(pseudo_value).nth_child_of_type
"""
new_src = replace_code_lines(src, start_token, end_token, replacement)

# Compile it and execute it in the target module's namespace
exec(new_src, bs4.element.__dict__)
# Monkey patch the target method
bs4.element.Tag.select = bs4.element.select

rawDescription: Extending CSS selectors in BeautifulSoup


code:
#!/usr/bin/kivy

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.properties import BoundedNumericProperty

Builder.load_string('''
<MyWidget>:
    Button:
        text: "Set error handler"
        on_press: root.set_error_handler()
    Button:
        text: "Test"
        on_press: root.bnp = 10000
''')

class MyWidget(BoxLayout):
    bnp = BoundedNumericProperty(0, min=-500, max=500)

    def error_handler(self, *args):
        print("error_handler")
        return 0

    def set_error_handler(self):
        # we need to add default value as the first argument
        self.property('bnp').__init__(0, errorhandler=self.error_handler)

class MainApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MainApp().run()

rawDescription: BoundedNumericProperty: set errorhandler at runtime


code: print("Time left till next update: %d seconds" % t, end='\r')

rawDescription: How do I print in Python 3.3.3 without carriage return?

description: Print in Python 3.3.3 without carriage return


code:
stringvar = []
while type(tuplevar) is tuple:
        stringvar.append(tuplevar[0])
        tuplevar=tuplevar[1]
stringvar.append(tuplevar)  # to get the last element.

rawDescription: Python converting a tuple (of strings) of unknown length into a list of strings


code:
from cx_Freeze import setup, Executable

# dependencies
build_exe_options = {
    "packages": ["os", "sys", "glob", "simplejson", "re", "atexit", "PySide.QtCore", "PySide.QtGui", "PySide.QtXml"],
    "include_files": [("./example/Ui/MainWindow.ui", "Ui/MainWindow.ui"),
                      ("./example/Ui/ExampleWidget.ui", "Ui/ExampleWidget.ui"),
                      ("./example/Ui/TestDialog.ui", "Ui/TestDialog.ui"),
                      ("./example/Resources/style.qss", "Ui/style.qss")], # this isn't necessary after all
    "excludes": ["Tkinter", "Tkconstants", "tcl"],
    "build_exe": "build",
    "icon": "./example/Resources/Icons/monitor.ico"
}

executable = [
    Executable("./bin/Example.py",
               base="Win32GUI",
               targetName="Example.exe",
               targetDir="build",
               copyDependentFiles=True)
]

setup(
    name="Example",
    version="0.1",
    description="Example", # Using the word "test" makes the exe to invoke the UAC in win7. WTH?
    author="Me",
    options={"build_exe": build_exe_options},
    executables=executable,
    requires=['PySide', 'cx_Freeze', 'simplejson']
)

rawDescription: What is the best approach with compiling PySide application


code:
from collections import defaultdict

desserts = defaultdict(list)

while True:
    name_vote = input('Name:vote ')
    if name_vote == '':
        break
    name, vote = name_vote.split(':')
    desserts[vote].append(name)

for dessert, names in desserts.items():
    print(dessert, len(names), 'vote(s):', ' '.join(names))

rawDescription: Counting items in a List used as a Dictionary Value


code:
import numpy as np
import simplejson as json
import cherrypy as cp
import operator

global pagearray

def initialize(self):
    global pagearray
    pagearray = np.load("pagearray.npy")
    #return os.path

def getUserPath(self, input):
    subpagearray = []
    possibilities = []
    global pagearray
    for i in pagearray:
        try:
            if input==i[0]:
                subpagearray += [i[1:]]
                possibilities+= [i[1]]
        except IndexError:
            pass
    x = build_dict(possibilities)
    sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
    pagearray = subpagearray
    totalelements = len(pagearray)
    returnvaluelist = []
    weight = []
    for i in sorted_x:
        returnvaluelist += [i[0]]
        weight += [(i[1]/(totalelements*1.0))*100]
    return returnvaluelist, weight

def build_dict(a_list=None):
    if a_list is None:
        a_list = []
    site_dict = {}
    for site in a_list:
        try:
            site_dict[site] = site_dict[site] + 1
        except KeyError:
            site_dict[site] = 1
    return site_dict

rawDescription: Numpy Arrays: Searching for subarrays

description: Numpy Arrays: Searching for subarrays


code:
from datetime import date, timedelta

d = date.today() - timedelta(days=days_to_subtract)

rawDescription: How can I subtract a day from a Python date?

description: Subtract a day from a Python date


rawDescription: How to convert u'\x96' to u'–' in python

description: Convert u'\x96' to u'–' in python


code:
mac = 'FF:FF:FF:FF:FF:FF'
spacemac = mac.replace(':',' ')
spacemac

rawDescription: Splitting MAC address on python

description: Splitting MAC address on python


rawDescription: Variable changes without the knowledge of after =


code:
import http.client
connection = http.client.HTTPConnection('www.python.org')

connection.request('GET', '/')
response = connection.getresponse()
print(response.status)
print(response.msg)
answer = response.read()
print(answer)

rawDescription: Python - sending http requests as strings


code:
book = xlrd.open_workbook("Test.xlsx")
sheet = book.sheet_by_index(0)

list_j = []

for k in range(1,sheet.nrows):
    list_j.append(str(sheet.row_values(k)[j-1]))

rawDescription: How would I take an excel file and convert its columns into lists in Python?


code:
import ast
with open('list.txt') as f:
    output = ast.literal_eval(f.read())

rawDescription: How do you load a file as a List type in Python?

description: Load a file as a List type in Python


code:
import os

my_path = os.environ['PATH']

rawDescription: sys.path vs. $PATH

description: Sys.path vs. $PATH


code:
from Tkinter import StringVar,Entry,Tk
class UIclass():
    def __init__(self,root):
        #define self.frame1
        self.myfunc()

    def myfunc(self):
        self.entry_boxes(6,1,'N/A','self.systest',self.frame1)
        self.entry_boxes(6,2,'N/A','self.systest',self.frame1)
        ...
        ...
        ...

    def entry_boxes(self, row, col, default, var, frame):
        setattr(self, var, StringVar)
        setattr(self, var, default)
        e = Entry(frame, textvariable=var)
        e.grid(row=row, column=col)

if __name__ == '__main__':
    root = Tk()
    UIclass(root)
    root.mainloop()

rawDescription: How to mass produce entry box widgets in Tkinter?

description: Mass produce entry box widgets in Tkinter


code:
r=pd.read_fwf('test.txt', widths=(3, 8, 9, 14, 14, 14),skiprows=1, header=None)
r=r.fillna(method='pad')
r=r.set_index(['X0','X1','X2'])

rawDescription: Reading from file a hierarchical ascii table using Pandas


code:
import os
import sys
import subprocess as sp

# Open -> gives file descriptor (integer, corresponds to /dev/fd/*)
fd = os.open(FILENAME,os.O_RDONLY) # see os module doc for O_RDONLY
# This gives a standard file object:
handle = os.fdopen(fd,'rb',0)

# Read one line, do whatever you want in python.
# Read in using unbuffered I/O, this requires reading in binary mode.
# The resulting bytes array must be converted to string using an encoding
header = handle.readline.decode(sys.getdefaultencoding())
header = header.rstrip().split()

# Make fd inheritable by children processes
os.set_inheritable(fd, True)

# Open child process, pass file descriptor as input.
# Using /dev/fds/{fd} or <(cat <&{fd}) (bash only) can turn a file descriptor stream
# into a file, if needed for child program.
# This child process sees any input which is not already consumed by the
# above lines
sp.check_call("wc -l <&{fd}".format(fd=fd),pass_fds=(fd,))

rawDescription: Read from a named pipe in two parts in python: First python, then subprocess


code:
import pandas as pd

df = pd.DataFrame({'date':['2010/09/06','2011/01/24','2011/09/12','2011/09/26'],
        'job':['D','C','B','A'],
        'count':[1,1,1,1]})

unqiue_dates = df.date.drop_duplicates()
unique_jobs = df.job.drop_duplicates()

dates = pd.DataFrame({"dates":unqiue_dates,"key":["key"] * len(unqiue_dates)})
jobs = pd.DataFrame({"jobs":unique_jobs,"key":["key"] * len(unique_jobs)})

columns = ['dates','jobs','count']
final = pd.merge(dates,jobs,on="key")

final = pd.merge(final,df,left_on=['dates','jobs'],right_on=['date','job'],
                how='left').fillna(0)[columns]

rawDescription: Using Pandas to add missing categories for each date


code:
rank = {key:rank for rank, key in list1}
print(sorted(list2, key=lambda t: rank.get(t[0]), reverse=True))

rawDescription: Sorting Lists of tuples based on a list of tuples - Python


code:
def precision(actual, predicted, k):
    act_set = set(actual)
    pred_set = set(predicted[:k])
    result = len(act_set & pred_set) / float(k)
    return result

def recall(actual, predicted, k):
    act_set = set(actual)
    pred_set = set(predicted[:k])
    result = len(act_set & pred_set) / float(len(act_set))
    return result

rawDescription: Evaluation of lists: AvgP@K and R@K are they same?


code:
import requests
from bs4 import BeautifulSoup
import csv

payload = {'ID': '18845', 'PS': '1', 'Submit': 'Submit'}
r = requests.post("http://.com", data=payload)

soup = BeautifulSoup(r.text, "html.parser")

with open('some.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=';')
    ll = []
    for row in soup.findAll('table')[0].findAll('tr'):
        ans = row.findAll('td')[1].contents
        ll.append(ans)
    csvwriter.writerow(ll)

rawDescription: How can I write a result as csv?

description: Write a result as csv


rawDescription: Transforming a numpy array into another

description: Transforming a numpy array into another


code:
def classify(number):
    num_str = str(number)
    if num_str.startswith("58"):
        return 1
    return 0

rawDescription: Way to match number patterns in Python

description: Way to match number patterns in Python


code:
def quick_sort(list):
    if not list:
        return list
    pivot = list[0]
    lesser = quick_sort([x for x in list[1:] if float(x[1]) < float(pivot[1])], 1)
    greater = quick_sort([x for x in list[1:] if float(x[1]) >= float(pivot[1])], 1)
    return lesser + [pivot] + greater

rawDescription: How to implement a Quick Sort in Python

description: Implement a Quick Sort in Python


code:
from twisted.internet import reactor, task

d = task.deferLater(reactor, 0, myFunction, parameter1)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()

rawDescription: How to combine callLater and addCallback?

description: Combine callLater and addCallback


code: horaactual = datetime.datetime.now() - datetime.timedelta(hours=7)

rawDescription: How to automatic display an editted datetime.now() in python?

description: Automatic display an editted datetime.now() in python


code:
[getattr(func.__code__,s)
 for s in ['co_argcount', 'co_cellvars', 'co_code', 'co_consts',
           'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars',
           'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize',
           'co_varnames']
]

rawDescription: Python: strategies for persistently memoizing functions with function arguments?


rawDescription: matching unicode characters in python regular expressions


code:
c = getch()
first_byte = ord(c)
bytes_remain = 0
while (first_byte >> (6 - bytes_remain)) & 0b11 == 0b11:
    bytes_remain += 1
    c += getch()

rawDescription: Python read a single unicode character from the user


rawDescription: Python append to a value in dictionary

description: Python append to a value in dictionary


code:
implot = plt.imshow(im,origin='upper')
...
extent = [xedges[0], xedges[-1], yedges[-1], yedges[0]]
plt.imshow(heatmap, extent=extent,alpha=.5,origin='upper')

rawDescription: Matplotlib heatmap: Image rotated when heatmap plot over it


code:
# How to load a text file as a corpus.
import nltk
from nltk.corpus import PlaintextCorpusReader
from nltk.corpus.util import LazyCorpusLoader
afrikaans = LazyCorpusLoader('afrikaans', PlaintextCorpusReader, r'(?!\.).*\.txt')
afrikaans.sents()[1]
af = nltk.Text(afrikaans.words())
af.concordance("mense")

rawDescription: How to access a text file with Afrikaans language words as a nltk corpus

description: Access a text file with Afrikaans language words as a nltk corpus


code:
def __truediv__(self, other):
  if callable(other):
      return Function(lambda x:self(x)/other(x))
  else:
      return Function(lambda x:self(x)/other)

rawDescription: Implementing pointwise arithmetic with implicit type conversion


code:
from selenium import webdriver
from selenium.webdriver.common import alert
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
class AlertsManager:
    def alertsManager(self,url):
        self.url_to_visit=url
        self.driver=webdriver.Firefox()
        self.driver.get(self.url_to_visit)
        try:
            while WebDriverWait(self.driver,1).until(EC.alert_is_present()):
                self.alert=self.driver.switch_to_alert()
                self.driver.switch_to_alert().accept()
        except TimeoutException:
            pass
        print("Continue what you want here ...")

if __name__=='__main__':
    AM=AlertsManager()
    url="http://htmlite.com/JS006.php"
    AM.alertsManager(url)

rawDescription: How to accept all the alerts of a website?

description: Accept all the alerts of a website


code:
#!/usr/bin/env python

from PyKDE4 import kdecore, kdeui
from PyQt4 import QtCore, QtGui

appName     = "default"
catalog     = ""
programName = kdecore.ki18n("default")
version     = "1.0"
description = kdecore.ki18n("Default Example")
license     = kdecore.KAboutData.License_GPL
copyright   = kdecore.ki18n("unknown")
text        = kdecore.ki18n("none")
homePage    = ""
bugEmail    = "email"
aboutData   = kdecore.KAboutData(appName, catalog, programName, version, description,
                          license, copyright, text, homePage, bugEmail)

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 400)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(80, 110, 271, 51))
        font = QtGui.QFont()
        font.setPointSize(24)
        self.label.setFont(font)
        self.label.setObjectName(_fromUtf8("label"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 20))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(kdecore.i18n(_fromUtf8("MainWindow")))
        self.label.setText(kdecore.i18n(_fromUtf8("Hello World!")))

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setupUi(self)

if __name__ == "__main__":
    import  sys

    kdecore.KCmdLineArgs.init(sys.argv, aboutData)
    app = kdeui.KApplication()
    main = MainWindow()
    main.resize(640, 480)
    main.show()
    app.lastWindowClosed.connect(app.quit)
    app.exec_()

rawDescription: How can I troubleshoot an "hello world" program in Qt Designer?

description: Troubleshoot an "hello world" program in Qt Designer


code:
import Tkinter as tk

class TableWithFrame(tk.Frame):
    def __init__(self,master=None,*args,**kwargs):
        tk.Frame.__init__(self,master,*args,**kwargs)
        self.table=tk.Frame(self)
        self.table.grid(row=0,column=0)

        self.optionmenu=None
        self.option=tk.StringVar()

        self.frames={}
        self.options=[]
        self.current_choice=None

        self.add_optionmenu()
        self.option.trace("w",self.option_changed)

    def add_option(self,option_string,frame):
        self.options.append(option_string)
        if(self.optionmenu is not None):
            self.optionmenu.destroy()
        self.add_optionmenu()
        self.frames[option_string]=frame

    def add_optionmenu(self):
        if(self.optionmenu is not None):
            self.optionmenu.destroy()

        if(self.options):
            self.optionmenu=tk.OptionMenu(self,self.option,*self.options)
            self.optionmenu.grid(row=1,column=0)

    def option_changed(self,*args):
        choice=self.option.get()
        if(self.current_choice is not None):
            self.current_choice.grid_forget()
        self.current_choice=self.frames[choice]
        self.current_choice.grid(row=0,column=1)

if __name__ == "__main__":
    def populate_table(table):
        """ junk data """
        for j in range(3):
            for i in range(10):
                l=tk.Label(table,text='%d'%(i*j))
                l.grid(row=j,column=i)

    def create_opt_frames(TWF):
        #Fixed Frame
        F=tk.Frame(TWF)
        F.boxes={}
        TWF.add_option('Fixed',F)

        #List Frame
        F=tk.Frame(TWF)
        F.boxes={}
        for i in (1,2,3,4):
            choice_title = tk.Label(F, text='Value %g'% float(i+1))
            choice_title.grid(row=0, column=i, sticky="news")
            box = tk.Entry(F, bg='white')
            box.grid(row=1, column=i, sticky="ew")
            F.boxes[i]=box

        TWF.add_option('List',F)

        #Bigger and Between Frame
        F=tk.Frame(TWF)
        F.boxes={}
        choice_title1 = tk.Label(F, text='Min Value')
        choice_title1.grid(row=0, column=0, sticky="news")
        choice_title2 = tk.Label(F, text='Max Value')
        choice_title2.grid(row=0, column=1, sticky="news")
        for i in (1,2):
            box = tk.Entry(F)
            box.grid(row=1, column=i-1, sticky="nsew", padx=1, pady=1)
            F.boxes[i]=box

        TWF.add_option('Between',F)
        TWF.add_option('Bigger',F)

    def print_boxes(TWF):
        """ Example of how to get info in Entry fields """
        if(TWF.current_choice is not None):
            for k,v in TWF.current_choice.boxes.items():
                print ("boxnum (%d) : value (%s)"%(k,v.get()))
        TWF.after(1000,lambda : print_boxes(TWF))

    root=tk.Tk()
    App=TableWithFrame(root)
    populate_table(App.table)
    create_opt_frames(App)
    print_boxes(App)
    App.grid(row=0,column=0)
    root.mainloop()

rawDescription: Equal size 'table' frames and deleting a single frame


code:
from django.test import Client
c = Client()
response = c.get('/')
response.content

rawDescription: Export Django view to static HTML files using Django API (i.e. not wget or other scraper)


rawDescription: Python how do I add user entry to a new value on a list?


code:
import pandas as pd
#your data looks something like this:
mydict={"date1" : {"calls": [ {"change":1,"ask":4,"bid":5,"name":"x83"},
                              {"change":3,"ask":9,"bid":2,"name":"y99"} ] },
        "date2" : {"calls": [ {"change":4,"ask":3,"bid":7,"name":"z32"} ] } }

def convert(something):
    # Convert strings to floats, unless they're really strings
    try: return float(something)
    except ValueError: return something

# make an empty sequence
dataseq = []
# list the fields you want from each call
desired = ["ask","change","bid","name"]

for thisdate in mydict.keys():
    # get the calls for each date
    for thiscall in mydict[thisdate]["calls"]:
        # initialize a new dictionary for this call with the entry date
        d = {"date":thisdate}
        for field in desired:
            # get the data and convert to float if it's a float
            d[field]=convert(thiscall[field])
        # add it to your sequence
        dataseq.append(d)
# make a dataframe
a = pd.DataFrame(dataseq)

rawDescription: Python, Nested Dictionary to Dataframe

description: Python, Nested Dictionary to Dataframe


code:
import random

random_idx = random.randint(0, Model.objects.count() - 1)
random_obj = Model.objects.all()[random_idx]

rawDescription: How to grab one random item from a database in Django/postgreSQL?

description: Grab one random item from a database in Django/postgreSQL


code:
def matches_template(word, template):
  found_chars = set(x for x in template if x != '-')
  for char, template_char in zip(word, template):
    if template_char == '-':
      if char in found_chars: return False
    else:
      if template_char != char: return False
  return True

rawDescription: Python RegEx- hangman algorithm

description: Python RegEx- hangman algorithm


code: np.ma.average(ma, axis=(1,2))

rawDescription: Averaging numpy masked array over multiple dimensions


code:
directories = {'': set()}

for f in files:
    splitted = f.split("/")
    directories[''].add(splitted[0])

    for i in range(len(splitted)):
        if i == len(splitted)-1:
            break

        d = ''
        for j in splitted[0:i+1]:
            d += j + os.path.sep

        d = d[0:-1]

        if not d in directories:
            directories[d] = set()

        directories[d].add(splitted[i+1])

rawDescription: get dictionary of files and directories from git repository

description: Get dictionary of files and directories from git repository


code:
if not self.has_permission(request):
    return self.login(request)

rawDescription: Incorporate custom template into the django admin interface and session


code:
import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")

rawDescription: Dump a NumPy array into a csv file

description: Dump a NumPy array into a csv file


code: result = [x[0][0] for x in exampleArray]

rawDescription: flatten list in python

description: Flatten list in python


code:
import itertools
Adict = {"x": 1, "y": 2, "z":3}
Bdict = {"foo": 4, "bar": 5, "baz":6}
A,B = Adict.values(),Bdict.values()
def comp(a, b):
  return a * b # Insert complicated computation here
res = {(a,b):comp(a,b) for a,b in itertools.product(A, B)}

rawDescription: What is the most appropriate python data structure to keep the result of pairwise computations over 2 dictionaries?


code:
import pygame,sys
from pygame import *

WIDTH = 480
HEIGHT = 480
WHITE = (255,255,255) #RGB
BLACK = (0,0,0) #RGB

pygame.init()
screen = display.set_mode((WIDTH,HEIGHT),0,32)
display.set_caption("Name of Application")
screen.fill(WHITE)
timer = pygame.time.Clock()
pos_on_screen, radius = (50, 50), 20
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    timer.tick(60) #60 times per second you can do the math for 17 ms
    draw.circle(screen, BLACK, pos_on_screen, radius)
    display.update()

rawDescription: drawing a point on the screen every 17ms in Python?

description: Drawing a point on the screen every 17ms in Python


code:
aa1 = [0,1,1,2,3,3,4,4,5,9]
aa2 = [0,1,3,3,4,4,4,4,5,6,7,9]
bins = [0,3,9]
height = [np.histogram( xs, bins=bins)[0] for xs in [aa1, aa2]]
left, n = np.arange(len(bins)-1), len(height)

ax = plt.subplot(111)
color_cycle = ax._get_lines.color_cycle

for j, h in enumerate(height):
    ax.bar(left + j / n, h, width=1.0/n, color=next(color_cycle))

ax.set_xticks(np.arange(0, len(bins)))
ax.set_xticklabels(map(str, bins))

rawDescription: How to draw histogram with same bins width for unequally spaced bins in matplotlib

description: Draw histogram with same bins width for unequally spaced bins in matplotlib


code:
encrypted = [ chr(ord(a) ^ ord(b)) for (a,b) in zip(var, key) ]
encrypted
decrypted = [ chr(ord(a) ^ ord(b)) for (a,b) in zip(encrypted, key) ]
decrypted
"".join(decrypted)

rawDescription: byte operations (XOR) in python

description: Byte operations (XOR) in python


code:
df
s = df.C.apply(Series).unstack().reset_index(level=0, drop = True)
s.name = 'C2'
df.drop('C', axis = 1).join(s)

rawDescription: DataFrame from dictionary with nested lists


code:
@hybrid_property
def created_on(self):
    return date(self.year_id, self.month_id, self.day_id)

@created_on.expression
def created_on(cls):
    # @todo: create RDBMS-specific fucntion
    # return func.date(cls.year_id, cls.month_id, cls.day_id)

    # below works on Sqlite: format to YYYY-MM-DD
    return (func.cast(cls.year_id, String) + '-' +
            func.substr('0' + func.cast(cls.month_id, String), -2) + '-' +
            func.substr('0' + func.cast(cls.day_id, String), -2))

rawDescription: Filter query in SQLAlchemy with date and hybrid_property


code:
x = 'http://www.example.com:8080/abcd/dir/file1.html?query1=value1&query2=value2'
query_pattern='(query\d+)=(\w+)'
# query_pattern='(\w+)=(\w+)'    a more general pattern
re.findall(query_pattern,x)

rawDescription: parse URL with regex in python

description: Parse URL with regex in python


rawDescription: How to check if a given character is considered as 'special' by the Python regex engine?

description: Check if a given character is considered as 'special' by the Python regex engine


code:
keywords = ...

for line in infile:
    # iterate through ALL the keywords
    found_all = True
    for kw in keywords:
        # if ANY keyword is not found, found_all = False
        if kw not in line:
            found_all = False

    if found_all:
        outfile.write(line)

rawDescription: Matching lines with an AND operator in Python


code:
from django.conf import settings
from django.http import HttpResponseRedirect

class SSLMiddleware(object):

    def process_request(self, request):
        if not any([settings.DEBUG, request.is_secure(), request.META.get("HTTP_X_FORWARDED_PROTO", "") == 'https']):
            url = request.build_absolute_uri(request.get_full_path())
            secure_url = url.replace("http://", "https://")
            return HttpResponseRedirect(secure_url)

rawDescription: How to make python on Heroku https only?

description: Make python on Heroku https only


code:
import sys

def sleep(sec):
    for i in range(sec):
        print(".", end=" ")
        sys.stdout.flush()
        time.sleep(1)

rawDescription: problem with python print function

description: Problem with python print function


code:
# algorithm
def average_point(rect, p1, p2, count=0):
    returnArray = []
    code_a = vcode(rect, p1)
    code_b = vcode(rect, p2)
    if math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)) < EPS:
        returnArray.append(count)
        returnArray.append(p1)
        returnArray.append(p2)
        return returnArray
    if not (code_a | code_b):
        returnArray.append(count)
        returnArray.append(p1)
        returnArray.append(p2)
        return returnArray
    if code_a & code_b:
        returnArray.append(count)
        returnArray.append(p1)
        returnArray.append(p2)
        return returnArray
    mid = Point((p2.x+p1.x)/2.0, (p2.y+p1.y)/2.0)
    count += 1
    returnArray = average_point(rect, p1, mid, count)
    mid.x = mid.x+1
    mid.y = mid.y+1
    returnArray = average_point(rect, mid, p2, count)
    return returnArray

rawDescription: python midpoint line clipping algorithm

description: Python midpoint line clipping algorithm


code:
def floodfill(matrix, x, y):
    #"hidden" stop clause - not reinvoking for "c" or "b", only for "a".
    if matrix[x][y] == "a":
        matrix[x][y] = "c"
        #recursively invoke flood fill on all surrounding cells:
        if x > 0:
            floodfill(matrix,x-1,y)
        if x < len(matrix[y]) - 1:
            floodfill(matrix,x+1,y)
        if y > 0:
            floodfill(matrix,x,y-1)
        if y < len(matrix) - 1:
            floodfill(matrix,x,y+1)

rawDescription: Flood Fill in Python

description: Flood Fill in Python


code:
from itertools import combinations
[x for d in data for x in combinations(d, 2)]

rawDescription: How to create network data from lists

description: Create network data from lists


code:
import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

rawDescription: Execute curl command within a Python script


code:
import matplotlib.pyplot as plt
import numpy as np

nboxes = 10

# fake up some data
spread= np.random.rand(50,nboxes) * 100
center = np.ones((25,nboxes)) * 50
flier_high = np.random.rand(10,nboxes) * 100 + 100
flier_low = np.random.rand(10,nboxes) * -100
data =np.concatenate((spread, center, flier_high, flier_low), 0)

# plot figure
plt.figure()
bp = plt.boxplot(data)

for i, box in enumerate(bp['boxes']):
    #Colour alternate boxes blue and red
    if i%2:
        box.set_color('blue')
    else:
        box.set_color('red')

plt.show()

rawDescription: Changing the colour of a boxplot when its paired


code:
def f(n):
  print('0')
  for a in range(1, n+1):
    print('1' if prime(a) else '0')

rawDescription: python - sieve of Eratosthenes when number is prime print "1" when not print "0"

description: Python - sieve of Eratosthenes when number is prime print "1" when not print "0"


rawDescription: using rolling functions on multi-index dataframe in pandas

description: Using rolling functions on multi-index dataframe in pandas


code: return [x for x in lista1 if x in lista2]

rawDescription: Python3 Inline if and for statements

description: Python3 Inline if and for statements


code:
def applyTopping1(functor):
    def wrapped():
        base_pizza = functor()
        base_pizza.add("mozzarella")
        return base_pizza
    return wrapped

def applyTopping2(functor):
    def wrapped():
        base_pizza = functor()
        base_pizza.add("ham")
        return base_pizza
    return wrapped

rawDescription: Do python decorators strictly implement the decorator pattern ?


code:
def _OnClick(self, evt):
    x, y = evt.GetX(), evt.GetY()

rawDescription: Get caret position in pixel in RichtextCtrl


code:
key_func = lambda x: x[0][1][x[1]] if len(x[0][1]) > x[1] else None
itertools.groupby(sorted(data, key=key_func), key_func)

rawDescription: itertools.groupby( ) in python

description: Itertools.groupby( ) in python


code:
self.threads = []
for i in xrange(self.thread_count):
    self.threads.append(DownloadThread(self.queue, self.status, self.save_dir, i))
    self.threads[i].start()

rawDescription: Accessing objects that aren't bound to a variable in Python


rawDescription: Python - merge items of two lists into a list of tuples


code: df.index.isin(df.between_time('9:00', '17:00', include_start=True, include_end=True).index)

rawDescription: Pandas between_time boolean

description: Pandas between_time boolean


code:
import numpy as np
from scipy.optimize import leastsq

def residual_two_functions(pars, x, y1, y2):
    off1   = pars[0]
    slope1 = pars[1]
    off2   = pars[2]
    slope2 = pars[3]
    diff1 = y1 - (off1 + slope1 * x)
    diff2 = y2 - (off2 + slope2 * x)
    return np.concatenate((diff1, diff2))

# create two tests data sets
NPTS = 201
x  = np.linspace(0, 10, NPTS)
y1 = -0.7 +  1.7*x + np.random.normal(scale=0.01, size=NPTS)
y2 =  5.2 + 50.1*x + np.random.normal(scale=0.02, size=NPTS)

# initial values
par_init = np.array([0, 1, 10, 100])

best, cov, info, message, ier = leastsq(residual_two_functions,
                                        par_init, args=(x, y1, y2),
                                        full_output=True)

print(" Best-Fit Parameters: ",  best)

rawDescription: Simultaneous data fitting in python with leastsq


code:
from collections import defaultdict
test_classes = {
    'test1': test1,
    'test2': test2
}
test_instances = defaultdict(list)
test_instances[testvariable].append(test_classes[testvariable])

rawDescription: Using variable value as dictionary/class name in Python


code:
import time
for x in range (0,5):
    b = "Loading" + "." * x
    print (b, end="\r")
    time.sleep(1)

rawDescription: Python - Remove and Replace Printed items


code:
import random
from collections import defaultdict

def main():
    dice = int(input("Enter the number of dice: "))
    sides = int(input("Enter the number of sides: "))
    rolls = int(input("Enter the number of rolls to simulate: "))
    result = roll(dice, sides, rolls)
    maxH = 0
    for i in range(dice, dice * sides + 1):
        if result[i] / rolls > maxH: maxH = result[i] / rolls
    for i in range(dice, dice * sides + 1):
        print('{:2d}{:10d}{:8.2%} {}'.format(i, result[i], result[i] / rolls, '#' * int(result[i] / rolls / maxH * 40)))

def roll(dice, sides, rolls):
    d = defaultdict(int)
    for _ in range(rolls):
        d[sum(random.randint(1, sides) for _ in range(dice))] += 1
    return d

main()

rawDescription: Dice Roll Game. Histogram?

description: Dice Roll Game. Histogram


code:
import numpy as np
import scipy.fftpack

data = np.arange(0.0, 12.8, 0.1)
fft = scipy.fftpack.fft(data)

rawDescription: NumPy/SciPy FFT for voltage/time data

description: NumPy/SciPy FFT for voltage/time data


code:
class Student(Base):
    __tablename__ = 'student'

    id = Column('id_', Integer, primary_key=True)
    # other columns...
    created = Column('_created', DateTime, nullable=False, default=datetime.utcnow)
    updated = Column('_updated', DateTime, onupdate=datetime.utcnow)

rawDescription: Cannot access column in PostgreSQL table from Python model


code:
import collections
l = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
c = collections.Counter(l)
assert c['hello'] == 3

rawDescription: dict comprehension with unique keys out of list

description: Dict comprehension with unique keys out of list


code:
def do_post_processing(filename):
    with open(str(filename), 'rb') as f:
        image = Image.open(f)
        ...
        del new_image, image
    os.remove(str(filename))
    os.rename(...)

rawDescription: How to Close an Image?

description: Close an Image


code:
s = RDF.HashStorage("abc", options="hash-type='memory'")
model = RDF.Model(s)

rawDescription: Parsing large NTriples File Python

description: Parsing large NTriples File Python


code:
import inspect

def mc_me(cls):
    main_locals = inspect.currentframe().f_back.f_locals
    for suffix in ['Super', 'Extra']:
        new_name = cls.__name__ + suffix
        main_locals[new_name] = type(new_name, (), {'name': new_name})
    return cls

rawDescription: Decorator that creates classes

description: Decorator that creates classes


code:
import csv

input = open('in.csv', 'rb')
output = open('out.csv', 'wb')
writer = csv.writer(output)

for read in csv.reader(input):
    writer.writerow([x for x in read if x]) #Removes empty fields and writes into new file

input.close()
output.close()

rawDescription: Replacing characters/delimiters (double comma) in CSV file using python


code:
import subprocess

program1 = subprocess.Popen("program1.py", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while program1.poll() == None:
    cmd_to_send = "prefix " + raw_input() + " suffix"
    program1.stdin.write(cmd_to_send + "\n")

rawDescription: Python wrapper for Python program

description: Python wrapper for Python program


code:
from collections import Counter
Counter('ATCGACAG')
Counter('ACCGACG')

rawDescription: Counting genetic mutations in dictionary using python


code:
from matplotlib import pyplot as plt
import numpy

data = numpy.random.randint(0, 100, size=(100,100))

plt.style.use('ggplot')
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
plt.imshow(data)
ax.grid(True)
for axi in (ax.xaxis, ax.yaxis):
    for tic in axi.get_major_ticks():
        tic.tick1On = tic.tick2On = False
        tic.label1On = tic.label2On = False

plt.show()
plt.savefig('noticks.pdf', format='pdf', bbox_inches='tight')
plt.close()

rawDescription: Remove axis ticks but keep grid using Matplolib / ggplot style


code:
from itertools import izip

reduce(lambda x, y: x * y[0] / y[1], izip(xrange(n - r + 1, n+1), xrange(1, r+1)), 1)

rawDescription: counting combinations and permutations efficiently

description: Counting combinations and permutations efficiently


code:
import os
os
import shutil
shutil

rawDescription: virtualenv does not copy standard modules like shutil and urllib2

description: Virtualenv does not copy standard modules like shutil and urllib2


code:
import sys

with open('file1.txt') as f:
    d = {line.split()[0]: line for line in f if line.strip()}

with open('file2.txt') as f:
    sys.stdout.writelines(d.get(line.strip(), '') for line in f)

rawDescription: Compare two files in perl / python and print matching entries


code:
s = pd.Series(pd.to_datetime('2016-04-21'))
s
np.tile(s, 10)
pd.DataFrame(np.tile(s, 10), columns=['date'])

rawDescription: how to duplicate pandas datetime object

description: Duplicate pandas datetime object


code:
with open('large-file.txt') as the_file:
    for line in the_file:
       result = do_something_with(line)
       print(result)

rawDescription: What is the best way to handle large inputs in python (100 k lines)?


code:
from gi.repository import GObject
from gi.repository import Gtk

class MyOwnWidget(Gtk.DrawingArea, Gtk.Orientable):
    orientation = GObject.Property(type=Gtk.Orientation, default=Gtk.Orientation.VERTICAL)

rawDescription: How to implement GtkOrientable in my custom widget

description: Implement GtkOrientable in my custom widget


code:
dis.dis(lambda: getattr(sys.modules[__name__], 'Foo'))
dis.dis(lambda: globals()['Foo'])
dis.dis(lambda: Foo)

rawDescription: Python: Accessing another class of current module by name


code:
bank_accts = {
    '456': {"Name":"LaVey","Balance":666},
    '123': {"Name":"Adams","Balance":42},
    '999': {"Name":"Zelany","Balance":64},
}

def view_all_accts():
    #########################
    ### 1. Get user input ###
    #########################
    # Get input, lowercase it
    sort = input("How would you like to sort? Please choose by account, name, or balance. ").lower()

    # Check if this is a valid key
    valid_keys = ['account', 'name', 'balance']
    if sort not in valid_keys:
        print("Please choose account, name, or balance!")

        # Ask for input again
        return view_all_accts()

    #######################################
    ### 2. Make a sorted data structure ###
    #######################################
    # The key name (account) is a special case, so handle that first
    if sort == 'account':
        sorted_list = sorted(bank_accts.items())
    # Sort by one of the values
    else:
        # Capitalize the first letter of the sort key
        sort_key = sort.capitalize()

        # Now we can use the key= parameter for sorted()
        sorted_list = sorted(bank_accts.items(), key=lambda v: v[1][sort_key])

    #########################################
    ### 3. Print out this data structure. ###
    #########################################
    for account, data in sorted_list:
        print("Account: %s" % account)
        for k, v in data.items():
            print("  %s: %s" % (k, v))

view_all_accts()

rawDescription: Sorting a Dictionary with multiple Key:values pairs in the original key:value pair


code:
for block in iter(lambda: file_obj.read(4), ""):
  use(block)

rawDescription: How to loop until EOF in Python?

description: Loop until EOF in Python


code:
urlpatterns = patterns("mobile.views",
    url(r'^$', 'something_cool', name='cool'),
    url(r'^mobile-thing/(?P<uuid>[^/]+)/$', 'mobile_thing', name='mobile-thinger'),
)

rawDescription: Regex django url

description: Regex django url


code:
from Tkinter import *

root = Tk()
c = Canvas(root, scrollregion=(0,0,500,500), height=200, width=200)
s = Scrollbar(root, command=c.yview)
c.pack(side=LEFT)
s.pack(side=RIGHT, fill=Y)
c.configure(yscrollcommand=s.set)

c.configure(yscrollincrement='2')
##yscrollincrement - increment for vertical scrolling, in pixels,
##millimeters '2m', centimeters '2c', or inches '2i'

c.create_rectangle(10,10,100,100)
c.create_rectangle(10,200,100,300)

def rollWheel(event):
    direction = 0
    if event.num == 5 or event.delta == -120:
     direction = 1
    if event.num == 4 or event.delta == 120:
     direction = -1
    event.widget.yview_scroll(direction, UNITS)

c.bind('<MouseWheel>', lambda event: rollWheel(event))
c.bind('<Button-4>', lambda event: rollWheel(event))
c.bind('<Button-5>', lambda event: rollWheel(event))

c.focus_set()

root.mainloop()

rawDescription: Python Tkinter canvas.xview units

description: Python Tkinter canvas.xview units


code:
from django.db import models

class Category(models.Model):
    name = models.Charfield(max_length=255)
    # ...

    def __str__(self):
        return self.name

class Item(models.Model):
    category = models.ForeignKey(Category)
    # ...

rawDescription: Django: how can I a create categories field/dropdown menu?


code:
import decimal
decimal.getcontext().rounding = decimal.ROUND_HALF_UP

rawDescription: How to use traditional rounding for decimal numbers in Python (version 3)?

description: Use traditional rounding for decimal numbers in Python (version 3)


code: [i for i, e in enumerate(a) if e != 0]

rawDescription: How do I get a list of indices of non zero elements in a list?

description: Get a list of indices of non zero elements in a list


rawDescription: How do you select just the element from an array in python from a database column

description: Select just the element from an array in python from a database column


code:
for line in old_file:
    stripped_line = line.lstrip()
    # do your matching here against `stripped_line` instead of `line`
    # `line` still contains the original, non-stripped line

rawDescription: How to search and replace a text that has spaces before the text?

description: Search and replace a text that has spaces before the text


code:
n = options.num

while (options.num == 0) or (n > 0):
    print("Hello World")
    n -= 1

rawDescription: while loop, run forever or count down

description: While loop, run forever or count down


rawDescription: How to split script and option at space, if script path can contain escaped spaces?

description: Split script and option at space, if script path can contain escaped spaces


code:
text = driver.find_element_by_xpath("//p[b = 'Postal code:']").text
postal_code = text.split(":")[-1].strip()
print(postal_code)

rawDescription: Using Python & Selenium, how to extract the text from HTML containing the <p> tag?


code:
print("type(path):", type(path))
# <class '_io.TextIOWrapper'>

print("path:", path)
# <_io.TextIOWrapper name='/some/path/file.txt' mode='r' encoding='UTF-8'>

print("path.name:", path.name)
# /some/path/file.txt

print("type(path.name):", type(path.name))
# <class 'str'>

rawDescription: How to get a string from the tkinter filedialog in Python 3?

description: Get a string from the tkinter filedialog in Python 3


code:
import numpy as np
keys = np.array(['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'])
indices = np.array([[4,2,8],[1,7,0]])
keys[indices]

rawDescription: Finding value at indexes present in a 2D array in Python


rawDescription: Regular expression to extract URLs with difficult formatting


rawDescription: How to make a list of numbers out of strings in a list of lists in Python

description: Make a list of numbers out of strings in a list of lists in Python


code:
from __future__ import print_function
import pylast

API_KEY = 'API-KEY-HERE'
API_SECRET = 'API-SECRET-HERE'

username = 'your-user-to-authenticate'
password_hash = pylast.md5('your-password')

# Specfy artist and track name here
artist_name = 'Saori@destiny'
track_name = 'GAMBA JAPAN'

# Authenticate and get a session to last.fm (we're using standalone auth)
client = pylast.LastFMNetwork(api_key = API_KEY, api_secret = API_SECRET,
                              username = username, password_hash = password_hash)

# Get an object representing a specific user
user = client.get_user(username)

# Call get_artist_tracks to retrieve all tracks a user
# has played from a specific artist and filter out all
# playbacks that aren't your track
track_scrobbles = [x for x in user.get_artist_tracks(artist_name)
                   if x.track.title.lower() == track_name.lower()]

# It just so happens that the API returns things in reverse chronological order
# of playtimes (most recent plays first), so you can just take the last item
# in the scrobbled list for the track you want
first_played = track_scrobbles[-1]

# first_played is of type PlayedTrack, which is a named tuple in the lastpy lib

print("You first played {0} by artist {1} on {2}".format(first_played.track.title,
                                                         first_played.track.artist,
                                                         first_played.playback_date))

rawDescription: What is the most efficient way to get the first time a track was played via last.fm API


code:
class Hello(object):
    def __init__(self):
        self.x = None
        self.y = None
        self.z = None
    def is_all_set(self):
        return all(getattr(self, attr) is not None for attr in self.__dict__)

rawDescription: How to check the values in a instance with Python?

description: Check the values in a instance with Python


rawDescription: Python: how to build a dict from plain list of keys and values


code:
def distribution(grades):
    available_grades = [ 'A+','A','A-','B+','B','B-','C+','C','C-','F']
    grade_dict = {}
    for grade in available_grades:
        grade_dict[grade] = 0

    fin = open(grades,'r')
    gradesList = fin.readline().split()
    fin.close()

    for grade in gradesList:
        grade_dict[grade] += 1

    for grade in available_grades:
        print(str(grade_dict[grade]) + ' students got ' + grade)

rawDescription: Python grade distribution function, counting and printing the amount of times a grade occurs


rawDescription: How can I check if an item is in a intermediate table and exclude it?

description: Check if an item is in a intermediate table and exclude it


code:
keys = ['val1', 'val2', 'val3', 'val4']
for line in csv.split('\r\n')[1:]:
    current_line = line.split(',')
    extras = len(current_line) - len(keys)
    newString = ""
    for i in range(len(keys), len(keys) + extras):
        if(i+1 == len(keys) + extras):
            newString += current_line[i]
        else:
            newString += current_line[i] + ","

    list = line.split(',')
    list[len(keys)-1] = probes
    yield dict(zip(keys, [cell.strip() for cell in list]))

rawDescription: argparse - group unknown fields in csv

description: Argparse - group unknown fields in csv


code:
class SuperUserAdminSite( AdminSite ):
    def has_permission(self, request):
        return request.user.is_active and request.user.is_staff and request.user. is_superuser

rawDescription: Overriding admin views - Django

description: Overriding admin views - Django


code:
import locale
locale.locale_alias

rawDescription: How can I list all available windows locales in python console?

description: List all available windows locales in python console


code: print([str(first[i])+second[i] for i in range(len(first))])

rawDescription: How to combine two lists into pairs and then make those pairs one element in list?

description: Combine two lists into pairs and then make those pairs one element in list


code:
from random import Random
myRandom = Random(anewseed)
randomvalue = myRandom.randint(0, 10)

rawDescription: What is the scope of a random seed in Python?


code:
class PySideIRCClient(IRC):
    def __init__(self):
        self.socket_notifiers = {}
        return IRC(self.on_connect, self.on_disconnect, self.on_schedule)

    def on_connect(self, socket):
        notifier = QtCore.QSocketNotifier(socket, QtCore.QSocketNotifier.Read)
        notifier.activated.connect(self.socket_activated)
        self.socket_notifiers[socket] = notifier

    def socket_activated(self, socket):
        self.process_data([socket])

    def on_disconnect(self, socket):
        self.socket_notifiers[socket].setEnabled(False)
        del self.socket_notifiers[socket]

    def on_schedule(self, seconds):
        QtCore.QTimer.singleShot(seconds * 1000, self.process_timeout)

rawDescription: How to have two event loops?

description: Have two event loops


code:
idx = numpy.arange(M)
i = numpy.vectorize(f1)(idx)
j = numpy.vectorize(f2)(idx)
k = numpy.vectorize(f3)(idx)

# you can index arrays with other arrays
# that lets you specify this operation in one line.
newfid[:, i,j,k] = tempfid.T

rawDescription: numpy: efficient execution of a complex reshape of an array

description: Numpy: efficient execution of a complex reshape of an array


code:
import csv
from collections import defaultdict

emails = defaultdict(list)

with open('email.tsv','r') as f:
   reader = csv.reader(f, delimiter='\t')
   for row in reader:
      if row:
         if '@' in row[0]:
           emails[row[1].strip()].append(row[0].strip()+'\n')

for key,values in emails.items():
   with open('output-{}.csv'.format(key), 'w') as f:
       f.writelines(values)

rawDescription: Write key to separate csv based on value in dictionary


code:
import numpy as np
import matplotlib.pyplot as plt

rows, cols = 480, 640
rgb_img = np.zeros((rows, cols, 3), dtype=np.uint8)

rgb_img[:rows//2, :cols//2] = 255

center_slice = rgb_img[1:-1, 1:-1]
left_slice = rgb_img[1:-1, :-2]
right_slice = rgb_img[1:-1, 2:]
up_slice = rgb_img[:-2, 1:-1]
down_slice = rgb_img[2:, 1:-1]

all_equal = (np.all(center_slice == left_slice, axis=-1) &
             np.all(center_slice == right_slice, axis=-1) &
             np.all(center_slice == up_slice, axis=-1) &
             np.all(center_slice == down_slice, axis=-1))

plt.subplot(211)
plt.imshow(rgb_img, interpolation='nearest')
plt.subplot(212)
plt.imshow(all_equal, interpolation='nearest')
plt.show()

rawDescription: Convolve an RGB image with a custon neighbout kernel using Python and Numpy


code: timeStamp = "TIME-" + str(time.time())

rawDescription: Python: Cast time module as string

description: Python: Cast time module as string


code:
# Map the options to functions to handle them.
handlers = {
    'CFLAGS': some_function,
    'CXXFLAGS': other_function,
}

# Loop through each option.
for line in configuration:
    # Get the option and value.
    option, value = line.split('=')
    option = option.strip().upper()
    value = value.strip()

    # Try to find a handler and process the option.
    handler = handlers.get(option)
    if handler:
        handler(option, value)
    else:
        raise Exception('Unknown option.')

rawDescription: How are arguments in a configuration file parsed regardless of position?


code: df_total_results = df_check_feeds.groupby('account_name').apply(lambda x: pd.DataFrame(x['entries'].iloc[0]))

rawDescription: What is a proper idiom in pandas for creating a dataframes from the output of a apply function on a df?


code: [[idx, (i,j)] for idx, (i,j) in enumerate(zip(l1, l2)) if i != j]

rawDescription: compare to lists and return the different indices and elements in python

description: Compare to lists and return the different indices and elements in python


code:
class Point:
  def __init__(self, x, y):
    self.x, self.y = x, y
  def __repr__(self):
    return 'Point(x=%s, y=%s)' % (self.x, self.y)
p = Point(1, 2)
p

rawDescription: Purpose of Python's __repr__

description: Purpose of Python's __repr__


code:
data=[["apple",2],["cake",7],["chocolate",7],["grapes",6]]

for (s,n) in data: print("%s, %d" % (s,n))
# or, an alternative syntax that might help if you have many arguments
for e in data: print("%s, %d" % tuple(e))

rawDescription: Printing nested list as string for display


code:
class JsonIterator(object):
    def __init__(self,folder):
        self.root = os.path.join(os.getcwd(), folder)
        self.fis = [fi for fi in os.listdir(folder) if "lyrics" in fi]

    def __iter__(self):
        for fi in self.fis:
            with open(os.path.join(self.root, fi)) as f:
                obj = json.load(f)
            yield obj

rawDescription: Yield & closing file objects properly

description: Yield & closing file objects properly


code: browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')]

rawDescription: Python - The request headers for mechanize


code:
class CustomToolbar(NavigationToolbar2TkAgg):
    def _Button(self, text, file, command, extension='.ppm'):
        img_file = os.path.join(matplotlib.rcParams['datapath'], 'images', file + extension)
        im = Tk.PhotoImage(master=self, file=img_file)
        # Do stuff with im here
        b = Tk.Button(
            master=self, text=text, padx=2, pady=2, image=im, command=command)
        b._ntimage = im
        b.pack(side=Tk.LEFT)
        return b

rawDescription: Change NavigationToolbar size of matplotlib in Tkinter


code:
import struct
from cStringIO import StringIO

def get_image_info(data):
    """
    Return (content_type, width, height) for a given img file content
    no requirements
    """
    data = str(data)
    size = len(data)
    height = -1
    width = -1
    content_type = ''

    # handle GIFs
    if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
        # Check to see if content_type is correct
        content_type = 'image/gif'
        w, h = struct.unpack("<HH", data[6:10])
        width = int(w)
        height = int(h)

    # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
    # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
    # and finally the 4-byte width, height
    elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
          and (data[12:16] == 'IHDR')):
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[16:24])
        width = int(w)
        height = int(h)

    # Maybe this is for an older PNG version.
    elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[8:16])
        width = int(w)
        height = int(h)

    # handle JPEGs
    elif (size >= 2) and data.startswith('\377\330'):
        content_type = 'image/jpeg'
        jpeg = StringIO(data)
        jpeg.read(2)
        b = jpeg.read(1)
        try:
            while (b and ord(b) != 0xDA):
                while (ord(b) != 0xFF): b = jpeg.read
                while (ord(b) == 0xFF): b = jpeg.read(1)
                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                    jpeg.read(3)
                    h, w = struct.unpack(">HH", jpeg.read(4))
                    break
                else:
                    jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                b = jpeg.read(1)
            width = int(w)
            height = int(h)
        except struct.error:
            pass
        except ValueError:
            pass

    return content_type, width, height

rawDescription: How can I determine type and size of common image types in Python?

description: Determine type and size of common image types in Python


code:
MyButton1 = Button(master, text="BUTTON1", width=10, command=callback)
MyButton1.grid(row=0, column=0)

MyButton2 = Button(master, text="BUTTON2", width=10, command=callback)
MyButton2.grid(row=1, column=0)

MyButton3 = Button(master, text="BUTTON3", width=10, command=callback)
MyButton3.grid(row=2, column=0)

rawDescription: Setting the position on a button in Python?


code:
import pytz as tz
from datetime import datetime as dt
CT = tz.timezone('America/Chicago')
indep_day = dt(2010, 7, 4, 0, 1, 1)
bar = CT.localize(indep_day, is_dst=None)
bar.tzname()
christmas = dt(2010, 12, 25, 0, 1, 1)
foo = CT.localize(christmas, is_dst=None)
foo.tzname()

rawDescription: How to get the common name for a pytz timezone eg. EST/EDT for America/New_York

description: Get the common name for a pytz timezone eg. EST/EDT for America/New_York


code:
from urllib.parse import urlparse  # urlparse.urlparse on Python 2

params = urlparse(request.path).params

rawDescription: How to deal with params in URL schema in Django application

description: Deal with params in URL schema in Django application


code:
for x in df['EVENT_CODE'].unique():
       df1 = df[df['EVENT_CODE'] == x]
       c = pd.DataFrame(columns=df1.columns)
       for file in df1['filename']:
           d = pd.read_csv(str(file))
           c = c.append(d,ignore_index=True)

rawDescription: iterating over a group-by result of pandas dataframe and operate on each group

description: Iterating over a group-by result of pandas dataframe and operate on each group


code:
from docx import Document

document = Document('custom_styles.docx')
table = document.add_table(1, 2, style='CustomTable')
table.cell(0,0).text = 'Left Text'
table.cell(0,1).text = 'Right Text'
document.save('new_document_name.docx')

rawDescription: python docx align both left and right on same line

description: Python docx align both left and right on same line


code:
import bisect
from collections import Counter
Counter(x[bisect.bisect_left(x, item)] for item in y)

rawDescription: How to group / count list elements by range

description: Group / count list elements by range


rawDescription: How to connect to a mongoDB

description: Connect to a mongoDB


rawDescription: how to subset pandas dataframe on a condition

description: Subset pandas dataframe on a condition


code: MY_SETTING = os.environ.get('MY_ENV_VAR', 'my_default')

rawDescription: Is there a way to put local_settings.py to Heroku bypassing Git?


code:
import string
'(123) 456-7890'.translate(string.maketrans('', ''), '-(), ')

rawDescription: What's the Python2.5 equivalent of Python2.6 translate with None as first param?


code:
import sys
sys.prefix
sys.exec_prefix

rawDescription: Path of current Python instance?

description: Path of current Python instance


code:
import io
from email.mime.image import MIMEImage

# ... make some image

outbuf = io.StringIO()
image.save(outbuf, format="PNG")
my_mime_image = MIMEImage(outbuf.getvalue())
outbuf.close()

rawDescription: attaching an image (or object) from memory to an email in python

description: Attaching an image (or object) from memory to an email in python


code:
def microtime(dt):
    time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0

rawDescription: Python get micro time from certain date

description: Python get micro time from certain date


code:
from pandas.tseries.offsets import DateOffset

end = datetime.datetime(2018 , 6, 1)
start = datetime.datetime(2016 ,2, 8)
#Get the range of months to cover
months = (end.year - start.year)*12 + end.month - start.month
#The frequency of periods
period = 6 # in months

pd.DatetimeIndex([end - DateOffset(months=e) for e in range(0, months, period)][::-1]).insert(0, start)

rawDescription: Pandas date_range starting from the end date to start date


code:
import re
s = "1S20M1I9M2D120M"
sum(int(x) for x in re.findall(r'\d+(?=[MI])', s))
sum(int(m.group()) for m in re.finditer(r'\d+(?=[MI])', s))

rawDescription: Python String Manipulation (SUM values)

description: Python String Manipulation (SUM values)


code:
myDict = None
get_myDict = lambda: myDict or {}

get_myDict()

rawDescription: Returning a dictionary based on a condition


code:
def is_foo(user):
   if user.is_authenticated() and user.foo :
       return True

rawDescription: How can I modify Django's login_required decorator on a custom Pinax installation?

description: Modify Django's login_required decorator on a custom Pinax installation


rawDescription: Quick way to replace all occurences of a value in a pandas data frame with NA


rawDescription: Using Regex to find words with characters that are the same or that are different


code:
class MySpider(scrapy.Spider):
    name = 'myspider'
    custom_settings = {'REDIRECT_ENABLED': True}

rawDescription: Difference between turning off the Middleware and disabling it?


code: block_future_res = future_res.result()

rawDescription: Cassandra python driver execute_async with callback not working as expected


code:
import MySQLdb
import os
import datetime

con = MySQLdb.connect(host='localhost', user='root', passwd='password', db='test')
cur = con.cursor()

cur.execute("SHOW TABLES")
data = ""
tables = []
for table in cur.fetchall():
    tables.append(table[0])

for table in tables:
    data += "DROP TABLE IF EXISTS `" + str(table) + "`;"

    cur.execute("SHOW CREATE TABLE `" + str(table) + "`;")
    data += "\n" + str(cur.fetchone()[1]) + ";\n\n"

    cur.execute("SELECT * FROM `" + str(table) + "`;")
    for row in cur.fetchall():
        data += "INSERT INTO `" + str(table) + "` VALUES("
        first = True
        for field in row:
            if not first:
                data += ', '
            data += '"' + str(field) + '"'
            first = False

        data += ");\n"
    data += "\n\n"

now = datetime.datetime.now()
filename = str(os.getenv("HOME")) + "/backup_" + now.strftime("%Y-%m-%d_%H:%M") + ".sql"

FILE = open(filename,"w")
FILE.writelines(data)
FILE.close()

rawDescription: How can I dump a MySQL database without using mysqldump in Python

description: Dump a MySQL database without using mysqldump in Python


code: TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'home', 'static'), )

rawDescription: TemplateDoesNotExist at /home/ - But yes, it's in there


code:
from google.appengine.ext import webapp
import json

class Handler(webapp.RequestHandler):
    def post(self):

        # Convert JSON from the request to Python objects.
        data = json.loads(self.request.body)

        # For your sample input, data will be a list of dicts.
        for person in data:
            name = person['name']
            value = person['value']

rawDescription: retrieve data from post requests in the form of JSON structure

description: Retrieve data from post requests in the form of JSON structure


code:
mydata = MyData.query()
mydata = mydata.filter(...)
# the order shouldn't matter, unless you want to make sure that property exists.
# mydata = mydata.order(MyData.added)
mydata = mydata.fetch(100, keys_only=True)
tasks = [taskqueue.Task(url='/worker', params={'key': key.urlsafe()}) for key in mydata]
taskqueue.Queue('default').add(tasks)

rawDescription: How to pass NDB data to task queue?

description: Pass NDB data to task queue


rawDescription: Closing file after converting xml to csv


code: obs = np.reshape(im, (-1, im.shape[-1]))

rawDescription: Flattening of numpy array

description: Flattening of numpy array


code:
from bokeh.plotting import figure, output_file, show
from bokeh.models.formatters import TickFormatter

x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y = [10**xx for xx in x]

output_file("log.html")

class MyTickFormatter(TickFormatter):
    __implementation__ = """
        Model = require "model"

        class MyTickFormatter extends Model
          type: 'MyTickFormatter'

          doFormat: (ticks) ->
            return ("#{ Math.log10(tick) }" for tick in ticks)

        module.exports =
          Model: MyTickFormatter
    """

# create a new plot with a log axis type
p = figure(plot_width=400, plot_height=400,
           y_axis_type="log", y_range=(10**-1, 10**4))

p.line(x, y, line_width=2)
p.circle(x, y, fill_color="white", size=8)

# use the custom TickFormatter
p.yaxis[0].formatter = MyTickFormatter()

show(p)

rawDescription: Formatting log axis labels with proper superscripts in Bokeh


code:
import Tkinter as tk
from Tkconstants import *
r=tk.Tk()

def set_aspect(content_frame, pad_frame, aspect_ratio):
    # a function which places a frame within a containing frame, and
    # then forces the inner frame to keep a specific aspect ratio

    def enforce_aspect_ratio(event):
        # when the pad window resizes, fit the content into it,
        # either by fixing the width or the height and then
        # adjusting the height or width based on the aspect ratio.

        # start by using the width as the controlling dimension
        desired_width = event.width
        desired_height = int(event.width / aspect_ratio)

        # if the window is too tall to fit, use the height as
        # the controlling dimension
        if desired_height > event.height:
            desired_height = event.height
            desired_width = int(event.height * aspect_ratio)

        # place the window, giving it an explicit size
        content_frame.place(in_=pad_frame, x=0, y=0,
            width=desired_width, height=desired_height)

    pad_frame.bind("<Configure>", enforce_aspect_ratio)

pad_frame = tk.Frame(borderwidth=0, background="bisque", width=200, height=200)
pad_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=20)
content_frame=tk.Frame(r,borderwidth=5,relief=GROOVE, background="blue")
tk.Label(content_frame,text='content').pack()
set_aspect(content_frame, pad_frame, aspect_ratio=2.0/1.0)
r.rowconfigure(0, weight=1)
r.columnconfigure(0, weight=1)

r.mainloop()

rawDescription: Resizing Tkinter Frames with fixed aspect-ratio


rawDescription: Masking between Pandas dataframes where index doesn't match


code:
import re

sample = 'foo.apples'
data_file = open("file1.py", "r")
out_file = open("file2.txt", "w")
within_def = False
def_indent = 0

for line in data_file:
    def_match = re.match(r'(\s*)def\s+start\s*\(', line)  # EDIT: fixed regex
    if def_match and not within_def:
        within_def = True
        def_indent = len(def_match.group(1))
    elif within_def and re.match(r'\s{%s}\S' % def_indent, line):
        within_def = False

    if within_def and sample in line:
        out_file.writelines(line)

out_file.close()
data_file.close()

rawDescription: Search for a string with in a module in a python file using Python


code:
self.fields['starttime'] = forms.TimeField(
                            required=True,
                            label='Start Time',
                            input_formats=['%I:%M %p'],
                            widget=forms.TimeInput(format='%I:%M %p'))

rawDescription: How to Render Django Forms.TimeField in 12h Format in Template?


code:
from collections import OrderedDict

dictionnary = OrderedDict(
    sorted(
        {'a': 3, 'b': 1.2, 'c': 1.6, 'd': 3.88, 'e': 0.72
         }.items(), key=lambda x:x[1], reverse=True))

rawDescription: Outputting dictionary values by min/max value


code: next(y for y in (f(x) for x in my_list) if y != 0)

rawDescription: Generator expression including conditionnal test without calling a function twice?


code:
import maya.cmds as cmds

pathOfFiles = "/path/to/folder/containing/objs/"
fileType = "obj"

files = cmds.getFileList(folder=pathOfFiles, filespec='*.%s' % fileType)
if len(files) == 0:
    cmds.warning("No files found")
else:
    for f in files:
        cmds.file(pathOfFiles + f, i=True)

rawDescription: Importing OBJ file to maya scene (MEL/Python)


code:
node.xpath("//t:assets/t:asset[@type='full']/t:file_name/text()",
        namespaces={'t':'http://apple.com/itunes/importer'})

rawDescription: Find XPATH with namespace based on attribute element


code: password = hash.split(':')[1]

rawDescription: Python, Using regex to read a password

description: Python, Using regex to read a password


code:
# env.py
_src = ''
_html = ''

def set_path_srcfile(path_srcfile):
    global _src
    _src = path_srcfile

def get_path_srcfile():
    return _src

...

rawDescription: Accessing class instance from another module (Python)


code:
ax = pylab.subplots()
ax.set_yticklabels(y_labels)
ax.set_xticklabels(x_labels)

rawDescription: How to plot rownames and column names for a heatmap with matplotlib?

description: Plot rownames and column names for a heatmap with matplotlib


code:
from collections import MutableSequence
def multiply(list_):
    for index, item in enumerate(list_):
        if isinstance(item, MutableSequence):
            multiply(item)
        else:
            list_[index] *= 2

rawDescription: Python: Iterating lists with different amount of dimensions, is there a generic way?


code:
for data_chunk in iter(lambda: data.read(1048576), ''):
    if not rpc_srv.chunk_upload(tf_uuid, data_chunk):
        raise Exception('Failed to upload data.')

rawDescription: cStringIO, reading bytes in chunks until EOF?

description: CStringIO, reading bytes in chunks until EOF


code:
@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], path, as_attachment=True)

rawDescription: How to capture a path in a url to serve files?

description: Capture a path in a url to serve files


code:
def add_to_dict(d, kvlist):
    out = []
    for key, value in kvlist:
        if key in d:
           out.append((key, d[key]))
        d[key] = value
    return out

d = { 'a': 0, 'b': 4 }
add_to_dict(d, [('a', 2), ])
print(d)

rawDescription: I am having trouble with a python tutorial for updating dictionaries. I can't figure it out


code:
import binascii
import struct
import array
x = binascii.unhexlify('b62e000052e366667a66408d')
y = array.array('h', x)
y.byteswap()
s = struct.Struct('<Id')
print(s.unpack_from(y))

# (46638, 943.2999999994321)

rawDescription: reorder byte order in hex string (python)

description: Reorder byte order in hex string (python)


code:
from module import some_function
class SomeClass:
    class_function = staticmethod(some_function)

rawDescription: python: Use a module function as a static method

description: Python: Use a module function as a static method


rawDescription: Reading an integer string in the form of xxx,yyy,zzz with python


code:
COLUMN_VARIABLES = ['provider', 'language','subtype']
data = {}

for variable in COLUMN_VARIABLES:
    data[variable] = node.xpath("//%s/text()"%variable)[0]

rawDescription: Define a long list of variables in python


code:
class Car(models.Model):
    engine_status =  models.CharField(max_length=256, default='inactive')

class CarModification(models.Model):
    CHOICES = (
        ('active', 'Active'),
        ('inactive', 'Inactive')
        )
    engine_status = models.CharField(max_length=256, default='inactive', choices=CHOICES)
    car = models.ForeignKey(Car, related_name='modifications')

@receiver(post_save, sender=CarModification)
def pre_save_handler(sender, **kwargs):
    """after saving CarModification, change car's engine_status"""
    instance = kwargs.get('instance')
    if instance.car_id:
        current_car = Car.objects.filter(id=instance.car_id)[0]
        current_car.engine_status = instance.engine_status
        current_car.save()

rawDescription: Use different model's field with the same value in Django


code: df = df[df.columns[df.columns!='values']].join(s, on='keys')

rawDescription: Python pandas join on with overwrite

description: Python pandas join on with overwrite


code:
list_ = [0, 3.5, 5.8, 6.2, 88]
item = 4.4
bisect.bisect_left(list_, item)

rawDescription: Fastest way to find which two elements of a list another item is closest to in python


rawDescription: Python / Pandas running total

description: Python / Pandas running total


code: rows = soup.findAll('tr')[4::5]

rawDescription: Getting the nth element using BeautifulSoup


code:
class IntroView(generic.DetailView):
    model = Book
    template_name = 'books/intro.html'

    def get_context_data(self, **kwargs):
        context = super(IntroView, self).get_context_data(**kwargs)
        context['symbol_list'] = Symbol.objects.all().order_by('name')
        return context

rawDescription: Django: passing multiple values into the dictionary of the render method


code:
import copy

foo = copy.deepcopy(bar)

rawDescription: a = b edit a without editing b

description: A = b edit a without editing b


rawDescription: Regex separate urls in text that has no separators


code:
## Gather the address components in groups, removing any that are None
address_parts = filter(None, [
    model_obj.address_1,
    model_obj.address_2,
    u', '.join(filter(None, [model_obj.address_city, model_obj.state])),
    model_obj.zip,
])

## In the template, join the address groups
{{ address_parts|join:"<br>" }}

rawDescription: Django: How to nicely format an address in a template without knowing how much information is available?


code:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

points = np.random.multivariate_normal([0, 0], [[1, 2], [2, 20]], size=1000)

plt.plot([-3, 3],[0,60])

ax = sns.kdeplot(points, shade=True)
ax.collections[0].set_alpha(0)

plt.show()

rawDescription: Change image limits of seaborn kdeplot

description: Change image limits of seaborn kdeplot


rawDescription: How use Scrapy encodage

description: How use Scrapy encodage


code:
parser = ArguementParser()
sp = parser.add_subparsers(dest='cmd')

sp.add_parser('about')

spp = sp.add_parser('load', help='report content of a database')
spp.add_argument('database')
spp.add_argument('--pattern', ...)
spp.add_argument('--less', ...)
spp.add_argument('--more', ...)

spp = sp.add_parser('render', help='render text into a database')
spp.add_argument('text')
spp.add_argument('--append',...)

rawDescription: Is there an other way to parse args with groups?


code: re_generator = re.compile('<meta name="generator" content="(.*?)" /?>', re.IGNORECASE)

rawDescription: Detecting blog or forum software using python?


rawDescription: tkinter entry bg and state

description: Tkinter entry bg and state


code:
# grow the y axis down by 0.05
ax.set_ylim(1.35, 1.8)
# expand the x axis by 0.5 at two ends
ax.set_xlim(-0.5, len(labels)-0.5)

rawDescription: Space between Y-axis and First X tick

description: Space between Y-axis and First X tick


code:
import subprocess

text = "es ist also ..."
tt = subprocess.Popen('treetagger/cmd/tree-tagger-german-utf8',
                      stdout=subprocess.PIPE,
                      stderr=subprocess.PIPE,
                      stdin=subprocess.PIPE)
tagged, stderr = tt.communicate(txt)

rawDescription: Suppress print to console with os.popen? - Python


code: a[:] = map(lambda x: -x, a)

rawDescription: Modify a large list without any loops in python


code:
def solveJosephus(specifics):
    people = [int(x) for x in range(1,int(specifics[0])+1)]
    killPosition = int(specifics[1])
    positionCounter = 0
    sorted = False

    while not sorted:
        if len(people) == 1:
            print(people[0]) # Pyschologically scarred Winner!
            sorted = True
        for person in people[:]: #Make copy of iterating list
            positionCounter += 1
            if positionCounter == killPosition:
                print(person)
                people.remove(person)
                positionCounter = 0 #Important! 0 != 1

solveJosephus(raw_input().split())

rawDescription: What is going wrong inside of my loop?

description: What is going wrong inside of my loop


code:
a = [4, 8, 0, 1, 5]

m = min(i for i in a if i > 0)

print("Position:", a.index(m))
print("Value:", m)
# Position: 3
# Value: 1

rawDescription: Find min value in array > 0

description: Find min value in array > 0


code:
from struct import *
# Two integers to a floating point
i1 = 0xC3F5
i2 = 0x4840
f = unpack('f',pack('>HH',i1,i2))[0]

# Floating point to two integers
i1, i2 = unpack('>HH',pack('f',3.14))

rawDescription: Python: convert 2 ints to 32 float

description: Python: convert 2 ints to 32 float


code:
class FooSingleton(object):
    class_var = "foo"

def func1():
    FooSingleton.class_var = "bar"

def func2():
    print(FooSingleton.class_var)

rawDescription: How do I use the same variable in one function with another function, without making that variable Global?

description: Use the same variable in one function with another function, without making that variable Global


rawDescription: Python Regex String

description: Python Regex String


code:
# Create Image
"""img = gimp.Image(cwidth * 10, cheight * 10, RGB)
img.disable_undo()

# Save the current foreground color:
pdb.gimp_context_push()

# Set the text color & background color
gimp.set_foreground(color)
gimp.set_background(0, 0, 0)

# Create All Layers & Position Accordingly
for i in range(char_begin, char_end):
    string = '%c' % i
    offset = i - char_begin

    x_pos = offset * cwidth
    y_pos = offset * cheight

    text_layer = pdb.gimp_text_fontname(img, None, x_pos, y_pos, string, -1, False, size, PIXELS, font)

    gimp.progress_update(float(offset) / float(num_chars))

pdb.gimp_image_flatten(img)

img.enable_undo()

# Create a new image window
gimp.Display(img)
# Show the new image window
gimp.displays_flush()

# Restore the old foreground color:
pdb.gimp_context_pop()"""

rawDescription: Plugins usually don't work, how do I debug?


code:
import matplotlib.pyplot as plt
import time
import threading
import random

data = []

# This just simulates reading from a socket.
def data_listener():
    while True:
        time.sleep(1)
        data.append(random.random())

if __name__ == '__main__':
    thread = threading.Thread(target=data_listener)
    thread.daemon = True
    thread.start()
    #
    # initialize figure
    plt.figure()
    ln, = plt.plot([])
    plt.ion()
    plt.show()
    while True:
        plt.pause(1)
        ln.set_xdata(range(len(data)))
        ln.set_ydata(data)
        plt.draw()

rawDescription: Can you plot live data in matplotlib?

description: Plot live data in matplotlib


code:
class ModelName(models.Model):
    field = models.CharField(max_length=200)

    @property
    def field1(self):
        return self.field[10:11]

    @property
    def field2(self):
        return self.field1

rawDescription: Refer to a model method within method in Django 1.5


code:
connector = aiohttp.TCPConnector(share_cookies=True)

response1 = yield from aiohttp.request('get', url1, connector=connector)
body1 = yield from response1.read_and_close()
response2 = aiohttp.request('get', url2, connector=connector)
body2 = yield from response2.read_and_close()

rawDescription: Detect http response encoding with aiohttp


code: dictionary = dict([(List[i], List[i+1]) for i in range(0, len(List), 2)])

rawDescription: How to get value on a certain index, in a python list?

description: Get value on a certain index, in a python list


code: df.div(df.sum(axis=1), axis=0)

rawDescription: Normalizing a pandas DataFrame by row

description: Normalizing a pandas DataFrame by row


code:
@app.route('/')
def aws_api_route_puppet_apply(ip=None):
    def generate():
        for row in somemethod(var1,var2,var3):
            yield row + '\n'
    return Response(generate(),  mimetype='application/json')

rawDescription: Flask Stream Output Of Function To Browser


code:
from subprocess import check_call as x

x(r'c:\myfiles\evapo.exe inputs.prj')

rawDescription: run an executable using wexpect

description: Run an executable using wexpect


code:
present = ['foo', 'bar', 'baz']
absent = ['spam', 'eggs']
for line in options:
    if all(opt in line for opt in present) and all(
           opt not in line for opt in absent):
       ...

rawDescription: Using iterator over a list within the if statement in Python


code:
cumsumpi = t(apply(pi, 1, cumsum));
u = runif(nrow(cumsumpi));

max.col((cumsumpi > u) * 1, "first")

rawDescription: Python bisect.bisect() counterpart in R?

description: Python bisect.bisect() counterpart in R


code:
values = {
        'order_line_id': order.id,
        'product_id': product.id,
}
if field == 0:
    values['new_line'] = line.id

rawDescription: How to eliminate redundancy when creating variants of a dictionary

description: Eliminate redundancy when creating variants of a dictionary


code:
import os
import signal
os.kill(os.getppid(), signal.SIGHUP)

rawDescription: How to Exit Linux terminal using Python script?

description: Exit Linux terminal using Python script