code:
import re

def get_context(text, w, left, right):
    all_contexts = []
    for i in range(len(text)):
        if re.match(w,text[i], 0):
            if i < left:
                context_left = text[:i]
            else:
                context_left = text[i-left:i]
            if len(text) < (i+right):
                context_right = text[i:]
            else:
                context_right = text[i:(i+right+1)]
            context = context_left + context_right
            all_contexts.append(context)
    return all_contexts

text = ['Python', 'is', 'dynamically', 'typed', 'language',
        'Python', 'functions', 'really', 'care', 'about', 'what',
        'you', 'pass', 'to', 'them', 'but', 'you', 'got', 'it', 'the',
        'wrong', 'way', 'if', 'you', 'want', 'to', 'pass', 'one',
        'thousand', 'arguments', 'to', 'your', 'function', 'then',
        'you', 'can', 'explicitly', 'define', 'every', 'parameter',
        'in', 'your', 'function', 'definition', 'and', 'your',
        'function', 'will', 'be', 'automagically', 'able', 'to', 'handle',
        'all', 'the', 'arguments', 'you', 'pass', 'to', 'them', 'for', 'you']

text.insert(0, "START")
text.append("END")

d = {}
for w in set(text):
    d[w] = get_context(text,w,2,2)

rawDescription: Finding word context with regular expressions


code:
class Check(models.Model):
    check_type = models.CharField(max_length=10, editable=False)
    type = models.CharField(max_length=10, null=True, choices=TYPES)
    method = models.CharField(max_length=25, choices=METHODS)
    'More fields.'

    def __init__(self, *args, **kwargs):
        super(Check, self).__init__(*args, **kwargs)
        if self.check_type:
            map = {'TypeA': Check_A,
                'TypeB': Check_B,
                'TypeC': Check_C}
            self.__class__ = map.get(self.check_type, Check)

    def run(self):
        'Do the normal stuff'
        pass

class Check_A(Check):
    class Meta:
        proxy = True

    def run(self):
        'Do something different'
        pass

class Check_B(Check):
    class Meta:
        proxy = True

    def run(self):
        'Do something different'
        pass

class Check_C(Check):
    class Meta:
        proxy = True

    def run(self):
        'Do something different'
        pass

rawDescription: Creating instances of Django proxy models from their base class


code:
import numpy as np
x = np.arange(-1,1,0.1)
print(x)
type(x[0])
print(x.tolist())
type(x.tolist()[0])

rawDescription: What kind of number 9.00000000e-01 is?

description: What kind of number 9.00000000e-01 is


code:
try:
    from mptt.fields import TreeForeignKey
    from mptt.models import MPTTModel
except ImportError:
    raise ImportError(
        'You are using the using the `foo` app which requires the `django-mptt` module.'
        'Be sure to add `mptt` to your INSTALLED_APPS for `foo` to work properly.'
)

rawDescription: How to include prerequisite apps in INSTALLED_APPS

description: Include prerequisite apps in INSTALLED_APPS


rawDescription: Index contains duplicate entries after drop_duplicates called


code:
def is_merged(row, column):
    for cell_range in sheet.merged_cells:
        row_low, row_high, column_low, column_high = cell_range
        if row in xrange(row_low, row_high) and column in xrange(column_low, column_high):
            return (True, row_high-1)
    return False

rawDescription: End of merged cells in Excel with Python


code:
req_url = ("{}origin={}&destination={}&waypoints=optimize:true|{}|{}"
              "&sensor=false&language=zh-TW".format(
                  url, quote(a), quote(b), quote(c), quote(d)))

print(req_url)
direction = urlopen(req_url).read().decode('utf-8')

with open('result.txt', 'w') as ii:
    ii.write(direction.encode('utf-8'))

rawDescription: Google direction API: not to translate addresses into English


code:
import unittest
from unittest import mock

def fn(entries):
    pass

def use_fn(entries, convert=lambda x: x):
    entries = (convert(entry) for entry in entries)
    entries = fn(entries)
    entries = fn(entries)

class MyTestCase(unittest.TestCase):

    def assertEqualGenerators(self,a,b):
        try:
            for x,y in zip(a,b):
                self.assertEqual(x, y)
        except TypeError:
            self.assertEqual(a, b)

    @mock.patch("mock_generators.fn")
    def test_use_fn(self, mock_fn):
        mock_fn.return_value = 'baz'
        entries = ['foo', 'bar']
        use_fn(entries)
        calls = [mock.call((entry for entry in entries)),
                    mock.call('baz')]
        self.assertEqual(len(calls), mock_fn.call_count)
        for a,b in zip(mock_fn.call_args_list,calls):
            self.assertEqualGenerators(a[0],b[0])

if __name__ == '__main__':
    unittest.main()

rawDescription: compare generator objects within mock.assert_has_calls

description: Compare generator objects within mock.assert_has_calls


code:
import subprocess
myfile = 'data'
sort = subprocess.Popen(['sort', '--key=1,2', myfile],
    stdout=subprocess.PIPE)
for line in sort.stdout:
    your_code_here
sort.wait()
assert sort.returncode == 0, 'sort failed'

rawDescription: Best way to pipe output of Linux sort

description: Pipe output of Linux sort


code:
import urllib
import cv

urllib.urlretrieve("http://192.168.0.10:8080/shot.jpg", "foto.jpg")
imagen=cv.LoadImage('foto.jpg')
cv.ShowImage('Image',imagen)

rawDescription: OpenCv using an IP camera photo

description: OpenCv using an IP camera photo


code:
import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        hbox = QtGui.QHBoxLayout(self)
        left = QtGui.QFrame(self)
        left.setFrameShape(QtGui.QFrame.StyledPanel)
        right = QtGui.QFrame(self)
        right.setFrameShape(QtGui.QFrame.StyledPanel)
        splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter.addWidget(left)
        splitter.addWidget(right)
        splitter.setStretchFactor(1, 1)
        splitter.setSizes([125, 150])
        hbox.addWidget(splitter)
        self.setLayout(hbox)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QtGui.QSplitter')
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: Semi-resizable widgets in PyQt

description: Semi-resizable widgets in PyQt


rawDescription: Intercest dataframes in python using pandas


code:
# `idx` is an an array of integer indices that sorts `pdd` in ascending order
idx = np.argsort(pdd)

depth_itp = np.interp([50.0], pdd[idx], depth[idx])

plt.plot(depth, pdd)
plt.plot(depth_itp, 50, 'xr', ms=20, mew=2)

rawDescription: Interpolating a data point on a curve with a negative slope


code:
f1 = open('fg','r')
f2 = open('gs','r')
genera= {}
for i in f1.readlines():
    family,genus = i.strip().split(" ")
    genera[genus] = family

for i in f2.readlines():
    genus,species = i.strip().split(" ")
    print(genera[genus], genus,species)

rawDescription: Iterate two files, compare matching strings in rows, merge matching rows


code:
import curses
oScreen = curses.initscr()
curses.noecho()
curses.curs_set(0)
oScreen.keypad(1)
oScreen.addstr("Woooooooooooooo\n\n",curses.A_BOLD)
while True:
    oEvent = oScreen.getch()
    if oEvent == ord("q"):
        break
curses.endwin()

rawDescription: Python terminal application with interface like nano


code:
class ComeUpWithAGoodName(object):
    def __init__(self, user):
        self.user = user
    def function1(self):
        do_stuff_with(self.user)
    # etc.

rawDescription: best practice for common constant variables

description: Best practice for common constant variables


code:
from tkinter import *
from tkinter.ttk import *

root = Tk()
tree = Treeview(root,selectmode="extended",columns=("A","B"))
tree.pack(expand=YES, fill=BOTH)
tree.heading("#0", text="C/C++ compiler")
tree.column("#0",minwidth=0,width=100, stretch=NO)
tree.heading("A", text="A")
tree.column("A",minwidth=0,width=200, stretch=NO)
tree.heading("B", text="B")
tree.column("B",minwidth=0,width=300)
root.mainloop()

rawDescription: How to change ttk.Treeview column width and weight in Python 3.3

description: Change ttk.Treeview column width and weight in Python 3.3


code:
from django.db.models import Q
Publisher.objects.filter(Q(name__contains="press") | Q(country__contains="U.S.A"))

rawDescription: How to use OR using Django's model filter system?

description: Use OR using Django's model filter system


code:
a = 1
dict1 = dict(id=a)
dict1

rawDescription: replace values in python dictionary using string variables

description: Replace values in python dictionary using string variables


code: __all__ = ['myfunction']

rawDescription: make available only a subset of functions in python package

description: Make available only a subset of functions in python package


code:
uniq_names = {person.name:person for person in people}
uniq_people = uniq_names.values() # use list(unique_names.values()) for Py 3.x

rawDescription: Insert only unique objects into list

description: Insert only unique objects into list


code: [[False], [True], [True], [True]]

rawDescription: Python - Print high if all word-comparisons are true


rawDescription: Check if a directory is a (file system) root


rawDescription: How to drop the index column of DataFrame?

description: Drop the index column of DataFrame


code:
class ERBFilterCoeffs(namedtuple('ERBFilterCoeffs','a b c')):
    """
    this is the doc string for ERBFilterCoeffs
    """

rawDescription: How can I provide Sphinx documentation for a namedtuple (with autodoc)?

description: Provide Sphinx documentation for a namedtuple (with autodoc)


code:
from sqlalchemy.orm import mapper
class ElevationMode(object):
    pass

mapper(ElevationMode, elevation_mode_table)

class ScanModes(db.Model):
    elevations = relationship(ElevationMode)

rawDescription: How do I make a relationship to a classless value in SQLAlchemy?

description: Make a relationship to a classless value in SQLAlchemy


code: itertools.ifilter(lambda e: is_a_nice_element(e, 42), iterable)

rawDescription: How to give extra arguments for the Python itertools.ifilter function?

description: Give extra arguments for the Python itertools.ifilter function


code:
with open('a.txt') as fa, open('b.txt') as fb, open('new.txt', 'w') as fn:
    line_a, line_b = int(next(fa, 0)), int(next(fb, 0))
    while line_a or line_b:
        if not line_b or (line_a and line_a < line_b):
            fn.write("{}\n".format(line_a))
            line_a = int(next(fa, 0))
        else:
            fn.write("{}\n".format(line_b))
            line_b = int(next(fb, 0))

rawDescription: How to merge two files and sort into one file?

description: Merge two files and sort into one file


code:
import itertools
list(itertools.combinations(df.Item, 2))

[('BREAD', 'MILK'),
 ('BREAD', 'DIAPER'),
 ('BREAD', 'BEER'),
 ('MILK', 'DIAPER'),
 ('MILK', 'BEER'),
 ('DIAPER', 'BEER')]

list(itertools.combinations(df.Item, 3))

[('BREAD', 'MILK', 'DIAPER'),
 ('BREAD', 'MILK', 'BEER'),
 ('BREAD', 'DIAPER', 'BEER'),
 ('MILK', 'DIAPER', 'BEER')]

rawDescription: Combination of values in pandas data frame


code:
sorted("asd") == sorted("dsa")
sorted( "asd" ) == sorted( "dsa" )
sorted( "asd" ) == sorted( "dsaf" )
set( "asd" ) == set( "dasf" )
set( "asd" ) == set( "daas" )
set( "asd" ) ^ set( "daf" )

rawDescription: search list for exact match

description: Search list for exact match


code:
import pandas as pd
import matplotlib as mpl
# Set new Backend to Use Seaborn
# mpl.use('Agg')
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import colorsys
import numpy as np

# Working example data:
df = pd.DataFrame([[0.5,0.7,0.4],[.9,.3,.8],[.3,.4,.7]],['A','B','C'])

# Get Color List
N = 3
COL = [colorsys.hsv_to_rgb(x*1.0/N, 0.7, 0.5) for x in range(N)]

im = np.zeros((df.shape[0], df.shape[1], 4))

with sns.axes_style('white'):

    for i, name in enumerate(df.columns):

        # Create cmap
        colors = COL[i]
        cmap = sns.light_palette(colors, input='rgb', reverse=False, as_cmap=True)
        values = np.array(df[name])
        color_indices = (values-np.min(values))/(np.max(values)-np.min(values))
        im[:,i,:] = cmap(color_indices)

im2 = im.copy()
for i, name in enumerate(df.T.columns):
    values = np.array(df.T[name])
    print(values)
    sorting = np.argsort(values)
    print("sorting", sorting)
    im2[i, ::-1, :] = im[i, sorting, :]
plt.imshow(im2, interpolation="nearest")
plt.grid(False)
plt.show()

rawDescription: Plotting sorted heatmap keeping (x,y) value colors


code:
def sieve3(n):
    top = n+1
    sieved = dict.fromkeys(xrange(3,top,2), True)
    for si in xrange(3,top,2):
        if si * si > top:
            break
        if sieved[si]:
            for j in xrange(3*si, top, si*2):
                sieved[j] = False
    return [2] + [pr for pr in xrange(3,top,2) if sieved[pr]]

rawDescription: Finding a Prime Sieve Inconsistency in Python


code:
def change_start_date(dictionary_with_temporal_distribution):
    unsw_mid_year_end_date = datetime.date(2015, 7, 12)
    for k in list(dictionary_with_temporal_distribution['C-STD-B&M-SUM'].keys()):
        dictionary_with_temporal_distribution['C-STD-B&M-SUM'][unsw_mid_year_end_date + timedelta(days=k)] = dictionary_with_temporal_distribution['C-STD-B&M-SUM'][k]
        del dictionary_with_temporal_distribution['C-STD-B&M-SUM'][k]

rawDescription: Change multiple keys from dictionary, while doing timedelta operation in Python


code:
g1 = (3, 4, 5)
g2 = "(3, 4, 5)"
g3 = 3, 4, 5
type(g1)  # <type 'tuple'>
type(g2)  # <type 'str'>
type(g3)  # <type 'tuple'>
g1 == g3  # True
g1 == g2  # False
g2 == g3  # False
g1[0]  # 3, first element of tuple, type: int
g2[0]  # "(", first char of string, type: str

rawDescription: difference between these 3 types of variable assignments

description: Difference between these 3 types of variable assignments


code:
class ReassignList(list):
    @staticmethod
    def iadd(left, right):
        print("Now this works!")
        return list.__iadd__(left, right)
    def __init__(self, *args, **kw):
        list.__init__(self, *args, **kw)
ReassignList.__iadd__ = ReassignList.iadd

rawDescription: Dynamically changing the behavior of __iadd__ and other operators


code:
from datetime import datetime as dt
date_str='12/20/2014 15:25:05 pm'
date_obj = dt.strptime(date_str, '%m/%d/%Y %H:%M:%S %p')
dt.strftime(date_obj, '%m/%d/%Y %I:%M:%S %p')

rawDescription: Date time format conversion in python

description: Date time format conversion in python


rawDescription: How to unpack a Series of tuples in Pandas?

description: Unpack a Series of tuples in Pandas


code:
@property
def NumPosts(self):
    return Posting.objects.filter(textbook__isbn=self.isbn).count()

rawDescription: Django Model Property - Count foreign key for multiple instances of model


code:
import sys

...
sys.stdout.flush()

rawDescription: python print function in real time

description: Python print function in real time


code:
import random
notes = {"raitisu": [{"name": "test"}, {"name": "test1"}],
         "iceyyheart": [{"name": "test"}]}
notes_key = random.choice(notes)
random_dict_list = notes[notes_key]
random_value = random.choice(random_dict_list)["name"]
note = { 'name': random_value }

rawDescription: Python how to choose randomly from a dict


code:
def output(copies, limit):
    for i in range(copies):
        for x in range(limit):
            print (x + 1, end=" ")
        print()  # <----
        # print()  # Add this if you want an empty line

output(copies, limit)

rawDescription: Python, nested loops print on one line, multiple copies


code:
id = "your_id"
array = array.array('f', [...])
data = {id: array}

rawDescription: Adding metadata to existing python objects


code:
fig = plt.figure(figsize=(16,6))
ax0 = fig.add_subplot(121)
ax0.plot(*args0)
ax1 = fig.add_subplot(122)
ax1.plot(*args1)
plt.tight_layout()
plt.savefig('plots.png')

rawDescription: How can I save two plots on a single file in python?

description: Save two plots on a single file in python


code:
class Cache(object):
    def __init__(self):
        self.cache = {}

    def get(self, a, b):
        key = (a,b)

        result = self.cache.get(key, None)
        if result is None:
            result = likelihood(data, a, b)
            self.cache[key] = result

        return result

rawDescription: What is the most pythonic way to conditionally compute?


code:
def game():
   ... # all the code for your game that you posted

if __name__ == "__main__":
   while True:
     game()
     response = int(raw_input('[5] to go out game\nor [9] to restart:'))
     if response != 9:
       break

rawDescription: How to restart the big loop (inside it 2 others small loops)

description: Restart the big loop (inside it 2 others small loops)


code:
from PyQt4 import QtGui

# Create window
class Window(QtGui.QWidget):

    #This block adds features into the window init
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setWindowTitle('Monterey Bay Sea Level Rise')
        self.resize(300, 240)
        self.addWidgets1()

    def addWidgets1(self):

        self.layout = QtGui.QFormLayout()
        self.setLayout(self.layout)

        #Add drop-down list for selecting forecast year

        # You don't need to set to parent of the widgets to self anymore, the
        # layout will set the parent automatically when you add the widgets
        self.year_lbl = QtGui.QLabel("1. Select Forecast Year")
        # self.year_lbl.move(5,0) # Can be removed. The layout takes care of it.
        year = QtGui.QComboBox()
        year.addItem('2030')
        year.addItem('2060')
        year.addItem('2100')
        self.layout.addRow(self.year_lbl, year)

        #Add drop-down list for selecting hazard
        self.hazard_lbl = QtGui.QLabel("2. Select Coastal Hazard")
        self.hazard = QtGui.QComboBox()
        self.hazard.addItem('Rising Tides')
        self.hazard.addItem('Coastal Storm Flooding')
        self.hazard.addItem('Cliff Erosion')
        self.hazard.addItem('Dune Erosion')
        self.hazard.activated[str].connect(self.updateComboboxes)
        self.layout.addRow(self.hazard_lbl, self.hazard)

        #Add drop-down list for inputing model intensity (s1,s2,s3)
        self.intensity_lbl = QtGui.QLabel("3. Select Intensity")
        intensity = QtGui.QComboBox()
        intensity.addItem('Low')
        intensity.addItem('Mid')
        intensity.addItem('High')
        self.layout.addRow(self.intensity_lbl, intensity)

        self.types_lbl = QtGui.QLabel("3. Select type of changes")
        self.types = QtGui.QComboBox()
        self.types.addItem('Long-term')
        self.types.addItem('Storm induced')
        self.layout.addRow(self.types_lbl, self.types)

        self.storm_lbl = QtGui.QLabel("4. Select for stormier")
        self.storm = QtGui.QComboBox()
        self.storm.addItem('No Change')
        self.storm.addItem('Stormier')
        self.layout.addRow(self.storm_lbl, self.storm)

        # show initial state
        self.updateComboboxes()

    def updateComboboxes(self, text=None):
        #if hazard is cliff erosion or dune erosion we want to update the widget
        #... to include wstorm,long_term AND no_change,stormier

        if text is None:
            text = self.hazard.currentText()

        usable = (text == 'Cliff Erosion' or text == 'Dune Erosion')

        if True: # change to False to use enabling/disabling widgets
            # May cause other widgets to be relocated
            self.types_lbl.setVisible(usable)
            self.types.setVisible(usable)
            self.storm_lbl.setVisible(usable)
            self.storm.setVisible(usable)
        else:
            # This option doesn't relocate widgets
            # Also may give additional clue to the uses that this exsits
            self.types_lbl.setEnabled(usable)
            self.types.setEnabled(usable)
            self.storm_lbl.setEnabled(usable)
            self.storm.setEnabled(usable)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    #window.resize(100, 60)
    window.show()
    sys.exit(app.exec_())

rawDescription: pyqt - Automatically update widget on user input

description: Pyqt - Automatically update widget on user input


rawDescription: How to convert a string containing the month's name to an integer?

description: Convert a string containing the month's name to an integer


code:
import sys, os, shutil

def prune(dirpath, exceptions=()):
    for name in os.listdir(dirpath):
        path = os.path.join(dirpath, name)
        if name in exceptions:
            prune(path)
        else:
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)

exceptions = ('dir1', 'dir2', '.dotfile1', '.dotfile2', 'dir3', '.dotdir1')

if __name__ == '__main__':

    root = os.path.join('/home', sys.argv[1], 'parentdir')

    prune(root, exceptions)

rawDescription: shutil.rmtree in mixed hierarchy levels in python

description: Shutil.rmtree in mixed hierarchy levels in python


code: [caller.__closure__[0].cell_contents for caller in callers]

rawDescription: How to get a nested function's namespace in Python?

description: Get a nested function's namespace in Python


code:
df1 = pd.read_csv(StringIO(b), index_col=0, names=['time', 'open', 'high', 'low', 'close', 'volume'], parse_dates=True)
df2 = pd.read_csv(StringIO(a), index_col=0, names=['time', 'open', 'high', 'low', 'close', 'volume'], parse_dates=True)
df1
df2
df2['other_close'] = df1['close']
df2

rawDescription: Python 2.7 and Pandas merge 2 csv files with Forex Data


code:
import matplotlib.pyplot as plt
x = [1890,1900,2000,2010]
y = [6,4,1,9]
stepsize = 10 # Chose your step here
fig, ax = plt.subplots()
ax.bar(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
plt.show()

rawDescription: How to border a bar for particular data aperiod in Python

description: Border a bar for particular data aperiod in Python


code: from bs4 import BeautifulSoup

rawDescription: Using/importing Beautiful Soup 4 without installation


code:
from django.core.management import setup_environ
from yourproject import settings

setup_environ(settings)

from yourproject.app.models import YourModel

rawDescription: DJANGO_SETTINGS_MODULE not importing my model classes


code:
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@id="RegisterButton"]'))).click()
# ...Filling Register form...
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@id="SubmitButton"]'))).click()

# Wait till the modal is no longer visible
wait.until_not(EC.visibility_of_element_located((By.ID, 'confirmWindow')))

wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@id="ApproveButton"]'))).click()

rawDescription: Expected condition: wait until one element clickable while other- dissapeared


code:
n.image = L.HDF5Data(hdf5_data_param={'source': './training_data_paths.txt',
                                      'batch_size': 64},
                     include={'phase': caffe.TRAIN})

rawDescription: Caffe Python API reference?

description: Caffe Python API reference


code:
ax1 = plt.subplot(111)
df[df['gender']=='M'].hist(ax=ax1, color='red', label='M')
df[df['gender']=='F'].hist(ax=ax1, color='blue', label='F')
ax1.legend(loc='best')

rawDescription: How to define colors for histogram in "groupby"?

description: Define colors for histogram in "groupby"


code:
costs = { '1': 1, '2': 2, '3': 3 }
open_set = set( ['1','2'] )
min(open_set,key=lambda x:costs[x])

rawDescription: Python: Finding a minimum value according to a dictionary


code:
import Levenshtein
Levenshtein.distance(songC, songA) # 0
Levenshtein.distance(songC, songB) # 11

rawDescription: Determining how much two strings match

description: Determining how much two strings match


code:
for line in file_reader:  # read in all of your data
    line['calculated_col0'] = line['col1'] * line['col2']
    csv_contents.append(line)  # gather data into a list (of dicts)

rawDescription: Adding columns that contain equations to a csv file in python


code:
from twisted.internet import reactor
from twisted.web.server import Site

from twisted.web.twcgi import FilteredScript

class PhpPage(FilteredScript):
    filter = "/usr/bin/php-cgi"
    #                  ^^^^^^^

    # deal with cgi.force_redirect parameter by setting it to nothing.
    # you could change your php.ini, too.
    def runProcess(self, env, request, qargs=[]):
        env['REDIRECT_STATUS'] = ''
        return FilteredScript.runProcess(self, env, request, qargs)

resource = PhpPage('./hello.php')
factory = Site(resource)

reactor.listenTCP(8880, factory)
reactor.run()

rawDescription: Python twisted render PHP

description: Python twisted render PHP


code: outputFile.write(""" WHERE tableID = '""" + uuid.UUID(parts[-1]) + """'""")

rawDescription: Python converting UUID's from string

description: Python converting UUID's from string


code:
def floatToInt(x):
    return int((x+1.0) * (2**31))

rawDescription: Faster float to int conversion in Python


code:
import ssl
from ftplib import FTP_TLS
ftps = FTP_TLS('127.0.0.1')

## set protocol to SSLv23 to request best version
ftps.ssl_version = ssl.PROTOCOL_SSLv23;

ftps.login()
ftps.prot_p()
ftps.retrlines('LIST')
ftps.quit()

rawDescription: Using TLS1.2 with ftplib in python 2.7.*


code:
sales['PERCENT_2012'] = sales['TOTAL_2012'] / sales['TOTAL_2012'].sum()
sales['CUM_PERCENT_2012'] = sales['PERCENT_2012'].cumsum().round(2)

rawDescription: Pandas floating point issue with cumsum and division


code:
array = [{'a':0,'b':1,'c':2}, {'a':3,'b':4,'c':5}, {'a':6,'b':2,'c':3},]
[y for x in array for y in x.values()]
[x['a'] for x in array]  # Assuming that all dicts have an 'a' key

rawDescription: Return a list of values of dictionaries inside a list


code:
ax=df.set_index('Species').plot(title='Invasive Species')
ax.set_xlabel('Departure Level')
ax.set_ylabel('Percent Occurance')

rawDescription: Multiple Indexes and graphs in Pandas

description: Multiple Indexes and graphs in Pandas


code:
import struct
struct.pack('!Q', 123)

rawDescription: How to convert a number in Python to 8 binary bytes (64-bit long)?

description: Convert a number in Python to 8 binary bytes (64-bit long)


code:
data = { "contentItems" : [
  {
    "userid" : "user1",
    "id" : "uuid1.1",
    "contenttype" : "text/plain",
    "language" : "en",
    "created" : 1393264847000,
    "content": "some text"
  },
  {
    "userid" : "user1",
    "id" : "uuid1.2",
    "contenttype" : "text/plain",
    "language" : "en",
    "created" : 1393263869000,
    "content": "even more"
  },
  {
    "userid" : "user2",
    "id" : "uuid2",
    "contenttype" : "text/plain",
    "language" : "en",
    "created" : 1394826985000,
    "content": "this is a different author"
  }
] }

response = requests.post(
       "https://gateway.watsonplatform.net/personality-insights"+
       "/api/v2/profile", # Or append: "?headers=True",
   auth=("API_USERID", "API_PASSWORD"),
   headers={"Content-Type": "application/json", "Accept": "text/csv"},
   data = json.dumps(data)
)

print("HTTP %d:\n%s" % (response.status_code, response.content))

rawDescription: Can one get multiple results from one API call in IBM Watson?


code:
sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()

rawDescription: How do I write output in same place on the console?

description: Write output in same place on the console


code:
progress_bar_tree_view_column.add_attribute(progress_bar_renderer, 'visible',
    NUMBER_OF_MY_HIDDEN_COLUMN)

rawDescription: Python3 Gtk3+: How to hide a cell of a row


code:
pout,perr = subprocess.Popen(['nmap', '192.168.1.2', '-oX', '-'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

xml_results = pout.read()

rawDescription: Is there any way I can use 'nmap' port scanner, to generate and output result on my Django App


code:
def _get_timestamp(self):
    """Return the timestamp of a user's most recently uploaded avatar."""
    path = settings.USER_AVATAR_DIRECTORY + self._get_dir()
    filenames = [filename for filename in os.listdir(path)
                 if filename.partition('_')[0] == str(self.user_id)]
    filenames.sort(reverse=True)
    return (filenames[0].rpartition('_')[2].partition('.')[0]
            if filenames else None)

rawDescription: Python: Parsing Timestamps Embedded in Filenames


rawDescription: how to split matrix into 4 quadrants in python using numpy

description: Split matrix into 4 quadrants in python using numpy


code:
def height(t):
    if not t.children:
        return 1
    else:
        return max(height(c) for c in t.children) + 1

rawDescription: Finding height of tree without using list


code:
import datetime
q = db.GqlQuery("SELECT * FROM LiveData WHERE timestamp > :1", datetime.datetime.now())

rawDescription: Using localtime in a where clause for GqlQuery


code:
from selenium import webdriver

browser = webdriver.Firefox()
a = "hello"
browser.execute_script("alert('"+a+"');")

rawDescription: Selenium WebDriver on Python. How to use variable created during test in the JavaScript?


code:
#load images
bg_filename = "start.png"
background = pygame.image.load(bg_filename)

#keep looping through
while 1:
    #clear the screen before drawing it again
    screen.fill(0)
    #draw the screen elements
    screen.blit(background, (0,0))
    #update the screen
    pygame.display.flip()
    #loop through the events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                if bg_filename == "start.png":
                    bg_filename = "new.png"
                    background = pygame.image.load(bg_filename)

rawDescription: Not sure why If Statement is not working. (Pygame)


code:
BeautifulSoup('
some text
').findAll()

rawDescription: What does findAll do when it has no argument?


code:
from mrss.feed_burner import get_feed
from _pytest.monkeypatch import monkeypatch

def test_first_feed(self):
    mp = monkeypatch()
    mp.setattr(mrss.version_controller, 'get_version', lambda env: 7)
    mrss_feed = get_feed(env=get_config())
    root = ET.fromstring(mrss_feed)

    self.assertEquals(21, len(programmes))

rawDescription: Python monkeypatch doesn't patch function correctly


code:
x
y = x.ravel().view(dtype=[('idx1', float), ('idx2', float), ('data', float, 3)])
y['idx1']
y['data']
y['data'][1]

rawDescription: How to convert a ndarray to a structured array?

description: Convert a ndarray to a structured array


code:
class win(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self, parent=None)
        self.box = QtGui.QHBoxLayout(self)
        self.setLayout(self.box)
        self.ed1 = QtGui.QTextEdit(self)
        self.ed2 = QtGui.QTextEdit(self)
        self.ed1.keyPressEvent = self.ed2.keyPressEvent
        self.ed1.keyReleaseEvent = self.ed2.keyReleaseEvent
        self.box.addWidget(self.ed1)
        self.box.addWidget(self.ed2)

rawDescription: Problems handling QTextEdit event()

description: Problems handling QTextEdit event()


code:
import hashlib
import os

class Verification(ndb.Model):
    account = ndb.KeyProperty()

    @classmethod
    def create(cls, account):
        verification = cls(
            id=hashlib.sha1(os.urandom(16)).hexdigest(),
            account=account.key,
        ).put()
        return verification.id()

    @classmethod
    def validate(cls, verification_id):
        verification = cls.get_by_id(verification_id)
        account = verification.account.get()
        account.verified = True
        account.put()

rawDescription: Verifying user accounts using email (Google App Engine)


code:
import re
text = "watch-freeseries.mu=lklsflamflkasfmsaldfasmf14792088"
expr = re.compile("watch\-freeseries\.mu.*?(\d{8})")
expr.findall(text)

rawDescription: Extracting a string from a txt file

description: Extracting a string from a txt file


code:
tcs = root.findall('Testcase')
tcs
len(tcs)
r = ET.Element('Root')
r.append(tcs[0])
ET.tostring(r, 'utf-8')

rawDescription: Split one large .xml file in more .xml files (python)


code:
def merge_lists(l):
        s=map(set, l)
        i, n=0, len(s)
        while i < n-1:
                for j in xrange(i+1, n):
                        if s[i].intersection(s[j]):
                                s[i].update(s[j])
                                del s[j]
                                n-=1
                                break
                else:
                        i+=1
        return [sorted(i) for i in s]

rawDescription: Python merge multiple list with intersection


code:
import sys
from PyQt4 import QtCore, QtGui, QtSvg
from PyQt4.QtWebKit import QGraphicsWebView
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    scene = QtGui.QGraphicsScene()
    view = QtGui.QGraphicsView(scene)

    br = QtSvg.QGraphicsSvgItem("C:\your_interactive_svg.svg").boundingRect()

    webview = QGraphicsWebView()
    webview.load(QtCore.QUrl("C:\your_interactive_svg.svg"))
    webview.setFlags(QtGui.QGraphicsItem.ItemClipsToShape)
    webview.setCacheMode(QtGui.QGraphicsItem.NoCache)
    webview.resize(br.width(), br.height())

    scene.addItem(webview)
    view.resize(br.width()+10, br.height()+10)
    view.show()
    sys.exit(app.exec_())

rawDescription: pyQt with interactive SVG images

description: PyQt with interactive SVG images


code:
import csv
with open(filename,'r') as fin, open (outputfile,'w') as fout:
    writer = csv.writer(fout, delimiter=',')
    for row in csv.reader(fin, delimiter=','):
        if int(row[1]) >=1 and int(row[2]) >= 1:
             writer.writerow(row)

rawDescription: How to filter rows from a csv file based on threshold numerical values using python

description: Filter rows from a csv file based on threshold numerical values using python


code:
from random import uniform

vals = [11, 23, 39]
prob = [0.25, 0.30, 0.45]
cdf = [sum(prob[0:i+1]) for i in xrange(3)]

def onetrial(vals, cdf):
    u = uniform(0, 1)
    for i in range(3):
        if u <= cdf[i]:
            return vals[i]

rawDescription: For loop, repetitive calculation in Python


code:
import pandas as pd
import numpy as np
from io import StringIO

df = pd.read_csv(StringIO(
'''
      A     B     C
a  0.44  0.41  0.46
b  0.47  0.46  0.02
c  0.85  0.82  0.78
d  0.76  0.93  0.83
e  0.88  0.93  0.72
f  0.12  0.15  0.20
g  0.44  0.10  0.28
h  0.61  0.09  0.84
i  0.74  0.87  0.69
j  0.38  0.23  0.44
'''), sep=r' +')

window = 2

def get_3d_shfted_array(df, window=window):
    rows = df.values
    res  = np.dstack((rows[i:i-window] for i in range(window)))
    return res
# 100000 loops, best of 3: 15.5 µs per loop

res  = get_3d_shfted_array(df)
zero = res[...,0]
one  = res[...,1]

# current method
def get_multiindexed_array(df, window=window):
    return pd.concat([df, df.shift(-1)], axis=1, keys=[0, 1]).dropna()
# 1000 loops, best of 3: 928 µs per loop

rawDescription: dataframe representation of a rolling window

description: Dataframe representation of a rolling window


code:
for line in open(' *< resulting file >* ','r'):
    if line[:1] != '>':
        out.write(line)
        continue

    chromname = match2chrom(line[1:-1])
    seqname = line[1:].split()[0]

    print('>{}'.format(chromname), file=out)
    print('{}\t{}'.format(seqname, chromname), file=mappingout)

rawDescription: Reading gzipped text file line-by-line for processing in python 3.2.6


code:
df["Desired_Output"] = df.groupby("Occurrence").cumcount() + 1
df

rawDescription: Pandas Dataframe: Adding the occurrence of values


code:
from flask.globals import _app_ctx_stack, _request_ctx_stack
from werkzeug.urls import url_parse

def route_from(url, method = None):
    appctx = _app_ctx_stack.top
    reqctx = _request_ctx_stack.top
    if appctx is None:
        raise RuntimeError('Attempted to match a URL without the '
                           'application context being pushed. This has to be '
                           'executed when application context is available.')

    if reqctx is not None:
        url_adapter = reqctx.url_adapter
    else:
        url_adapter = appctx.url_adapter
        if url_adapter is None:
            raise RuntimeError('Application was not able to create a URL '
                               'adapter for request independent URL matching. '
                               'You might be able to fix this by setting '
                               'the SERVER_NAME config variable.')
    parsed_url = url_parse(url)
    if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name:
        raise NotFound()
    return url_adapter.match(parsed_url.path, method)

rawDescription: Looking for inverse of url_for in Flask

description: Looking for inverse of url_for in Flask


code:
import csv

from itertools import chain

reader = csv.DictReader(f, delimiter='\x01', lineterminator="\x02")
my_dict_of_values = {}  # whatever goes here

for line in chain(reader, my_dict_of_values):
    do_something(line)

rawDescription: How to iterate over two different iterable objects

description: Iterate over two different iterable objects


code:
from collections import defaultdict
objtree = defaultdict(lambda: defaultdict(dict))
objtree[1][2][3] = 1
objtree
objtree[1][2][3]

rawDescription: Initializing a variable with a nested dictionary literal


code:
import wnck
screen = wnck.screen_get_default()
window_list = screen.get_windows()
active_window = screen.get_active_window()

rawDescription: Discover what window is active on Gnome/Linux/Ubuntu from Python?


code:
lines = f.readlines()

with open("your_filename_here.nii", 'w') as output:
    for line in lines:
        output.write(line)

rawDescription: Extract a file and rename it at the same time in python


code: [f.group(0) for f in current_f]

rawDescription: How to make a list comprehension with the group() method in python?

description: Make a list comprehension with the group() method in python


code:
NOW = datetime.now()
last_monday = NOW+relativedelta(years=-1, weekday=MO)
last_sunday = NOW+relativedelta(years=-1, weekday=SU)

rawDescription: Get Monday and Sunday and last year's Monday and Sunday, same week


code:
def fn(df):
    def inner(dt):
        return df.ix[abs(df.index - dt).argmin(), 'Z']
    return inner

df1['C'] = df1.index.map(fn(df2))

rawDescription: Extract column info based on index of another Data frame for time based Data frames - Avoid Iterating


code:
def test(x):
    return test(x)

test.__code__.co_name in test.__code__.co_names  # true and co_name can't be changed
test.__name__ in test.__code__.co_names  # true but name can be changed

rawDescription: Is it possible to tell if a function is recursive?


code:
class OrderProducts(models.Model):
    product  = models.ForeignKey(Product, related_name='orders')

Product.objects.annotate(total_ordered=models.Sum('orders__quantity'),
                         num_orders=models.Count('orders__id'))

rawDescription: Django group by a query set and multiply with another field


code:
from tkinter import filedialog, Tk

root = Tk().withdraw()

file = filedialog.asksaveasfile(mode='w', defaultextension=".csv")

if file:
    file.write("Hello World")
    file.close()

rawDescription: How do I write to the file I selected using filedialog.asksaveasfile?

description: Write to the file I selected using filedialog.asksaveasfile


code: new = {F(dict[key]): item for key, item in zip(dict, ll)}

rawDescription: How to create a dictionary in python from a list and another dictionary

description: Create a dictionary in python from a list and another dictionary


code:
import numpy as np

y_test = np.asarray(y_test)
misclassified = np.where(y_test != clf.predict(X_test))

rawDescription: retrieve misclassified documents using scikitlearn

description: Retrieve misclassified documents using scikitlearn


code:
name_age_pairs = zip(request.POST.getlist('name'), request.POST.getlist('age'))
data_dicts = [{'name': name, 'age': age} for name, age in name_age_pairs]
for data in data_dicts:
    form = PersonForm(data)
    form.save()

rawDescription: DJANGO: request.POST.getlist() into ModelForm


code:
haystack = 'hello world'
needles = ['.css', '.js', '.jpg', '.gif', '.png', '.com']
if any(needle in haystack for needle in needles):
    pass  # ...

rawDescription: If either needle in haystack

description: If either needle in haystack


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui

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

        self.dialog = None

        self.buttonShow = QtGui.QPushButton(self)
        self.buttonShow.setText("Show Dialog")
        self.buttonShow.clicked.connect(self.on_buttonShow_clicked)

        self.buttonHide = QtGui.QPushButton(self)
        self.buttonHide.setText("Close")
        self.buttonHide.clicked.connect(self.on_buttonHide_clicked)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.buttonShow)
        self.layout.addWidget(self.buttonHide)

    @QtCore.pyqtSlot()
    def on_buttonHide_clicked(self):
        self.accept()

    @QtCore.pyqtSlot()
    def on_buttonShow_clicked(self):
        self.dialog = myDialog(self)
        self.dialog.exec_()

class myWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)

        self.buttonShow = QtGui.QPushButton(self)
        self.buttonShow.setText("Show Dialog")
        self.buttonShow.clicked.connect(self.on_buttonShow_clicked)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.buttonShow)

        self.dialog = myDialog(self)

    @QtCore.pyqtSlot()
    def on_buttonHide_clicked(self):
        self.dialog.accept()

    @QtCore.pyqtSlot()
    def on_buttonShow_clicked(self):
        self.dialog.exec_()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myWindow')

    main = myWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: How to re-display a QDialog after hiding it?

description: Re-display a QDialog after hiding it


code:
3>> bytes(int(x, 16) for x in '0xDE 0xAD 0xBE 0xEF'.split())
b'\xde\xad\xbe\xef'

rawDescription: Python - Parse string in "0xDE 0xAD 0xBE 0xEF" form to a bytearray


code:
from unittest import TestCase
from mock import patch

def method_a(some_thing):
    #some logic here
    return update({'a': 1}, request=some_thing)

def update(value, request):
    if request:
        return value.update({'b': 2})
    return value.update({'c': 3})

class TestMethodA(TestCase):
    def test_mocked_update(self):
        with patch('%s.update' % __name__, lambda value, request: value):
            self.assertEqual(method_a('test'), {'a': 1})

rawDescription: python how to access input params in MagicMock?

description: Python how to access input params in MagicMock


code:
self.myComboList = ["some", "list"]
for row in rows:
   self.myComboList.Append(row[1])
self.ComboList.sort()
self.myComboBoxWidget.AppendItems(self.ComboList)

rawDescription: How to take data from mysql db and insert them into a wx.ComboBox with mysqldb in Python

description: Take data from mysql db and insert them into a wx.ComboBox with mysqldb in Python


code:
import pygame
from ConfigParser import SafeConfigParser

action2function = {
    "up": player.move_up,
    "down": player.move_down,
    "left": player.move_left,
    "right": player.move_right
}

config = SafeConfigParser()
config.read(CONFIG_DIRS)
key2action = config.items()

...
for event in pygame.event.get():
    if event.type == KEYDOWN:
        action2function[key2action[pygame.key.name(event.key)]]()
...

rawDescription: Pygame - customisable controls

description: Pygame - customisable controls


code:
import random

number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))

already_guessed = []

def get_guess(already_guessed):
    if guess in already_guessed:
        print("You already guessed that number.")
    else:
        already_guessed.append(guess)
    return already_guessed

while guess != number:
    if guess < number:
        print("Your guess is too low.")
    if guess > number:
        print("Your guess is too high.")
    if guess == number:
        break

    guess = int(input("Try again.\n\n"))
    already_guessed = get_guess(already_guessed)

rawDescription: Player already guessed the number

description: Player already guessed the number


code:
from gdata.youtube import service
VIDEO_ID = 'IcVqemzfyYs'
yt_service = service.YouTubeService(email=my_email,
                                password=my_password,
                                client_id=my_client_id,
                                source=my_source,
                                developer_key=my_developer_key)
yt_service.ProgrammaticLogin()
userfeed = yt_service.GetYouTubeUserFeed(username=my_email[:my_email.index('@')])
video_entry = reduce(lambda e1, e2: e1 if e1.id.text.endswith(VIDEO_ENTRY) else (e2 if e2.id.text.endswith(VIDEO_ENTRY) else None),
                     userfeed.entry)

rawDescription: 404 when getting private YouTube video even when logged in with the owner's account using gdata-python-client


code: x = np.linspace(0, 100, 10)[:, np.newaxis]

rawDescription: About the numpy.linspace

description: About the numpy.linspace


code:
class Bunch(dict):
    def __init__(self, d):
        dict.__init__(self, d)
        self.__dict__.update(d)

def to_bunch(d):
    r = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = to_bunch(v)
        r[k] = v
    return Bunch(r)

rawDescription: How to use dicts in Mako templates?

description: Use dicts in Mako templates


code:
class BlobstoreImageHandler(blobstore.handler.BlobstoreDownloadHandler):
  def get(self, resource):
    resourse = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

rawDescription: show images on the templates of django using google app engine

description: Show images on the templates of django using google app engine


code:
class Tuple(object):
    def __init__(self, t):
        self.t = t

    def __getitem__(self, item):
        return self.t[item]

    def __add__(self, other):
        return self[0] + other[0], self[1]+other[1]

    def __sub__(self, other):
        return self[0] - other[0], self[1] - other[1]

t1 = MyTuple((20,20))
t2 = MyTuple((40,30))

print(t2 - t1)
print(t2 + t1)

rawDescription: Python - Applying new functions to builtin classes


code:
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("LOCK TABLES %s READ", [tablename])
    try:
        ...
    finally:
        cursor.execute("UNLOCK TABLES;")

rawDescription: How to perform table/row locks in Django

description: Perform table/row locks in Django


code: primes = [2] + filter(lambda p: all(p % n for n in range(3, int(sqrt(p)) + 1, 2)), range(3, max, 2))

rawDescription: Python: A compact way to generate prime numbers in a given range


code:
import cStringIO
from matplotlib import pyplot as plt
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Image, Flowable
from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet

from pdfrw import PdfReader, PdfDict
from pdfrw.buildxobj import pagexobj
from pdfrw.toreportlab import makerl

styles = getSampleStyleSheet()
style = styles['Normal']

def form_xo_reader(imgdata):
    page, = PdfReader(imgdata).pages
    return pagexobj(page)

class PdfImage(Flowable):
    def __init__(self, img_data, width=200, height=200):
        self.img_width = width
        self.img_height = height
        self.img_data = img_data

    def wrap(self, width, height):
        return self.img_width, self.img_height

    def drawOn(self, canv, x, y, _sW=0):
        if _sW > 0 and hasattr(self, 'hAlign'):
            a = self.hAlign
            if a in ('CENTER', 'CENTRE', TA_CENTER):
                x += 0.5*_sW
            elif a in ('RIGHT', TA_RIGHT):
                x += _sW
            elif a not in ('LEFT', TA_LEFT):
                raise ValueError("Bad hAlign value " + str(a))
        canv.saveState()
        img = self.img_data
        if isinstance(img, PdfDict):
            xscale = self.img_width / img.BBox[2]
            yscale = self.img_height / img.BBox[3]
            canv.translate(x, y)
            canv.scale(xscale, yscale)
            canv.doForm(makerl(canv, img))
        else:
            canv.drawImage(img, x, y, self.img_width, self.img_height)
        canv.restoreState()

def make_report(outfn, use_pdfrw):
    fig = plt.figure(figsize=(4, 3))
    plt.plot([1,2,3,4],[1,4,9,26])
    plt.ylabel('some numbers')
    imgdata = cStringIO.StringIO()
    fig.savefig(imgdata, format='pdf' if use_pdfrw else 'png')
    imgdata.seek(0)
    reader = form_xo_reader if use_pdfrw else ImageReader
    image = reader(imgdata)

    doc = SimpleDocTemplate(outfn)
    style = styles["Normal"]
    story = [Spacer(0, inch)]
    img = PdfImage(image, width=200, height=200)

    for i in range(10):
        bogustext = ("Paragraph number %s. " % i)
        p = Paragraph(bogustext, style)
        story.append(p)
        story.append(Spacer(1,0.2*inch))

    story.append(img)

    for i in range(10):
        bogustext = ("Paragraph number %s. " % i)
        p = Paragraph(bogustext, style)
        story.append(p)
        story.append(Spacer(1,0.2*inch))

    doc.build(story)

make_report("hello_png.pdf", False)
make_report("hello_pdf.pdf", True)

rawDescription: loading matplotlib object into reportlab

description: Loading matplotlib object into reportlab


rawDescription: How to enter decimal/binary numbers when creating byte objects in python?

description: Enter decimal/binary numbers when creating byte objects in python


code: "".join(chr_string[slice(*exon_interval)] for exon_interval in zipped)

rawDescription: Pulling parts from a string (python)

description: Pulling parts from a string (python)


rawDescription: Matplotlib Contourf Plots Unwanted Outlines when Alpha < 1


code:
lines = open('textfile.txt').readlines()
open('newfile.txt', 'w').writelines(lines[3:-1])

rawDescription: Remove lines from textfile with python

description: Remove lines from textfile with python


code:
class Foo(object):
    def __new__(cls):
        return 1

Foo()
type(Foo())

rawDescription: Best way to implement/call a class that returns an immutable value?

description: Implement/call a class that returns an immutable value


rawDescription: is there any way to use special functions with rasters?

description: Is there any way to use special functions with rasters


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

# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

# This is  the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')

# Plot histogram.
n, bins, patches = plt.hist(data, 25, normed=1, color='green')
bin_centers = 0.5 * (bins[:-1] + bins[1:])

# scale values to interval [0,1]
col = bin_centers - min(bin_centers)
col /= max(col)

for c, p in zip(col, patches):
    plt.setp(p, 'facecolor', cm(c))

plt.show()

rawDescription: Plot histogram with colors taken from colormap


rawDescription: Regex to separate Numeric from Alpha

description: Regex to separate Numeric from Alpha


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,300))
writer = pd.ExcelWriter("output.xlsx")
df.to_excel(writer,columns=range(0,255))
df.to_excel(writer,columns=range(256,300),startcol=257,index='False')
writer.save()

rawDescription: Pandas to Excel : Keep Existing Data

description: Pandas to Excel : Keep Existing Data


code:
def count(x,y):
    X = load_tuples(x)
    Y = load_tuples(y)
    XY = [t for t in X if t[1] == y]
    return map(len,[X,Y,XY])

rawDescription: Memory saving alternatives to Counter tuple keys splitting


code:
with open('new1.tex', 'a') as f1:
    for num, line in enumerate(f0, 1):
        line = line.rstrip('\n')
        if num  % 2 == 0:
            f1.write(line[2:-2])
        else:
            f1.write(line[1:-1])
        f1.write('\n')

rawDescription: Deleting characters not working correctly


code:
while True:
    messagetoencode = input().upper()
    if len(messagetoencode) > 8 and len(messagetoencode) % 4 == 0:
        break
    else:
        print("Message must be more than 8 characters & divisible by 4")

rawDescription: Restricting user input length and what it can be divisible by


code:
profile = db.GqlQuery("SELECT * FROM Profile WHERE account = :1",
                        users.get_current_user()).get()

rawDescription: How do I check for Existence of a Record in GAE

description: Check for Existence of a Record in GAE


code:
user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]

rawDescription: User input integer list

description: User input integer list


rawDescription: How do I keep Python print from adding newlines or spaces?

description: Keep Python print from adding newlines or spaces


code:
from StringIO import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

print("test")

sys.stdout = old_stdout

s = mystdout.getvalue()
s = "prefix" + s

sys.stderr.write(s)

rawDescription: How to intercept content of stdout in Python?

description: Intercept content of stdout in Python


code:
def browseFile(event):
    buttonText = event.widget.cget("text")
    if buttonText == "OK":
        doSomeStuff()

rawDescription: add information to event in tkinter

description: Add information to event in tkinter


rawDescription: Extracting data from `:` till <br> using python


code:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from os.path import basename, splitext

Tk().withdraw()

path = askopenfilename()
file = basename(path)
(filename, fileextension) = splitext(file)

print(filename)

rawDescription: how to use dynamic modules with file browser?

description: Use dynamic modules with file browser


code:
import cPickle as pickle

# To save the object
pickle.dump( SKFolds , open( "skfolds.p", "wb" ) )

# To load the object
SKFolds = pickle.load( open( "skfolds.p", "rb" ) )

rawDescription: StratifiedKFold: shuffle and random_state


rawDescription: Context-sensitive string splitting, preserving delimiters


code: n = int(self.ids.ramp_time.text) #or float or whatever you need

rawDescription: Reading user-input data in Python 2.7 from Kivy file


code:
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application, url,asynchronous
from Queue import Queue

import json

q=Queue()
q.put("one")
q.put("two")

class HelloHandler(RequestHandler):
    def get(self):
        data=q.get()
        self.write(data)

def make_app():
     return Application([
         url(r"/", HelloHandler),
         ])

def main():
    app = make_app()
    app.listen(8888)
    IOLoop.current().call_later(2, q.put, "three")
    IOLoop.current().start()

if __name__=='__main__':
    main()

rawDescription: python tornado - how to return real-time data

description: Python tornado - how to return real-time data


rawDescription: Count all categories in pandas data frame and add their values


code:
filtered = [col for col in cols if col not in [0, 1]]
sum(filtered) / float(len(filtered))

rawDescription: Eliminating certain values from mean calculation in Python


code:
import struct
struct.pack('>3b',0,0,1)
struct.unpack('>i','\x00'+'\x00\x00\x01')

rawDescription: Reading 3 bytes as an integer

description: Reading 3 bytes as an integer


code:
def to_db_f(f):
    for b in f:
        db.a.update_or_insert((db.a.event_id == b['event_id']), db.a._filter_fields(b))
        db.commit()

def main():
    while 1:
        result = some_function()
        to_db_f(result)

rawDescription: wep2py doesn't write into sql base while function is in endless loop

description: Wep2py doesn't write into sql base while function is in endless loop


code: process = subprocess.Popen(command, shell=True)

rawDescription: how to call an interactive program and show output immediately

description: Call an interactive program and show output immediately


code:
from pyspark.mllib.clustering import LDA

k = ... # number of clusters
corpus = indexed_data.select(col("KeyIndex").cast("long"), "features").map(list)
model = LDA.train(corpus, k=k)

rawDescription: From TF-IDF to LDA clustering in spark, pyspark


code:
abc = 'ABCccCDde :)! f'
from collections import Counter
Counter(c for c in abc.upper() if c.isalpha())

rawDescription: Python - Count number of alphabets only in a string ignoring case


rawDescription: Referencing the ith element of each list in a 2d list


code:
from PyQt4 import QtGui

import sys
class SRM(QtGui.QWidget):
    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.MainWindow = QtGui.QMainWindow()
        self.menubar = self.MainWindow.menuBar()
        self.MainWindow.show()
        self.addAdminMenu()
        sys.exit(self.app.exec_())

    def addAdminMenu(self):
        self.menubar.addMenu('&Admin');

if __name__ == '__main__':
        srm = SRM()

rawDescription: PYQT Adding extra menu items to an existing UI before it opens


code:
originalList=[5433, (32, 54, 122)]
newList=[item for item in originalList if isinstance(item,tuple)]

rawDescription: Python return only a tuple in a list

description: Python return only a tuple in a list


code:
dict1 = {'imp_local'+str(k):700 for k,val in enumerate(nBottom)}
dict2 = {'imp_global'+str(k):600 for k,val in enumerate(nBottom)}

rawDescription: How to call variables generated in loop

description: Call variables generated in loop


code:
import alpha
import sys; sys.modules['alpha'] = object()
import alpha

rawDescription: Import Python class from module but not dependencies


code: cand = [[0, 0] for _ in range(4)]

rawDescription: Does generating a list with multiplication produce references


code:
import cv

capture = cv.CaptureFromFile(filename)
while Condition1:
    # Need a frame to get the output video dimensions
    frame = cv.RetrieveFrame(capture) # Will return None if there are no frames
    # New video file
    video_out = cv.CreateVideoWriter(output_filenameX, CV_FOURCC('M','J','P','G'), capture.fps, frame.size(), 1)
    # Write the frames
    cv.WriteFrame(video_out, frame)
    while Condition2:
        frame = cv.RetrieveFrame(capture) # Will return None if there are no frames
        cv.WriteFrame(video_out, frame)

rawDescription: python library for splitting video

description: Python library for splitting video


code:
list.append(1)
list.append(2)
list.append(3)
# list = [1, 2, 3]

valid_values = (2, 3)

list = [item for item in list if item in valid_values]
# list = [2, 3] now

rawDescription: extend python list to check input before append

description: Extend python list to check input before append


code:
import urllib
from urlparse import urljoin

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

base_url = 'http://www.youtube-mp3.org/'

driver = webdriver.PhantomJS()
driver.get("http://www.youtube-mp3.org/?e=t_exp&r=true#v=hC-T0rC6m7I")

# convert the video to mp3
driver.find_element_by_id('submit').click()

# wait for download link to appear
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, "Download")))
link = element.get_attribute('href')
url = urljoin(base_url, link)

# download the song
urllib.urlretrieve(url, 'song.mp3')

driver.quit()

# enjoy the great song

rawDescription: Download file via hyperlink in PhantomJS using Selenium


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

x = y = np.linspace(1, 10, 10)

t1mean, t2mean = 2, 9
sigma1, sigma2 = .3, .01
t1 = np.random.normal(t1mean, sigma1, 10)
t2 = np.random.normal(t2mean, sigma2, 10)

class nlcmap(object):
    def __init__(self, cmap, levels):
        self.cmap = cmap
        self.N = cmap.N
        self.monochrome = self.cmap.monochrome
        self.levels = np.asarray(levels, dtype='float64')
        self._x = self.levels
        self.levmax = self.levels.max()
        self.transformed_levels = np.linspace(0.0, self.levmax,
             len(self.levels))

    def __call__(self, xi, alpha=1.0, **kw):
        yi = np.interp(xi, self._x, self.transformed_levels)
        return self.cmap(yi / self.levmax, alpha)

tmax = max(t1.max(), t2.max())
#the choice of the levels depends on the data:
levels = np.concatenate((
    [0, tmax],
    np.linspace(t1mean - 4 * sigma1, t1mean + 4 * sigma1, 5),
    np.linspace(t2mean - 4 * sigma2, t2mean + 4 * sigma2, 5),
    ))

levels = levels[levels <= tmax]
levels.sort()

cmap_nonlin = nlcmap(plt.cm.jet, levels)

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.scatter(x, y, edgecolors=cmap_nonlin(t1), s=15, linewidths=4)
ax2.scatter(x, y, edgecolors=cmap_nonlin(t2), s=15, linewidths=4)

fig.subplots_adjust(left=.25)
cbar_ax = fig.add_axes([0.10, 0.15, 0.05, 0.7])

#for the colorbar we map the original colormap, not the nonlinear one:
sm = plt.cm.ScalarMappable(cmap=plt.cm.jet,
                norm=plt.Normalize(vmin=0, vmax=tmax))
sm._A = []

cbar = fig.colorbar(sm, cax=cbar_ax)
#here we are relabel the linear colorbar ticks to match the nonlinear ticks
cbar.set_ticks(cmap_nonlin.transformed_levels)
cbar.set_ticklabels(["%.2f" % lev for lev in levels])

plt.show()

rawDescription: nonlinear colormap, matplotlib

description: Nonlinear colormap, matplotlib


code:
list = [ [ ] ]
money = 10
list[0].append(money)
list

rawDescription: Extend string to a list inside a list

description: Extend string to a list inside a list


code:
import numpy as np
import pandas as pd
import json
import time

def extract_data(data):
    """ convert 1 json dict to records for import"""
    dummy = {}
    jfile = json.loads(data.strip())
    return (
        jfile.get('location', dummy).get('groupe', np.nan),
        jfile.get('id', np.nan),
        jfile.get('Mother', dummy).get('MotherName', np.nan),
        jfile.get('Father', dummy).get('FatherName', np.nan))

start = time.time()
df = pd.DataFrame.from_records(map(extract_data, open('file.json')),
    columns=['group', 'id', 'Father', 'Mother'])
print('New algorithm', time.time()-start)

#
# The original way
#

start= time.time()
df=pd.DataFrame(columns=['group', 'id', 'Father', 'Mother'])
with open ('file.json') as f:
      for chunk in f:
           jfile=json.loads(chunk)
           if 'groupe' in jfile['location']:
               groupe=jfile['location']['groupe']
           else:
               groupe=np.nan
           if 'id' in jfile:
                id=jfile['id']
           else:
                id=np.nan
           if 'MotherName' in jfile['Mother']:
                MotherName=jfile['Mother']['MotherName']
           else:
                MotherName=np.nan
           if 'FatherName' in jfile['Father']:
                FatherName=jfile['Father']['FatherName']
           else:
                FatherName=np.nan
           df = df.append({"groupe":groupe,"id":id,"MotherName":MotherName,"FatherName":FatherName},
            ignore_index=True)
print('original', time.time()-start)

rawDescription: Optimize parsing file with json objects in pandas dataframe


code:
for i, line in enumerate(textfile):
    if i in (1, 4, 5, 9):
        target = re.sub(r"line (printed) here", r"\1", line)

rawDescription: extracting data from specific lines in a file

description: Extracting data from specific lines in a file


code:
import subprocess
server = subprocess.Popen(["python", "manage.py", "runserver"])

rawDescription: IPython Kernel Non-Responsive: Running a Django development server from an IPython Notebook


code:
mutations=0
for i,j in zip(aln1,aln2):
    if i != j and i != '-' and j != '-':
        mutations+=1

rawDescription: Using python to count nucleotide mutations in an alignment


code:
timeit.timeit('999 in list(xrange(1000))')
timeit.timeit('999 in list(xrange(1000))', number=1)

rawDescription: Cannot understand timeit output

description: Cannot understand timeit output


code:
import dbf

source_dbf = '/path/to/big/dbf_file.dbf'
base_name = '/path/to/smaller/dbf_%03d'

sdbf = dbf.Table(source_dbf)
i = 1
ddbf = sdbf.new(base_name % i)

sdbf.open()
ddbf.open()
for record in sdbf:
    if not record.name:    # assuming if 'name' is empty, all are empty
        ddbf.close()
        i += 1
        ddbf = sdbf.new(base_name % i)
        continue
    ddbf.append(record)
ddbf.close()
sdbf.close()

rawDescription: How to divide a dbf table to two or more dbf tables by using python

description: Divide a dbf table to two or more dbf tables by using python


code:
class DynamicList(list):
    def __init__(self, gen):
        self.gen = gen

    def __getitem__(self, index):
        while index >= len(self):
            self.append(next(self.gen))
        return super(DynamicList, self).__getitem__(index)

    def __getslice__(self, start, stop):
        # treat request for "last" item as "most recently fetched"
        if stop == 2147483647: stop = len(self)
        while stop >  len(self):
            self.append(next(self.gen))
        return super(DynamicList, self).__getslice__(start, stop)

    def __iter__(self):
        return self

    def next(self):
        n = next(self.gen)
        self.append(n)
        return n

a = DynamicList(iter(xrange(10)))

rawDescription: Dynamic list that automatically expands

description: Dynamic list that automatically expands


code:
self._session.commit()
self._session.query(Automatic).\
             filter(Automatic.do_when <= time()).\
             limit(limit).\
             all()

rawDescription: Sqlalchemy returns "stale" rows?

description: Sqlalchemy returns "stale" rows


code:
from blinker import Namespace
my_signals = Namespace()

def add_user():
    # add user code here
    user_added = my_signals.signal('user-added')

rawDescription: Which is the best way to log user actions in flask views?


code:
list_of_tuples = [(1, 2), (4, 5)]
list_of_lists = [list(elem) for elem in list_of_tuples]
list_of_lists

rawDescription: Convert a list of tuples to a list of lists


code:
@given('I request a new widget for an account via SOAP')
def step_impl(context):
    client = Client("http://127.0.0.1:8000/soap/")
    context.response = client.Allocate(customer_first='Firstname',
        customer_last='Lastname', colour='red')

@then('I should receive an OK SOAP response')
def step_impl(context):
    eq_(context.response['ok'], 1)

rawDescription: How is data from one Behave step passed to a later step?


code: {c: sum(dict2.get(p, 0) for p in items) for c, items in dict1.items()}

rawDescription: manipulating two dictionaries in python

description: Manipulating two dictionaries in python


code:
module_object = import_py_file(import_name)
module_object.__name__ = import_name
sys.modules[import_name] = module_object

rawDescription: Get current python module object (by name or otherwise)


rawDescription: Is it safe to use frozen set as Dict key?


code:
for key, value in dict1.iteritems():
    outfile.write(key +": ")
    outfile.write(', '.join([str(item) for item in value]))
    outfile.write("\n")

rawDescription: Write list items to a text file in Python


code:
data, result = 'a/b/c/d/e', {}
reduce(lambda x, y: x.setdefault(y, {}), data.split("/"), result)
result

rawDescription: How can I construct a nested dictionary object based on a delimited string?

description: Construct a nested dictionary object based on a delimited string


code:
url = request.get_full_url()
data = request.get_data()
headers = request.headers

rawDescription: Inspecting urllib2.Request attributes when using OpenerDirector with handlers


code:
# Context establishment
try:
    if (autoinit):
        import pycuda.autoinit
        self.context = None
        self.device = pycuda.autoinit.device
        self.computecc = self.device.compute_capability()
    else:
        driver.init()
        self.context = tools.make_default_context()
        self.device = self.context.get_device()
        self.computecc = self.device.compute_capability()

    # GPU code initialization
    # load pre compiled CUDA code from cubin file
    # Select the cubin based on the supplied dtype
    # cubin names contain C++ mangling because of
    # templating. Ugly but no easy way around it
    if self.computecc == (1,3):
        self.fimcubin = "fim_sm13.cubin"
    elif self.computecc[0] == 2:
        self.fimcubin = "fim_sm20.cubin"
    else:
        raise NotImplementedError("GPU architecture not supported")

    fimmod = driver.module_from_file(self.fimcubin)

    IterateName32 = "_Z10fimIterateIfLj8EEvPKT_PKiPS0_PiS0_S0_S0_jjji"
    IterateName64 = "_Z10fimIterateIdLj8EEvPKT_PKiPS0_PiS0_S0_S0_jjji"

    if (self.dtype == np.float32):
        IterateName = IterateName32
    elif (self.dtype == np.float64):
        IterateName = IterateName64
    else:
        raise TypeError

    self.fimIterate = fimmod.get_function(IterateName)

except ImportError:
    warn("Could not initialise CUDA context")

rawDescription: PyCUDA+Threading = Invalid Handles on kernel invocations


code:
import xml.etree.cElementTree as ET

def record_time(root, time, speed, acc):
    attribs = {"t": str(time), "speed": str(speed), "acc": str(acc)}
    ET.SubElement(root, "record", attribs)

root = ET.Element("data")

speed = 0
t = 0
acc = 0
dt = 5/60
print ('This program writes a set of values to an xml file.')

#output to file: t, acc, speed
record_time(root, t, speed, acc)

while (speed < 100):
   acc = acc + 5
   speed = speed + acc*dt

   t = t + dt
   record_time(root, t, speed, acc)
acc = 0
while (t <= 5):
   t = t + 1
   record_time(root, t, speed, acc)
while (speed > 0):
   acc = acc - 5
   speed = speed + acc*dt
   t = t + dt
   record_time(root, t, speed, acc)

#The following lines automatically create, write and close your xml for you, with the appropriate XML header.
tree = ET.ElementTree(root)
tree.write("YOUR_FILENAME_HERE.xml", xml_declaration=True)

print ('Program done!')

rawDescription: Python xml help? Finish my program?

description: Python xml help? Finish my program


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.rect = tk.Frame(width=200, height=200)
        self.rect.pack(fill="both", expand=True, padx=20, pady=20)

        # compute a list of colors that form a gradient between
        # a starting and ending color, then slowly adjust the background
        # of the rectangle according to the computed colors
        self.colors = self._compute_colors("brown", "white", 60)
        self._adjust_colors()

    def _adjust_colors(self):
        color = self.colors.pop(0)
        self.rect.configure(background=color)
        if len(self.colors) > 0:
            self.after(100, self._adjust_colors)

    def _compute_colors(self, start, end, limit):
        (r1,g1,b1) = self.winfo_rgb(start)
        (r2,g2,b2) = self.winfo_rgb(end)
        r_ratio = float(r2-r1) / limit
        g_ratio = float(g2-g1) / limit
        b_ratio = float(b2-b1) / limit

        colors = []
        for i in range(limit):
            nr = int(r1 + (r_ratio * i))
            ng = int(g1 + (g_ratio * i))
            nb = int(b1 + (b_ratio * i))
            color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
            colors.append(color)

        return colors

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True);
    root.mainloop()

rawDescription: lightness of colour python tkinter

description: Lightness of colour python tkinter


code:
item_found = False
for index, item in enumerate(hr):
    if list2[0] == item[0]:
        item_found = True #found the item
        hr[index] = (item[0], item[1]+1) #increment by 1
        break #don't loop more than we need to
if not item_found:
    hr.append((list2[0], 1)) #add new item

rawDescription: Find string in a List of Tuples

description: Find string in a List of Tuples


code:
import multiprocessing as mp
import os
import itertools

def wordCounter(qIn, qOut):
    answer = {}
    for fname, words in iter(qIn.get, None):
        for word in words:
            if fname not in answer:
                answer[fname] = {}
            if word not in answer[fname]:
                answer[fname][word] = 0
            answer[fname][word] += 1
    qOut.put(answer)

def getLines(corpusPath, qIn, numProcs):
    for fname in os.listdir(corpusPath):
        with open(os.path.join(corpusPath, fname)) as infile:
            for i, (k,lines) in enumerate(itertools.groupby((l.strip() for l in infile), lambda line : bool(line) and not line.startswith('"<') and "$" not in line.split(None,1)[0])):
                if not k:
                    continue
                qIn.put((fname, [line.split(None,1)[0].strip('"').strip().lower() for line in lines]))

    for _ in range(numProcs):
        qIn.put(None)

def main(corpusPath):
    qIn, qOut = [mp.Queue() for _ in range(2)]
    procs = [mp.Process(target=wordCounter, args=(qIn, qOut)) for _ in range(mp.cpu_count() -1)]

    lineGetter = mp.Process(target=getLines, args=(corpusPath, qIn, len(procs)))
    lineGetter.start()

    for p in procs:
        p.start()

    answer = {}
    for _ in range(len(procs)):
        for fname, wdict in qOut.get().items():
            if fname not in answer:
                answer[fname] = {}
            for word,count in wdict.items():
                if word not in answer[fname]:
                    answer[fname][word] = 0
                answer[fname][word] += count

    for fname in sorted(answer):
        for word in sorted(answer[fname]):
            print("{} appeared in {} {} times".format(word, fname, answer[fname][word]))

    for p in procs:
        p.terminate()
    lineGetter.terminate()

rawDescription: Computing frequencies fast in Python

description: Computing frequencies fast in Python


code:
from django.views.static import serve
from django.contrib.auth.decorators import login_required

urlpatterns += patterns('',
    url(r'^docs/(?P<path>.*)', login_required(serve), {'document_root': '/path/to/sphinx/build/html'}, 'docs'),
)

rawDescription: Integrating Sphinx and Django in order to require users to log in to see the documentation


code:
A = np.asarray([[1,2],[3,4],[5,6],[7,8]])
rows = len(A)
cols = rows + 1
data = A.flatten() # we want a copy
indptr = np.arange(0, len(data)+1, 2) # 2 non-zero entries per row
indices = np.repeat(np.arange(cols), [1] + [2] * (cols-2) + [1])
import scipy.sparse as sps
a_sps = sps.csr_matrix((data, indices, indptr), shape=(rows, cols))
a_sps.A

rawDescription: Sparse arrays from tuples

description: Sparse arrays from tuples


code:
#cols = ['red', 'blue', 'green']
cols = [[1,0,0,0.5],
        [0,1,0,0.5],
        [0,0,1,0.5]]

controls = ['trt_a', 'trt_b', 'trt_c']

fig, ax = plt.subplots()

boxplot_dict = ax.boxplot([data[x] for x in ['a', 'b', 'c']], \
    positions = [1, 1.5, 2], labels = controls, \
    patch_artist = True, widths = 0.25)

for b, c in zip(boxplot_dict['boxes'], cols):
    #b.set_alpha(0.6)
    b.set_edgecolor('k') # or try 'black'
    b.set_facecolor(c)
    b.set_linewidth(1)

rawDescription: Matplotlib: how to have a transparent box plot face while a non-transparent line edge?


code:
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import TreebankWordTokenizer
import re

vectorizer = CountVectorizer(ngram_range=(1,1), stop_words=None, tokenizer=TreebankWordTokenizer().tokenize)
tokenize = vectorizer.build_tokenizer()

tokenList = tokenize('this is a teste test1 and 12.')
# ['this', 'is', 'a', 'teste', 'test1', 'and', '12', '.']

# Remove any token that (i) does not consist of letters or (ii) is a punctuation mark
tokenList = [token for token in tokenList if re.match('^([a-zA-Z]+|\d+|\W)$', token)]
# ['this', 'is', 'a', 'teste', 'and', '12', '.']

rawDescription: Only words or numbers re pattern. Tokenize with CountVectorizer


code:
import commands
for x in xrange(100):
  commands.getstatusoutput("/home/Example.R")

rawDescription: Translation of Shell Script in to Python


code:
x
(np.ediff1d(x, to_begin=[0])<0).cumsum()*64 + x

rawDescription: Cumulative sum after 64 in Python(Conditional Cumulative sum)


code:
def input_with_prefill(prompt, text):
    def hook():
        readline.insert_text(text)
        readline.redisplay()
    readline.set_pre_input_hook(hook)
    result = input(prompt)
    readline.set_pre_input_hook()
    return result

rawDescription: Is it possible to prefill a input() in Python 3's Command Line Interface?


rawDescription: Is it possible to unpack a tuple without using variables?


code:
# this is a generator (an iterable) which only outputs a
# line containing "DNS" if it was requested in an iteration
# furthermore, the way i use a generator here is called "list comprehension"
dns_lines = ( line for line in open('/home/user/file','r') if "DNS" in line )

# the with-statement uses python's magic-methods to take care of
# opening and closing the file
with open("output", 'w') as f:
    # enumerate works on generators
    # it enumerates each item that is iterated over
    # a tuple is returned (count, line)
    for count_line in enumerate(dns_lines):
        f.write("%d - %s" % (count_line))

rawDescription: String Counts from dynamic data sets in Python


code:
listing = os.listdir(self.Parent.userTempFolderPath)
for infile in listing:
    if 'Thumbs.db' not in infile and 'DS' not in infile:
        path = os.path.join(self.Parent.userTempFolderPath, infile)

        fileMover.moveFile(path, self.Parent.userTempFolderPath, self.Parent.currentProjectObject.Watchfolder, True)

rawDescription: Move files with spaces in the name

description: Move files with spaces in the name


code:
s = sorted(data.items(), key=lambda x: x[0])  # alphabetic
s = sorted(s, key=lambda x: len(x[1]), reverse=True)  # length

rawDescription: How to sort a {str:[int]} into a tuple with the string and list of integers based on length of the lists?

description: Sort a {str:[int]} into a tuple with the string and list of integers based on length of the lists


rawDescription: Reductions down a column in Pandas

description: Reductions down a column in Pandas


code:
def erase_random_elements(elements_list, iterable_random_numbers):
    s = set(iterable_random_numbers)
    elements_list[:] = [x for i, x in enumerate(elements_list) if i not in s]
    #return elements_list -> not required actually because we're updating the list in-place

rawDescription: Python large list (~150M lists inside with 4 string elements each) convertion speeding up


code:
class Point(object):
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z

    def __hash__(self):
        return hash((self.x,self.y,self.z))

    def __eq__(self,other):
        return (self.x,self.y,self.z) == (other.x,other.y,other.z)

rawDescription: How to match arbitrary data using hash codes?

description: Match arbitrary data using hash codes


code:
def reverseTranslation(d):
    return dict((v1,[k for k,v in d.iteritems() if v1 in v])
                for v1 in set(sum(d.values(),[])))

rawDescription: Change the value of a dictionary to key of a dictionary in python


code:
list1=[1, 4, 10]
list2=[2, 3, 6]

n = len(list2)
sum_min = 0

for x in list1:

    diff=[abs(y-x) for y in list2]
    mindiff=min(int(s) for s in diff)

    sum_min += mindiff  # iterating will keep on adding min of differences 1 + 1 + 4

    print (mindiff)

print(sum_min/n)  # mean minimum difference

rawDescription: How to perform sum of elements iterated in Python loop

description: Perform sum of elements iterated in Python loop


code:
c = Counter()
for item in something:
    if item.has_some_property:
        c[item.property] += 1
    elif item.has_some_other_property:
        c[item.other_property] += 1
    elif item.has_some.third_property:
        c[item.third_property] += 1

rawDescription: Python Counter class: add or increment single item


code:
from netCDF4 import Dataset
new_value = -999
nc.variables['var'][0,0,0] = new_value

rawDescription: Overwriting specific cells in netcdf

description: Overwriting specific cells in netcdf


rawDescription: numpy array initialization (fill with identical values)

description: Numpy array initialization (fill with identical values)


code:
import filecmp
filecmp.cmp('file1.txt', 'file1.txt')

rawDescription: Python - can i know if a printing occurred or not


code:
from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer

blob = TextBlob(message, analyzer=NaiveBayesAnalyzer())
a = (blob.sentiment)
if a.__getattribute__("p_pos") > a.__getattribute__("p_neg"):
    tag = str(a.__getattribute__("classification"))
    sentiment = str(a.__getattribute__("p_pos"))
elif a.__getattribute__("p_pos") < a.__getattribute__("p_neg"):
    tag = str(a.__getattribute__("classification"))
    sentiment = str(a.__getattribute__("p_neg"))
else:
    tag = "N"
    sentiment = "0"

rawDescription: Is there any feature of TextBlob to obtain neutral classification?


rawDescription: How to get all values with the same key in an immut. dict?

description: Get all values with the same key in an immut. dict


code: prettyprint = True

rawDescription: creating xml documents with whitespace with xml.etree.cElementTree

description: Creating xml documents with whitespace with xml.etree.cElementTree


code:
def quicksort(list, start, end):
  if start < end:                            # If there are two or more elements...
    split = partition(list, start, end)    # ... partition the sublist...
    quicksort(list, start, split-1)
    quicksort(list, split+1, end) #we need to sort the second half as well!

rawDescription: Getting a quick sort in Python to work

description: Getting a quick sort in Python to work


code:
@ndb.transactional
def my_get_or_insert(cls, id, **kwds):
  key = ndb.Key(cls, id)
  ent = key.get()
  if ent is not None:
    return (ent, False)  # False meaning "not created"
  ent = cls(**kwds)
  ent.key = key
  ent.put()
  return (ent, True)  # True meaning "created"

rawDescription: How do I know if ndb.Model.get_or_insert created a new entity or got an existing one?

description: Know if ndb.Model.get_or_insert created a new entity or got an existing one


code:
final_data = {}
for entry in data:
    userid = entry["userid"]
    if userid not in final_data:
        final_data[userid] = {"userid": userid, "score": 0}
    final_data[userid]["score"] += entry["score"]
    if not entry["ctype"] in final_data[userid]:
        final_data[userid][entry["ctype"]] = 1
    else:
        final_data[userid][entry["ctype"]] += 1

rawDescription: Creating multiple dictionaries based on other dictionary values in python


code: 'hello=potato'.translate(None, '=p')

rawDescription: Getting rid of certain characters in a string in python


code:
f, (ax1) = plt.subplots(1,figsize=(15,6))
f, (ax2) = plt.subplots(1,figsize=(15,6))
f, (ax3) = plt.subplots(1,figsize=(15,6))

sns.set(style="darkgrid")

sns.barplot(x='Country',y='Average Rate',data=pddf1, palette="muted", x_order=pddf1["Country"].tolist(), ax=ax1)
ax1.set_xticklabels(pddf1["Country"],rotation=90)

sns.barplot(x='Country',y='Jobs Completed',data=pddf2, palette="muted", x_order=pddf2["Country"].tolist(), ax=ax2)
ax2.set_xticklabels(pddf2["Country"],rotation=90)

sns.barplot(x='Country',y='User Rating',data=pddf3, palette="muted", x_order=pddf3["Country"].tolist(), ax=ax3)
ax3.set_xticklabels(pddf3["Country"],rotation=90)

rawDescription: seaborn barplot() output figure is overwritten

description: Seaborn barplot() output figure is overwritten


code:
class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()
class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

getch = _Getch()
# then call getch() to get the input...

rawDescription: Read backspace, DEL and friends from stdin in pure Python?


code:
headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    records = Record.objects.all()

    if sort is not None:
        records = records.order_by(sort)

        if headers[sort] == "des":
            records = records.reverse()
            headers[sort] = "asc"
        else:
            headers[sort] = "des"

    return render_to_response(...)

rawDescription: Sortable tables in Django

description: Sortable tables in Django


code:
handlers = [
  (r'/', MainHandler),
  (r'/(.*)', web.StaticFileHandler, {'path': public_root}),
]

rawDescription: Have Tornado serve static HTML with javascript without using static, public, etc. prefix


code:
import sys, pygame, math
from pygame.locals import *

# set up a bunch of constants
WHITE      = (255, 255, 255)
DARKRED    = (128,   0,   0)
RED        = (255,   0,   0)
BLACK      = (  0,   0,   0)
GREEN      = (  0, 255,   0) ### HERE
BLUE       = (  0,   0, 255) ### HERE

BGCOLOR = WHITE

WINDOWWIDTH = 640 # width of the program's window, in pixels
WINDOWHEIGHT = 480 # height in pixels
WIN_CENTERX = int(WINDOWWIDTH / 2) # the midpoint for the width of the window
WIN_CENTERY = int(WINDOWHEIGHT / 2) # the midpoint for the height of the window

FPS = 160 # frames per second to run at

AMPLITUDE = 80 # how many pixels tall the waves with rise/fall.

# standard pygame setup code
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Trig Waves')
fontObj = pygame.font.Font('freesansbold.ttf', 16)

# variables that track visibility modes
showSine = True
showSquare = True ### HERE

pause = False

xPos = 0
step = 0 # the current input f

### HERE
posRecord = {'sin': [], 'square': []} # keeps track of the ball positions for drawing the waves

# making text Surface and Rect objects for various labels

### HERE
squareLabelSurf = fontObj.render('square', True, BLUE, BGCOLOR)
squareLabelRect = squareLabelSurf.get_rect()

sinLabelSurf = fontObj.render('sine', True, RED, BGCOLOR)
sinLabelRect = sinLabelSurf.get_rect()

instructionsSurf = fontObj.render('Press Q to toggle wave. P to pause.', True, BLACK, BGCOLOR)
instructionsRect = instructionsSurf.get_rect()
instructionsRect.left = 10
instructionsRect.bottom = WINDOWHEIGHT - 10

### HERE
yPosSquare = AMPLITUDE # starting position

# main application loop
while True:
    # event handling loop for quit events
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()

        # check for key presses that toggle pausing and wave visibility
        if event.type == KEYUP:
            if event.key == K_q:
                showSine = not showSine
            elif event.key == K_p:
                pause = not pause

    # fill the screen to draw from a blank state
    DISPLAYSURF.fill(BGCOLOR)

    # draw instructions
    DISPLAYSURF.blit(instructionsSurf, instructionsRect)

    # sine wave
    yPos = -1 * math.sin(step) * AMPLITUDE
    posRecord['sin'].append((int(xPos), int(yPos) + WIN_CENTERY))
    if showSine:
        # draw the sine ball and label
        pygame.draw.circle(DISPLAYSURF, RED, (int(xPos), int(yPos) + WIN_CENTERY), 10)
        sinLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)
        DISPLAYSURF.blit(sinLabelSurf, sinLabelRect)

    # draw the waves from the previously recorded ball positions
    if showSine:
        for x, y in posRecord['sin']:
            pygame.draw.circle(DISPLAYSURF, DARKRED, (x, y), 4)

    ### HERE - drawing horizontal lines
    # square
    posRecord['square'].append((int(xPos), int(yPosSquare) + WIN_CENTERY))
    if showSquare:
        # draw the sine ball and label
        pygame.draw.circle(DISPLAYSURF, GREEN, (int(xPos), int(yPosSquare) + WIN_CENTERY), 10)
        squareLabelRect.center = (int(xPos), int(yPosSquare) + WIN_CENTERY + 20)
        DISPLAYSURF.blit(squareLabelSurf, squareLabelRect)

    # draw the waves from the previously recorded ball positions
    if showSquare:
        for x, y in posRecord['square']:
            pygame.draw.circle(DISPLAYSURF, BLUE, (x, y), 4)

    # draw the border
    pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)

    pygame.display.update()
    FPSCLOCK.tick(FPS)

    if not pause:
        xPos += 0.5

        if xPos > WINDOWWIDTH:
            #sine ### HERE
            xPos = 0
            posRecord['sin'] = []
            step = 0

            # square ### HERE
            yPosSquare = AMPLITUDE
            posRecord['square'] = []
        else:
            #sine ### HERE
            step += 0.008
            #step %= 2 * math.pi

            # square ### HERE
            # jump top and bottom every 100 pixels
            if xPos % 100 == 0:
                yPosSquare *= -1
                # add vertical line
                for x in range(-AMPLITUDE, AMPLITUDE):
                    posRecord['square'].append((int(xPos), int(x) + WIN_CENTERY))

rawDescription: Drawing a square wave in pygame

description: Drawing a square wave in pygame


code:
def getfile():
    filename = askopenfilename()
    print(filename)

button = Button(frame, text="Choose File", fg="black", command=getfile)

rawDescription: Choosing file by clicking on a button [Python 2.7.6]


rawDescription: are numpy functions forward compatible

description: Are numpy functions forward compatible


code:
import pandas as pd
import sqlite3

#read the CSV
df = pd.read_csv('/resources/data/findhelp/tabledata.csv')
#connect to a database
conn = sqlite3.connect("Any_Database_Name.db") #if the db does not exist, this creates a Any_Database_Name.db file in the current directory
#store your table in the database:
df.to_sql('Some_Table_Name', conn)
#read a SQL Query out of your database and into a pandas dataframe
sql_string = 'SELECT * FROM Some_Table_Name'
df = pd.read_sql(sql_string, conn)

rawDescription: SQL statement for CSV files on IPython notebook


code:
class MyAuthenticationForm(AuthenticationForm):
    username = forms.CharField(label=_("Username"), max_length=64)

rawDescription: Django override default functionalities

description: Django override default functionalities


code:
with open("filename") as f:
    contents = f.read()

rawDescription: Python Challenge Level 2

description: Python Challenge Level 2


rawDescription: In Python, how can I change the sign of one number in a list based on another number's sign?


code:
sql_cmd = '''CREATE TABLE {}(id, column1, column2, column2)'''.format(
            'table_name')
db.execute(sql_cmd)

rawDescription: Create Table using a variable in python

description: Create Table using a variable in python


code:
import gtk

tv = gtk.TextView()

def keyPress(widget, event):
    if event.keyval == 65293:
        ## do something
        return True
    return False

tv.connect('key-press-event', keyPress)

win = gtk.Dialog()
win.vbox.pack_start(tv)
win.vbox.show_all()
win.run()

rawDescription: How to Set Call Back For Enter key of GtkTextView?


code:
import pandas as pd
pd.read_csv("test.csv")
df = pd.read_csv("test.csv")
df.applymap(lambda x: x.split())

rawDescription: How to edit .csv in python to proceed NLP

description: Edit .csv in python to proceed NLP


code:
from Tkinter import *

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master

        self.table = {}

        self.rightFrame = None # for first "grid_forget()"

        self.createButtons()

    #-----------------------------

    def run(self):
        self.master.mainloop()

    #-----------------------------

    #   creates buttons with alignment and their functions
    def createButtons(self):
        self.menuFrame = Frame(self.master)
        self.menuFrame.grid(row=0, column=0)

        load = Button(self.menuFrame, text="Load Table", command=self.loadTable)
        load.grid(row=0, column=0, pady=30)

        course = Button(self.menuFrame, text="Add Course", command=self.addCourse)
        course.grid(row=1, column=0, pady=30)

        time = Button(self.menuFrame, text="Add Time", command=self.addTime)
        time.grid(row=2, column=0, pady=30)

        reset = Button(self.menuFrame, text="Reset Time", command=self.resetTime)
        reset.grid(row=3, column=0, pady=30)

        comment = Button(self.menuFrame, text="Change Comment", command=self.changeComment)
        comment.grid(row=4, column=0, pady=30)

        view = Button(self.menuFrame, text="View Table", command=self.viewTable)
        view.grid(row=5, column=0, pady=30)

    #-----------------------------

    def loadTable(self):
        # remove previous content
        if self.rightFrame:
            self.rightFrame.grid_forget()

        # create new content
        self.rightFrame = Frame(self.master)
        self.rightFrame.grid(row=0, column=1, sticky=N)

        title = Label(self.rightFrame, text='load Table')
        title.grid(row=0, column=0)

    #-----------------------------

    def addCourse(self):
        # remove previous content
        if self.rightFrame:
            self.rightFrame.grid_forget()

        # create new content
        self.rightFrame = Frame(self.master)
        self.rightFrame.grid(row=0, column=1, sticky=N)

        #creates addCourse window and text boxes for input
        title = Label(self.rightFrame, text='Enter the course name')
        title.grid(row=0, column=0)

        courseBox = Entry(self.rightFrame, width=10)
        courseBox.grid(row=1, column=0)

        label = Label (self.rightFrame, text='Enter the hours per week spent on course')
        label.grid(row=2, column=0)

        weekHoursBox = Entry(self.rightFrame, width=10)
        weekHoursBox.grid(row=3, column=0)

        #function to accept input from boxes into dict
        def callback():
            course = courseBox.get()
            weekHours = weekHoursBox.get()
            string = "0 "+ str(weekHours) + " "
            self.table[course] = string

        enterB = Button(self.rightFrame, text='Enter Information', command=callback)
        enterB.grid(row=4, column=0)

    #-----------------------------

    def addTime(self):
        # remove previous content
        if self.rightFrame:
            self.rightFrame.grid_forget()

        # create new content
        self.rightFrame = Frame(self.master)
        self.rightFrame.grid(row=0, column=1, sticky=N)

        title = Label(self.rightFrame, text='Add Time')
        title.grid(row=0, column=0)

    #-----------------------------

    def resetTime(self):
        # remove previous content
        if self.rightFrame:
            self.rightFrame.grid_forget()

        # create new content
        self.rightFrame = Frame(self.master)
        self.rightFrame.grid(row=0, column=1, sticky=N)

        title = Label(self.rightFrame, text='Reset Time')
        title.grid(row=0, column=0)

    #-----------------------------

    def changeComment(self):
        # remove previous content
        if self.rightFrame:
            self.rightFrame.grid_forget()

        # create new content
        self.rightFrame = Frame(self.master)
        self.rightFrame.grid(row=0, column=1, sticky=N)

        title = Label(self.rightFrame, text='Change Comment')
        title.grid(row=0, column=0)

    #-----------------------------

    def viewTable(self):
        # remove previous content
        if self.rightFrame:
            self.rightFrame.grid_forget()

        # create new content
        self.rightFrame = Frame(self.master)
        self.rightFrame.grid(row=0, column=1, sticky=N)

        title = Label(self.rightFrame, text='View Table')
        title.grid(row=0, column=0)

#----------------------------------------------------------------------

Application(Tk()).run()

rawDescription: Tkinter Add/Remove "windows" within current window


code:
d = {
    'americanexpress': {
        'maxchar': 30,
        'special_char': False,
        'numbers': True,
        'capital': True
    },
    'discover': {
        'maxchar': 29,
        'special_char': True,
        'numbers': True,
        'capital': False
    }
}

# Yes, it works
assert d['americanexpress']['maxchar'] == 30
assert d['discover']['capital'] is False

rawDescription: Optimal way to store data in python

description: Optimal way to store data in python


code:
def make_f(g):
    # Note: a new f() is compiled each time make_f() is called!
    @jit(nopython=True)
    def f(x):
        return g(x) + g(-x)
    return f

f = make_f(my_g_function)
result = f(1)

rawDescription: Numba jitclass with function input

description: Numba jitclass with function input


code:
print(sorted(vars(a).keys() - vars()))
# prints ['__initializing__', 'f'], only `a` has `f` defined, the `__initializing__` value is a flag used by the import machinery
print(sorted(vars().keys() - vars(a)))
# prints ['a', 'g'], only `main` has imported `a` and defined function `g`

rawDescription: __globals__ in imported function is much different than __globals__ of function in main module


code:
import datetime
import matplotlib.pyplot as plt

dates = [datetime.date(2002, 3, 11) - datetime.timedelta(days=x) for x in range(0, 10)]
yvalues = [2, 4, 1,7,9,2, 4, 1,7,9]
errorvalues = [0.4, 0.1, 0.3,0.4, 0.1,.4, 0.1, 0.3,0.4, 0.1]

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.errorbar(dates,yvalues,yerr=errorvalues,fmt='.')
ax.margins(x=0.05)
fig.autofmt_xdate()

plt.show()

rawDescription: Datetime axis spacing

description: Datetime axis spacing


code: coa1.to_csv('0000-2951-test.txt',index=False, sep='\t', encoding = 'utf-16')

rawDescription: problems writing a pandas DataFrame into a unicode text file

description: Problems writing a pandas DataFrame into a unicode text file