code:
for route, origincoord in izip(results, origincoords):
    route['routes'][0]['bounds']['origincoord'] = origincoord

rawDescription: Adding Labeled Values to JSON

description: Adding Labeled Values to JSON


code:
import re
from pprint import pprint

thestr = "(x=1, y = 2, z = 3 ) (a = 1) (m = 4, n = 6, o = 2)"
groups = re.findall(r'\([^)]+\)', thestr)
matches = []

for group in groups:
    matches.append(re.findall(r'(\w+)\s*=\s*(\d+)', group))

pprint(matches)

rawDescription: Python regex based split

description: Python regex based split


code: list(seen)

rawDescription: How risky is using list.index() for getting the index of a set?


code: vars = ['blank.png'] * 3;

rawDescription: For loop variable increment (Python 2.7)


code:
class square_result(object):
    def __call__(self, x, y):
        return (x+y)**2

# this has no effect at all after the reassignment
def add_two_numbers(x, y):
    return x + y

add_two_numbers = square_result()

rawDescription: Chaining decorators that are defined as classes?


rawDescription: I need to generate x random numbers in an interval from 1 to x but each number have to occur only once


rawDescription: Python pandas. Group By and removing a timestamp


code:
import re
s = '''
static public Register myReg1 = new Register("D4_STAT_1", 81);
static public Register myReg2 = new Register("D5_STAT_1", 819);
'''
myvar = "81"
re.search('static public Register \w+ = new Register\("(\w+)", %s\);' % re.escape(str(myvar)), s).group(1)

rawDescription: regex to match a variable and get the words inside the quotations from the matching line in python

description: Regex to match a variable and get the words inside the quotations from the matching line in python


code:
blog_years=[]
for entry in blog_entries:
    if entry.date.date().year not in blog_years:
        blog_years.append(entry.date.date().year)

rawDescription: How do I get each distinct 'year' value out of a Django model with a datetime field?

description: Get each distinct 'year' value out of a Django model with a datetime field


rawDescription: Send NULL message in PyZMQ

description: Send NULL message in PyZMQ


code:
from operator import itemgetter

MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))

rawDescription: Sorting a tuple that contains tuples

description: Sorting a tuple that contains tuples


rawDescription: Flask - how can I always include language code in url


code: counts_and_means.columns = ["Count", "Avg_val1", "Avg_val2"]

rawDescription: Pandas: Best idioms for renaming, reordering columns while aggregating


rawDescription: Return Django queryset of items that appear in a single category when items can appear in multiple categories


rawDescription: Python slice first and last element in list


code: v = ['one-point-five', 'four']

rawDescription: Merge sequences of unique elements

description: Merge sequences of unique elements


rawDescription: It is possible to round up integers using format?


code:
from traits.api import *
from traitsui.api import *

class ColorColumn(ObjectColumn):
  def get_cell_color(self,object):
    return object.color

class ColorContainer(HasTraits):
  color=Color('red')
  blank_text=Str('')

class SomeApplication(HasTraits):
  dummy_table=List(ColorContainer)

  def _dummy_table_default(self):
    return [ColorContainer()]

  traits_view=View(Item(name='dummy_table',
    editor=TableEditor(columns=
      [ColorColumn(label='',editor=TextEditor(),name='blank_text',editable=False)],
      selection_bg_color=None,),show_label=False))

SomeApplication().configure_traits()

rawDescription: Drawing solid box of color in traits GUI


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided as ast
from itertools import product

def norm_shape(shape):
    '''
    Normalize numpy array shapes so they're always expressed as a tuple,
    even for one-dimensional shapes.

    Parameters
        shape - an int, or a tuple of ints

    Returns
        a shape tuple
    '''
    try:
        i = int(shape)
        return (i,)
    except TypeError:
        # shape was not a number
        pass

    try:
        t = tuple(shape)
        return t
    except TypeError:
        # shape was not iterable
        pass

    raise TypeError('shape must be an int, or a tuple of ints')

def sliding_window(a,ws,ss = None,flatten = True):
    '''
    Return a sliding window over a in any number of dimensions

    Parameters:
        a  - an n-dimensional numpy array
        ws - an int (a is 1D) or tuple (a is 2D or greater) representing the size
             of each dimension of the window
        ss - an int (a is 1D) or tuple (a is 2D or greater) representing the
             amount to slide the window in each dimension. If not specified, it
             defaults to ws.
        flatten - if True, all slices are flattened, otherwise, there is an
                  extra dimension for each dimension of the input.

    Returns
        an array containing each n-dimensional window from a
    '''

    if None is ss:
        # ss was not provided. the windows will not overlap in any direction.
        ss = ws
    ws = norm_shape(ws)
    ss = norm_shape(ss)

    # convert ws, ss, and a.shape to numpy arrays so that we can do math in every
    # dimension at once.
    ws = np.array(ws)
    ss = np.array(ss)
    shape = np.array(a.shape)

    # ensure that ws, ss, and a.shape all have the same number of dimensions
    ls = [len(shape),len(ws),len(ss)]
    if 1 != len(set(ls)):
        raise ValueError(\
        'a.shape, ws and ss must all have the same length. They were %s' % str(ls))

    # ensure that ws is smaller than a in every dimension
    if np.any(ws > shape):
        raise ValueError(\
        'ws cannot be larger than a in any dimension.\
 a.shape was %s and ws was %s' % (str(a.shape),str(ws)))

    # how many slices will there be in each dimension?
    newshape = norm_shape(((shape - ws) // ss) + 1)
    # the shape of the strided array will be the number of slices in each dimension
    # plus the shape of the window (tuple addition)
    newshape += norm_shape(ws)
    # the strides tuple will be the array's strides multiplied by step size, plus
    # the array's strides (tuple addition)
    newstrides = norm_shape(np.array(a.strides) * ss) + a.strides
    strided = ast(a,shape = newshape,strides = newstrides)
    if not flatten:
        return strided

    # Collapse strided so that it has one more dimension than the window.  I.e.,
    # the new array is a flat list of slices.
    meat = len(ws) if ws.shape else 0
    firstdim = (np.product(newshape[:-meat]),) if ws.shape else ()
    dim = firstdim + (newshape[-meat:])
    # remove any dimensions with size 1
    dim = filter(lambda i : i != 1,dim)
    return strided.reshape(dim)

rawDescription: resize a 2D numpy array excluding NaN

description: Resize a 2D numpy array excluding NaN


rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code:
from collections import defaultdict

in_ = ((["a"], "t1"), (["a","b","c"], "t2"), (["c","d"], "t3"))
out = defaultdict(list)

for keys,val in in_:
    for key in keys:
        out[key].append(val)

rawDescription: How this operation is called?

description: How this operation is called


code:
def rangetest(func):
    def onCall(**kargs):
        argchecks = func.__annotations__

        if all(val in range(*argchecks.get(arg)) for arg,val in kargs.items()):
            return func(**kargs)
        else :
              print ("invalid arg range")
    return onCall

@rangetest
def func(a:(1, 5), b:(4,7), c:(0, 10)):
    print(a + b + c)

rawDescription: Pattern matching on function parameters in Python


code: set(row) - valid_set

rawDescription: check whether an element is in list or not

description: Check whether an element is in list or not


rawDescription: python --path=/path/to/my/module/?

description: Python --path=/path/to/my/module/


code:
labels = bins
bins = list(np.unique(np.fromiter(chain.from_iterable(bins), dtype='int')))
last = bins[-1]
bins.append(int(df.val1.max() + 1))

rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


code:
def orderedpermutations(lst):
    from copy import copy # possibly deepcopy, but unnecessary for this implementation
    new_list = copy(lst)
    for _ in range(len(new_list)):
        new_list.append(new_list.pop(0))
        yield new_list

rawDescription: Moving a column around in python

description: Moving a column around in python


code: yourList = [line.rstrip('\n') for line in f]

rawDescription: Reading from a plain text file

description: Reading from a plain text file


code:
class SettingsCombo(QtGui.QComboBox):
    VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    def __init__(self):
        QtGui.QComboBox.__init__(self)
        self.addItems(map(str,SettingsCombo.VALUES))

rawDescription: Combobox unable to display 2-digits in a line


code: ['name']

rawDescription: Python: Assigning function along with parameters to a variable


code:
term = "Lizards and Amphibians not salamander or newt"
re.sub(r"\b(not|or|and)\b", lambda m: m.group().upper(), term)

rawDescription: Multiple re.sub() statements

description: Multiple re.sub() statements


rawDescription: Escaped string of bytes to bytestring

description: Escaped string of bytes to bytestring


code:
df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1.sort(['a', 'b'], ascending=[True, False])

rawDescription: How to sort a dataFrame in python pandas by two or more columns?

description: Sort a dataFrame in python pandas by two or more columns


code:
from psychopy import visual
w = visual.Window()

rawDescription: Exiting PsychoPy Window

description: Exiting PsychoPy Window


code: f = type(rand(int())).min

rawDescription: How to instantiate a class function for not instantiated objects?

description: Instantiate a class function for not instantiated objects


rawDescription: Tkinter Scale Widget State

description: Tkinter Scale Widget State


code:
pool = IPv4Pool.objects.get(pk=1)
pool.available_ips
range = IPRange()
range.pool = poll
range.save()
pool.available_ips

rawDescription: Field calculated from Foreign Keys, need to save twice?


code: interact(replot_it, a=(0.,5.))

rawDescription: Modify line / plot in IPython notebook "interact"


code:
# comment explaining why this unusual check is necessary
if 'attribute' in instance.__class__.__dict__:
    value = instance.attribute
else:
    value = None

rawDescription: How to get an attribute just from the current class and not from possible parent classes?

description: Get an attribute just from the current class and not from possible parent classes


code:
def affiliate(request, idnum=None):
    idnum = int(idnum or request.args.get('idnum'))
    golfe = Golf.get_by_id(idnum)
    return render_to_response('myapp/affiliate.html',{'affiliate': golfe})

rawDescription: Send request from template html file to views.py


code:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]

c = []
tmp = [a]*len(a) + [b]*len(b)
while a and b:
    c.append(random.choice(tmp).pop(0))

c += a + b

rawDescription: Randomly Interleave 2 Arrays In Python

description: Randomly Interleave 2 Arrays In Python


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm

n = 10                            # rough number of points
dom = np.linspace(-2,2,n+1)       # 1d input grid
x1,y1 = np.meshgrid(dom,dom)      # 2d input grid
z = np.random.rand(*x1.shape)     # ill-conditioned sample
#z = np.cos(x1)*np.sin(y1)        # smooth sample

# first interpolator with interp2d:
fun1 = interp.interp2d(x1,y1,z,kind='linear')

# construct twice finer plotting and interpolating mesh
plotdom = np.linspace(-1,1,2*n+1)             # for interpolation and plotting
plotx1,ploty1 = np.meshgrid(plotdom,plotdom)
plotz1 = fun1(plotdom,plotdom)                # interpolated points

# construct 45-degree rotated input and interpolating meshes
rotmat = np.array([[1,-1],[1,1]])/np.sqrt(2)           # 45-degree rotation
x2,y2 = rotmat.dot(np.vstack([x1.ravel(),y1.ravel()])) # rotate input mesh
plotx2,ploty2 = rotmat.dot(np.vstack([plotx1.ravel(),ploty1.ravel()])) # rotate plotting/interp mesh

# interpolate on rotated mesh with interp2d
# (reverse rotate by using plotx1, ploty1 later!)
fun2 = interp.interp2d(x2,y2,z.ravel(),kind='linear')

# I had to generate the rotated points element-by-element
# since fun2() accepts only rectangular meshes as input
plotz2 = np.array([fun2(xx,yy) for (xx,yy) in zip(plotx2.ravel(),ploty2.ravel())])

# try interpolating with griddata
plotz3 = interp.griddata(np.array([x1.ravel(),y1.ravel()]).T,z.ravel(),np.array([plotx1.ravel(),ploty1.ravel()]).T,method='linear')
plotz4 = interp.griddata(np.array([x2,y2]).T,z.ravel(),np.array([plotx2,ploty2]).T,method='linear')

# function to plot a surface
def myplot(X,Y,Z):
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(X, Y, Z,rstride=1, cstride=1,
                    linewidth=0, antialiased=False,cmap=cm.coolwarm)
    plt.show()

# plot interp2d versions
myplot(plotx1,ploty1,plotz1)                    # Cartesian meshes
myplot(plotx1,ploty1,plotz2.reshape(2*n+1,-1))  # rotated meshes

# plot griddata versions
myplot(plotx1,ploty1,plotz3.reshape(2*n+1,-1))  # Cartesian meshes
myplot(plotx1,ploty1,plotz4.reshape(2*n+1,-1))  # rotated meshes

rawDescription: scipy interp2d/bisplrep unexpected output when given 1D input

description: Scipy interp2d/bisplrep unexpected output when given 1D input


code:
ax.plot([1, 2, 3])
ax.legend(['A simple line'])

rawDescription: Matplotlib editing legend labels

description: Matplotlib editing legend labels


code: results = [float(item.rsplit('= ', 1)[1]) for item in data]

rawDescription: simple and best way of list manipulation in python

description: Simple and best way of list manipulation in python


code:
import re
s = "I have a string submarine I want to be able to detect marines as a match"
kw = "submarine"
r  = re.compile(r"\b[{0}]+\b".format(kw))
print(r.findall(s))

rawDescription: Efficient unordered substing matching

description: Efficient unordered substing matching


code:
from Acquisition import aq_inner
from zope.component import getUtility
from zope.intid.interfaces import IIntIds
from zope.security import checkPermission
from zc.relation.interfaces import ICatalog

def back_references(source_object, attribute_name):
    """ Return back references from source object on specified attribute_name """
    catalog = getUtility(ICatalog)
    intids = getUtility(IIntIds)
    result = []
    for rel in catalog.findRelations(
                            dict(to_id=intids.getId(aq_inner(source_object)),
                                 from_attribute=attribute_name)
                            ):
        obj = intids.queryObject(rel.from_id)
        if obj is not None and checkPermission('zope2.View', obj):
            result.append(obj)
    return result

rawDescription: Reverse reference RelationList in Dexterity type


code:
out_files = []
for root, dirs, filenames in os.walk('.'):
   for filename in fnmatch.filter(filenames, '???[0-9][0-9][0-9][0-9]????*.txt'):
       if(1 <= int(filename[3:7]) <= 146):
           out_files.append(os.path.join(root, filename))

rawDescription: File name matching with fnmatch

description: File name matching with fnmatch


code:
class Foo:
    # String bar;  <-- useless declaration is useless
    def __init__(self):
        self.bar = "xyz"

rawDescription: Why does Python seem to treat instance variables as shared between objects?


code:
root_element_name = "XMLROOT"  # this can be anything
rooted_html = "<{0}>\n{1}\n</{0}>".format(root_element_name, html)
soup = bs4.BeautifulSoup(rooted_html, features="xml")

rawDescription: Beautifulsoup HTML data extraction with BeautifulSoup and Python


code:
class PlottingInteractive:
    add_slice = wrap_pylab_newplot(add_slice)

rawDescription: What are your (concrete) use-cases for metaclasses in Python?


code:
import json
s = "'type': 'singlechoice',        'add_to_user_messages': false,        'text': 'See you tomorrow',        'next': '31'"
modified_s = '{' + s.replace("'", '"') + '}'
json.loads(modified_s)

rawDescription: Reading comma separated string values as dictionary elements in python


code:
import isoweek
isoweek.Week.last_week_of_year(2014)
isoweek.Week.last_week_of_year(2014).week

rawDescription: The number of calendar weeks in a year?

description: The number of calendar weeks in a year


code: A = [None if item == 1 else item for item in A]

rawDescription: Delete elements in a list and retaining the size of a list in Python?


code:
mySphere = cmds.sphere()
print(mySphere)
# Result: [u'nurbsSphere1', u'makeNurbSphere1']

print(mySphere[0])  # the first element in the list is the object name
# Result: nurbsSphere1

rawDescription: Maya transform node not appearing in list


rawDescription: How to store values in list based on another list and tuple

description: Store values in list based on another list and tuple


code:
from collections import defaultdict
import re

ip_freq = defaultdict(int)
with open("auth", "r") as fh:
    for match in re.finditer(r'Failed password for (?:root|invalid user\s?.*) from ((?:\d{1,3}\.){3}\d{1,3}) ', fh.read()):
        ip_freq[match.group(1)] += 1

with open("bad_ips.log", "w") as fh:
    for ip, n in ip_freq.iteritems():
        if n>=13:
            print >>fh, ip

rawDescription: Python - splitting a list then loop through to find an ip address


code:
pl.imshow(values, origin='lower', extent=[0, max(X), 0, max(Y)],
          aspect='auto', cmap=pl.get_cmap('YlOrRd'))

rawDescription: Plot (x, y, z) triples on 2d plane with a colormap


code:
line = '%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1)
with open('output', 'a') as opfile: # This creates the file if it does not exist and opens it in the append mode
    opfile.write(line)
opfile.close()

rawDescription: How to save my variables to a txt file from a program

description: Save my variables to a txt file from a program


code:
timedelta(hours=3)
timedelta(hours=2)
timedelta(hours=3) + timedelta(hours=2)

rawDescription: How to get the sum of timedelta in Python?

description: Get the sum of timedelta in Python


rawDescription: Row counting with conditional range

description: Row counting with conditional range


code:
# Do something which enqueues a task.

# Check that a task was enqueued, then execute it.
self.assertTrue(len(self.get_tasks()), 1)
self.execute_tasks(some_module.application)

# Now test that the task did what was expected.

rawDescription: GAE: unit testing taskqueue with testbed


code:
def rotations24(polycube):
    # imagine shape is pointing in axis 0 (up)

    # 4 rotations about axis 0
    yield from rotations4(polycube, 0)

    # rotate 180 about axis 1, now shape is pointing down in axis 0
    # 4 rotations about axis 0
    yield from rotations4(rot90(polycube, 2, axis=1), 0)

    # rotate 90 or 270 about axis 1, now shape is pointing in axis 2
    # 8 rotations about axis 2
    yield from rotations4(rot90(polycube, axis=1), 2)
    yield from rotations4(rot90(polycube, -1, axis=1), 2)

    # rotate about axis 2, now shape is pointing in axis 1
    # 8 rotations about axis 1
    yield from rotations4(rot90(polycube, axis=2), 1)
    yield from rotations4(rot90(polycube, -1, axis=2), 1)

def rotations4(polycube, axis):
    """List the four rotations of the given cube about the given axis."""
    for i in range(4):
        yield rot90(polycube, i, axis)

rawDescription: How to calculate all 24 rotations of 3d array?

description: Calculate all 24 rotations of 3d array


rawDescription: Dictionary __gt__ and __lt__ implementation


code:
l = []
d = {}
d['key'] = 4
l.append(d.copy())
d['key'] = 5
l.append(d.copy())

rawDescription: Making a list of a "master" dictionary

description: Making a list of a "master" dictionary


code: A.objects.filter( Q(b__x=1) | Q(c__y=2)).distinct()

rawDescription: Full outer Join in Django with all columns (null if not existing)


code:
MC = MaClasse()
MC.dessiner_lignes(points)
MC.maclasse()

rawDescription: Draw same lines drawn on a Tkinter Canvas on an OpenCV image


code:
movies
# <generator object find at 0x10b64acd0>

rawDescription: py2neo (1.6) how to get an existing node by node property without CypherQuery

description: Py2neo (1.6) how to get an existing node by node property without CypherQuery


code: image = models.ImageField(upload_to='products/img', blank=True)

rawDescription: Django - Images not displaying properly

description: Django - Images not displaying properly


code:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X1)
output = scaler.transform(X2)

rawDescription: scale two matrices with scipy or sklearn

description: Scale two matrices with scipy or sklearn


code:
Hostname: www.google.com
({'issuer': ((('countryName', 'US'),),
             (('organizationName', 'Google Inc'),),
             (('commonName', 'Google Internet Authority G2'),)),
  'notAfter': 'Sep 11 11:04:38 2014 GMT',
  'notBefore': 'Sep 11 11:04:38 2013 GMT',
  'serialNumber': '50C71E48BCC50676',
  'subject': ((('countryName', 'US'),),
              (('stateOrProvinceName', 'California'),),
              (('localityName', 'Mountain View'),),
              (('organizationName', 'Google Inc'),),
              (('commonName', 'www.google.com'),)),
  'subjectAltName': (('DNS', 'www.google.com'),),
  'version': 3},
 {'issuer': ((('countryName', 'US'),),
             (('organizationName', 'GeoTrust Inc.'),),
             (('commonName', 'GeoTrust Global CA'),)),
  'notAfter': 'Apr  4 15:15:55 2015 GMT',
  'notBefore': 'Apr  5 15:15:55 2013 GMT',
  'serialNumber': '023A69',
  'subject': ((('countryName', 'US'),),
              (('organizationName', 'Google Inc'),),
              (('commonName', 'Google Internet Authority G2'),)),
  'version': 3},
 {'issuer': ((('countryName', 'US'),),
             (('organizationName', 'Equifax'),),
             (('organizationalUnitName',
               'Equifax Secure Certificate Authority'),)),
  'notAfter': 'Aug 21 04:00:00 2018 GMT',
  'notBefore': 'May 21 04:00:00 2002 GMT',
  'serialNumber': '12BBE6',
  'subject': ((('countryName', 'US'),),
              (('organizationName', 'GeoTrust Inc.'),),
              (('commonName', 'GeoTrust Global CA'),)),
  'version': 3},
 {'issuer': ((('countryName', 'US'),),
             (('organizationName', 'Equifax'),),
             (('organizationalUnitName',
               'Equifax Secure Certificate Authority'),)),
  'notAfter': 'Aug 22 16:41:51 2018 GMT',
  'notBefore': 'Aug 22 16:41:51 1998 GMT',
  'serialNumber': '35DEF4CF',
  'subject': ((('countryName', 'US'),),
              (('organizationName', 'Equifax'),),
              (('organizationalUnitName',
                'Equifax Secure Certificate Authority'),)),
  'version': 3})

rawDescription: Getting certificate chain with Python 3.3 SSL module


code:
def how_many_to_pick(N, M, prob):
    """
    Given a deck of N cards, M of which are marked,
    how many do you have to pick randomly without replacement
    to have at least prob probability of picking at least one marked card?
    """
    for q in xrange(1, M+1):
        if pick_Q(N, M, q) >= prob:
            return q
    raise ValueError("Could not find a value for q")

rawDescription: Drawing cards from a deck in SciPy with scipy.stats.hypergeom


code: import mp_guard

rawDescription: Preventing multiprocessing "runaway bugs"


rawDescription: python 2.7 username with minimum and max

description: Python 2.7 username with minimum and max


code:
squarer = maker(2)

print(squarer(2)) # outputs 4
print(squarer(4)) # outputs 16
print(squarer(8)) # outputs 64

rawDescription: Python Factory Function

description: Python Factory Function


code:
df2 = df.unstack().copy()
df2.sort()
df2[-3:]
df2[-3:].index

rawDescription: index and column for the max value in pandas dataframe

description: Index and column for the max value in pandas dataframe


code:
x = object()
getattr(x, 'foo')
getattr(x, 'foo', 42)

rawDescription: Why use setattr() and getattr() built-ins?


code:
nodes = {0: True, 1: True, 2: True,
         3: False, 4: False, 5: False,
         6: True, 7: True, 8: False, 9: False}

print("Marked nodes: ", *[i for i, value in nodes.items() if value])
print("Unmarked nodes: ", *[i for i, value in nodes.items() if not value])

rawDescription: How to print with inline if statement?

description: Print with inline if statement


code:
hdf_d = {'test_dset':mock}
def getitem(name):
##    print 'getitem', name
    return hdf_d[name]
def setitem(name, value):
    hdf_d[name] = value
mock_hdf = mock.MagicMock()
mock_hdf.__getitem__.side_effect = getitem
mock_hdf.__setitem__.side_effect = setitem

rawDescription: Test if some field has been initialized in python


code:
import csv
from scrapy import signals

class SortedCSVPipeline(object):

    def __init__(self):
        self.items = []
        self.file_name = r'YOUR_FILE_PATH_HERE'
        self.key = 'YOUR_KEY_HERE'

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_closed(self, spider):
        for item in sorted(self.items, key=lambda k: k[self.key]):
            self.write_to_csv(item)

    def process_item(self, item, spider):
        self.items.append(item)
        return item

    def write_to_csv(self, item):
       writer = csv.writer(open(self.file_name, 'a'), lineterminator='\n')
       writer.writerow([item[key] for key in item.keys()])

rawDescription: Python Scrapy function to be called just before spider_closed signal sent?


rawDescription: Python regex for matching bb code

description: Python regex for matching bb code


code:
RATING_CHOICES = list(enumerate(['', 'Disappointed', 'Not Promissing',
                                 'OK', 'Good', 'Awesome']))

class Review(models.Model):
    ...
    rating = models.IntegerField(..., choices=RATING_CHOICES)

rawDescription: Accessing list item in django template

description: Accessing list item in django template


code:
total = 0
while True:
  grocery = input('Enter an item: ')
  if grocery == 'EXIT':
       print('Your final total is $%s' %total)
       break
  else:
       cost = groceries[grocery]
       total += cost
       print('Your current total is $%s' %total)

rawDescription: Reading a .txt into a definition

description: Reading a .txt into a definition


code: '''This class contains a bunch of |Foo| objects'''

rawDescription: In Sphinx, can I register a bunch of keywords that should always be translated into links?


code:
def similarity(alist):
  position = 0
  while position < len(alist):
    item = alist[position]
    position += 1
    # code here that modifies alist

rawDescription: for-in loop's upper limit changing in each loop

description: For-in loop's upper limit changing in each loop


code:
import urllib
import bs4
url = "http://yourURL.com"
html = urllib.urlopen(url).read()
soup = bs4.BeautifulSoup(html)

rawDescription: Print all elements in <li> - BeautifulSoap


rawDescription: Python: Read line by line, performing an operation at each end line


code: np.random.choice(a, size=n, p=w)

rawDescription: Probabilistic selection from a numpy array


code:
for i, label in enumerate(["Argonian", "Khajiit"]):
    mb.menu.add_command(label=label, command=lambda: changename(i))

rawDescription: Creating a drop down menu item selection Python


code:
mainscreen = MainScreen()
mainlayout = MainLayout()
mainscreen.add_widget(mainlayout)

rawDescription: Associating Screens with GridLayout classes in kivy


code:
import numpy as np
import pandas as pd

shape = (5,2,3,4)
SM = np.arange(np.prod(shape)).reshape(shape)
dates = pd.date_range('2000-1-1', periods=shape[0], freq='12H')
zlevel = np.arange(shape[1])
lat = np.arange(shape[2])
lng = np.arange(shape[3])

rawDescription: Python Pandas Panel4D resample

description: Python Pandas Panel4D resample


rawDescription: Python transform current list into 2d

description: Python transform current list into 2d


rawDescription: Escape string to be valid python expression


code:
from operator import not_
list(dropwhile(not_, lines))

rawDescription: Additional condition in Python list comprehension


code:
import json
import requests

class ATTSpeech:
    CLIENT_ID = "SOME"
    CLIENT_SECRET = "ID"
    TOKEN = None

    def __init__(self, *args, **kwargs):
        self.get_token()

    def get_token(self):
        # Get Access Token via OAuth.
        # https://matrix.bf.sl.attcompute.com/apps/constellation-sandbox
        response = requests.post("https://api.att.com/oauth/token", {
            "client_id": self.CLIENT_ID,
            "client_secret": self.CLIENT_SECRET,
            "grant_type": "client_credentials",
            "scope": "SPEECH,STTC"
        })
        content = json.loads(response.content)
        self.TOKEN = content["access_token"]

    def text_from_file(self, path):

        with open(path, 'rb') as f:
            response = requests.post("https://api.att.com/speech/v3/speechToText",
                headers = {
                    "Authorization": "Bearer %s" % self.TOKEN,
                    "Accept": "application/json",
                    "Content-Type": "audio/wav",
                    "X-SpeechContext": "Generic",
            }, data=f)
        content = json.loads(response.content)
        return content

rawDescription: Using the AT&T Speech to Text API With Python


code: ['she also loves to play chess.']

rawDescription: How can I take a few paragraphs of text, see if any sentence has a pronoun and select all those sentences to make a new paragraph?

description: Take a few paragraphs of text, see if any sentence has a pronoun and select all those sentences to make a new paragraph


rawDescription: Python: Compare 2 lists of tuples of different size


code:
import webapp2
import os #added
from google.appengine.ext.webapp import template #also added

class MainPage(webapp2.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, {}))

class Guestbook(webapp2.RequestHandler):
    def post(self): #didn't change this
        self.response.write('You wrote:
')
        self.response.write(cgi.escape(self.request.get('content')))
        self.response.write('
')

application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook), ], debug=True)

rawDescription: How to load .html page with python on app-engine

description: Load .html page with python on app-engine


code:
json.loads('{"foo": 1.234567890123456789}',
           parse_float=decimal.Decimal,
           parse_int=decimal.Decimal,
           parse_constant=decimal.Decimal)

rawDescription: Decimal(str(my_float)) seems to be better than Decimal(my_float), what's going on?


code:
import random
import string
import pandas as pd
import numpy as np

city = random.sample(string.lowercase*500,100)
raingarden = np.random.randint(0,10,100)

out = pd.DataFrame({'city':city, 'raingarden':raingarden})

rawDescription: Tabulate data frame with groupby and size methods


rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
import sqlacodegen
sqlacodegen --help

rawDescription: How to run sqlacodegen?

description: Run sqlacodegen


rawDescription: Numpy matrix row stacking

description: Numpy matrix row stacking


code:
import Foundation
# ...
bundle = Foundation.NSBundle.mainBundle()
path = bundle.pathForResource_ofType_('foo', None)

rawDescription: Can executables made with py2app include other terminal scripts and run them?


code:
def validated_route_path(request, *args, **kwargs):
    route_name = args[0]
    path = request.route_path(*args, **kwargs)
    route_intr = request.registry.introspector.get('routes', route_name)
    route = route_intr['object']
    if route.match(path) is None:
        raise ValueError('invalid url generated')
    return path

config.add_request_method(validated_route_path)

request.validated_route_path('numbers', n='chicken') # -> ValueError

rawDescription: How to ensure URLs generated by Pyramid's route_url and route_path are valid?

description: Ensure URLs generated by Pyramid's route_url and route_path are valid


code:
with open('filename') as f:
   table_data = [ line.split() for line in f]

rawDescription: use file content to create a nested list in python

description: Use file content to create a nested list in python


code:
from forms_builder.forms.models import Form

def get_form(request, slug, pk):
    form_obj = Form.objects.get(slug=slug)
    form_instance = form_obj.entries.get(pk=pk)
    form = FormForForm(form=form_obj, instance=form_instance, context=request)
    return render_to_response('update_form.html', {'form':form_instance.form, 'request':request})

rawDescription: django-forms-builder. How do I update a form?

description: Django-forms-builder. How do I update a form


code:
print(list(tree.entry.iterchildren()))
# ['Hello World!', 'USA']

rawDescription: Using objectify to get items with a different namespace prefix


code:
lst = [7, 8, 7]
bytes(lst)

rawDescription: Python writing binary

description: Python writing binary


code:
def pdf_encode(pdf_filename):
    return open(pdf_filename,"rb").read().encode("base64");

rawDescription: Converting a PDF file to Base64 to index into Elasticsearch


rawDescription: Equivalent of "genvarname" in Python

description: Equivalent of "genvarname" in Python


rawDescription: Pythonic way to return list of every n'th item in a larger list


code:
toroidal.connect_to(cartesian,[eta,theta,psi],
[(a*sinh(eta)*cos(psi))/(cosh(eta) - cos(theta)),
 (a*sinh(eta)*sin(psi))/(cosh(eta) - cos(theta)),
 (a*sin(theta))/(cosh(eta) - cos(theta))], inverse=False)

rawDescription: Using sympy.diffgeom.CoordSystem to connect two coordinate systems


code:
import mpmath
mpmath.mp.dps = 100
def chi2_cdf(k,x): return mpmath.gammainc(x/2.0,0,k/2.0)/mpmath.gamma(x/2.0)
chi2_cdf(332.185545938, 18.8967858326)
float(1-_)

rawDescription: stats.scipy.chi2 returns value of 0.0

description: Stats.scipy.chi2 returns value of 0.0


rawDescription: Ansible lineine file with regex is adding new line when it shouldn't


code: names = g.vs[sorted_eigen]["name"]

rawDescription: How to get name property out of the result of eigenvalue in igraph?

description: Get name property out of the result of eigenvalue in igraph


code:
import numpy as np
# 500 arrays of random numbers
x = [np.random.rand(100) for _ in xrange(500)]
y = np.vstack(x)
y.shape
y.argmax(axis=0)
y.argmax(axis=0).shape

rawDescription: Cascading numpy logical_and leads to memory error


code:
from django.db.models.base import ModelBase

class CustomModelMetaClass(ModelBase):

    def __new__(cls, name, bases, attrs):
        klas = super(CustomModelMetaClass, cls).__new__(cls, name, bases, attrs)
        klas._meta.verbose_name_plural = klas._meta.verbose_name

        return klas

rawDescription: Django admin model plural mode global settings, not adding suffix 's'


code:
Output
{'AAAX': 'id2', 'AAAC': 'id3', 'AAAD': 'id3', 'AAAF': 'id1'}

rawDescription: Iterate and match in large files in python


code: blueprint = Blueprint('login', __name__, url_prefix='/login')

rawDescription: Can multiple webpages be implemented using a single Flask app?


code:
import functools

...

fooA = functools.partial(call_one, _fooA)
fooB = functools.partial(call_one, _fooB)

rawDescription: Code refactoring with python decorators?

description: Code refactoring with python decorators


code:
parser.add_argument('-n', '--noprompt', action='store_true')
parser.parse_args(''.split())
parser.parse_args('--noprompt'.split())
parser.parse_args('-n'.split())

rawDescription: Python CLI - Answer yes to all user questions


code:
xm
ym

rawDescription: MATLAB to Python Conversion Arrays

description: MATLAB to Python Conversion Arrays


code:
import Tkinter as tk
root = tk.Tk()

label = tk.Label(root, text = 'Label')
label.grid(column = 3, row = 8)

button = tk.Button(root, text = 'Button')
button.grid(column = 5, row = 1)

root.grid_columnconfigure(4, minsize=100)  # Here

rawDescription: Tkinter.grid spacing options?

description: Tkinter.grid spacing options


code: df_result.apply(get_col_name, axis=1)

rawDescription: Get column name where value is something in pandas dataframe


code: from urlparse import parse_qs

rawDescription: Regular Expression to extract parts of Twitter query


code:
l = [[1,2,3], [4,5], [], [6,7,8,9]]
import itertools
list(itertools.izip_longest(*l, fillvalue=""))

rawDescription: Python: transposing uneven rows into columns


code: re.sub(pattern, repl, string, count=0)

rawDescription: Replacing a single character by a substring in python 3


code:
event.add('summary').value = 'your summary'
event.add('dtstart').value = datetime.now() # or anything else
...

rawDescription: Create "downloadable" vCalendar object for Outlook with vObject (Python)


code: start, stop = 0, start

rawDescription: How Python's a, b = b, a works?

description: How Python's a, b = b, a works


code:
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def reset(self):
        HTMLParser.reset(self)
        self.links = []

    def handle_starttag(self, tag, attr):
        if tag == 'a':
            href = [v for k, v in attr if k == "href"]
            self.links.append(href[0])
            print(self.getpos())

parser = MyHTMLParser()
parser.feed('''
<!DOCTYPE html>

            <meta charset="UTF-8">
            <title></title>

    ''')
parser.close()
print(parser.links)

rawDescription: Python: SGMLParser can't get line number


code: strdata.append(json.dumps(data, default=lambda o: o.__dict__))

rawDescription: Not about to deserialize json kept as string in Python using json.load


code:
import scipy.stats as stats

def f(i):
    return i
n, p = 5000, 0.5
print(stats.binom.expect(f, (n, p), lb=0, ub=n))
# 2499.99999997

rawDescription: Log-computations in Python

description: Log-computations in Python


code:
import datetime
d = datetime.datetime(2015, 7, 11, 13, 30)
d.day
d.hour
d.minute

rawDescription: Reformatting Dates after strptime Python


rawDescription: in NetworkX cannot save a graph as jpg or png file

description: In NetworkX cannot save a graph as jpg or png file


code:
reqSocket.connect(self._reqAddress)
reqSocket.send_multipart([repId, message])
reply = reqSocket.recv_multipart()[0]

rawDescription: ZMQ Python Request Reply Broker for Addressed Asynchronous Requests


code:
fileHandler = logging.handlers.RotatingFileHandler('file.log', mode='a', maxBytes=10000, backupCount=5)
logger = logging.getLogger('netmap')

if LOG_TO_FILE:
    logger.addHandler(fileHandler)

rawDescription: Logging in Python with Config File - Using handlers defined in file through code


rawDescription: three.js to webGL to OpenGL

description: Three.js to webGL to OpenGL


code:
N = numpy.sqrt(U**2+V**2)  # there may be a faster numpy "normalize" function
U2, V2 = U/N, V/N

rawDescription: Matplotlib quiver scale

description: Matplotlib quiver scale


rawDescription: How to replace years without leading zeros, with leading zeros using Python re?

description: Replace years without leading zeros, with leading zeros using Python re


rawDescription: remove something from each individual element from the array

description: Remove something from each individual element from the array


code:
from __future__ import division
from math import ceil

def make_combos(max_val,target_sum,n_cells):
    highest = min(max_val, target_sum - n_cells + 1)
    lowest = int(ceil(target_sum/n_cells))
    for x in xrange(highest, lowest-1, -1):
        if n_cells == 1:
            yield (x,)
            break
        for combo in make_combos(x, target_sum-x, n_cells-1):
            yield (x,)+combo

if __name__ == '__main__':
    import pprint
    pprint.pprint(list(make_combos( 6,12,4)))

rawDescription: KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm


code:
import time

MIN_TIME_DELTA = 120

last_call = time.clock() - (MIN_TIME_DELTA+1)  # init to longer than delta ago
while not exit_condition:
    if test:
        otherFunction()
    if test:
        anotherFunction()
    if test and ((time.clock()-last_call) > MIN_TIME_DELTA):
        last_call = time.clock()
        myFunction()

rawDescription: Python - looking for a way to stop a function being called temporarily in a infinte while loop


code:
def hotels(request, country, region):
    pass

rawDescription: How would I pass a calculated parameter to a url in Django


code:
class DataBase(object):
    @staticmethod
    def execute_some_query(query):
        code_here()
        some_code()
    @staticmethod
    def close_database():
        proceed_to_close()
import atexit ; atexit.register(DataBase.close_database)

rawDescription: Method that gets called on module deletion in Python


code:
import gmpy2
import sys
a=long('1'*750000, 2)
sys.getsizeof(a)
sys.getsizeof(gmpy2.mpz(a))

rawDescription: Put python long integers into memory without any space between them


code: fd = open('c:\\anotherdir\\myfile.txt')

rawDescription: Distinction Between CWD and Import Search Path in Python?


rawDescription: Faster way to do `A[tuple(B.T)]` in Numpy


code:
import win32com.client
import re

xl = win32com.client.Dispatch('Excel.Application')
xl.Visible=True
wb = xl.Workbooks.Add()
ws = wb.Sheets(1)
values = [['a','b','c'],
          [ 1,  2,  3 ],
          [ 4,  5,  6 ]]
for nrow, row in enumerate(values):
    for ncol, item in enumerate(row):
        xl.Cells(nrow+1, ncol+1).Value = item

xl.Range("A1:C3").Select()
chart = xl.Charts.Add()

# chart.Legend.Delete only works while it's a chart sheet.
# so get this done before changing the chart location!
chart.Legend.Delete()

# Excel changes the name of the chart when its location is changed.
# The new name inserts a space between letters and numbers.
# 'Chart1' becomes 'Chart 1'
new_chart_name = re.sub(r'(\D)(\d)', r'\1 \2', chart.Name)
chart.Location(2, ws.Name)

# After changing the location the reference to chart is invalid.
# We grab the new chart reference from the Shapes collection using the new name.
# If only one chart is on sheet you can also do: chart = ws.Shapes(1)
chart = ws.Shapes(new_chart_name)

chart.Top = 1
chart.Left = 1
chart.Width = 500
chart.Height = 400

rawDescription: Delete legend in an Excel plot with Python and win32com


code: roidata = np.vstack([bigarray[:,i,j] for i,j in zip(*roipixels)])

rawDescription: PyTables: indexing multiple dimensions of large arrays


code:
from __future__ import with_statement
with_statement.getOptionalRelease()
with_statement.getMandatoryRelease()

rawDescription: Which python version needs from __future__ import with_statement?


code: py_loglevel = getattr(logging, self.loglevel, logging.DEBUG)

rawDescription: Python oneline switch

description: Python oneline switch


code:
avg = sum(datetimes, datetime.timedelta(0)) / len(datetimes)
avg = avg - datetime.timedelta(microseconds=avg.microsecond)

rawDescription: Python timedelta remove microseconds

description: Python timedelta remove microseconds


code:
import re
def consecCheck(s):
    return bool(re.search(r'(.)\1', s))
consecCheck("apple")
consecCheck("candyman")

rawDescription: check 2 consecutive occurrences of the same letter

description: Check 2 consecutive occurrences of the same letter


code:
from zope.interface.interface import InterfaceClass
from zope import schema

def add_visibility_fields(iface):
    fields = {}
    for name, attr in iface.namesAndDescriptions():
        if isinstance(attr, schema.Field):
            fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)

    return InterfaceClass(iface.__name__, (iface,), fields)

rawDescription: How to dynamically add attributes to an interface

description: Dynamically add attributes to an interface


code:
class Foo(object):
    # assuming you've added a self argument to the previous function
    framework_dependent_method = framework_dependent_function

rawDescription: Importing in functions instead of at the beginning or the script?


code:
modelDict = DictModelAdaptor(DictModel)
modelDict["name"] = "Bob Jones"

rawDescription: Django: Converting an entire set of a Model's objects into a single dictionary


code:
from collections import Counter
from itertools import chain
list_of_lists = [[9, 7, 5, 3, 1], [2, 1, 3, 2, 5, 3, 7], [3, 5, 8, 1]]
Counter(i for nested in list_of_lists for i in nested)
Counter(chain.from_iterable(list_of_lists))

rawDescription: Fast dictionary population with list of keys


code:
x = 1
y = lambda : x
print(y()) # will print 1
x = 2
print(y()) # will print 2; lambda captures variables, not values

rawDescription: How do you use the same function as the command for multiple buttons created in a loop?

description: Use the same function as the command for multiple buttons created in a loop


code:
('Test_Group_A', 'network_object_group')
Host1
Host2
Host3
Host4
Host5
Host6

rawDescription: Python Looping with etree

description: Python Looping with etree


code:
import numpy as np
import ctypes
from multiprocessing import Array, Process

def main():
    buf = Array(ctypes.c_int8, 10) # 10 byte buffer

    with buf: # acquire lock
        ctypes_arr = buf.get_obj()
        arr = np.frombuffer(ctypes_arr, dtype=np.int16) # int16 array, with size 5
        total = arr.sum()
        del arr, ctypes_arr # losing lock, delete local reference to the buffer

    print("total before:", total) # 0

    p = Process(target=subprocess_target, args=(buf,))
    p.start()
    p.join()

    with buf:
        # interpret first 8 bytes as two 4 byte ints
        view = memoryview(buf.get_obj())[:8]
        arr = np.frombuffer(view, dtype=np.int32)
        total = arr.sum()
        del arr, view

    print("total after:", total) # 262146
    raw_bytes = list(buf.get_obj())
    assert raw_bytes == [0, 0, 1, 0, 2, 0, 3, 0, 4, 0]

def subprocess_target(buf):
    """Sets elements in buf to [0, 1, ..., n-2, n-1]"""
    with buf:
        arr = np.frombuffer(buf.get_obj(), dtype=np.int16)
        arr[:] = range(len(arr))
        del arr

if __name__ == "__main__":
    main()

rawDescription: Define Ctypes array that overlaps in memory for numpy array and multiprocessing


code:
for key in myDictionary:
    entries = myDictionary[key]
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

rawDescription: Python 3 - Print Specific List Item from Dictionary


rawDescription: Python: How to remove whitespace from number in a string


rawDescription: Sharing scope in Python between called and calling functions


code:
for row in csvReader:
  c.execute(sql_statement, row)

rawDescription: this python script can be shortened/optimized, how?

description: This python script can be shortened/optimized, how


code:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, _ = p.communicate()
do_something_with(out)

rawDescription: In a Python 2.4 script, I would like to execute a os system call `ls -l` or `curl` for example and capture the output in a variable. How to do this?


code:
new_episodes = []
for name, it in groupby(episodes, lambda x: x[0]):
    new_episodes.extend(deque(it, maxlen=2))

rawDescription: Move last two episodes from directory in Python?


code:
#@PydevCodeAnalysisIgnore
import pyodbc
class DbMain(object):
    def __init__(self):
        # make cnxn an attribute of the instance
        self.cnxn = pyodbc.connect(driver='{SQL Server}', server='server',
            database='database', uid='name', pwd='pwd')

    # receive `self` explicitly
    def getRow(self):
        cursor = self.cnxn.cursor()
        cursor.execute("select user_id, user_name from users")
        row = cursor.fetchone()
        # actually return something
        return row

rawDescription: Python method doesn't run in class

description: Python method doesn't run in class


code:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

ab = zip(a, b)  # generator expression created by the zip function
aabb = list(ab) # element read from ab, disposed, placed in a list

print(list(ab)) # now ab has nothing because it was disposed

rawDescription: python list(zipobject) returns empty (list) container

description: Python list(zipobject) returns empty (list) container


code: locations[destination]

rawDescription: Python raw_input a variable name

description: Python raw_input a variable name


code:
def factorial(x):
    return x * factorial(x-1)

rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


rawDescription: Pandas: how to broadcast values by specific column rather than index when doing arithmetic operation?


code:
x, y, z = symbols('x y z')
expr = sympify('x/z - y')
expr.subs({x: 10, y: 5})

rawDescription: Using SymPy to generically parse and solve equations


code:
@api_view(['GET'])
def current_user(request):
    serializer = UserSerializer(request.user)
    return Response(serializer.data)

rawDescription: Return the current user with Django Rest Framework


code:
class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code:
key = ndb.Key('WikiPage','hello')
entity = key.get()
entity = WikiPage.get_by_id(key.id())

rawDescription: Google App Engine: defining custom id and querying


code:
sig = inspect.signature(test)
{name: param.default for name, param in sig.parameters.items()
 if not param.default is param.empty}

rawDescription: How can I access the default value for a keyword argument in Python?

description: Access the default value for a keyword argument in Python


code:
names = list(legislators.keys())
parties = list(legislators.values())

print(names)
['Tsang Yok-sing', 'Lee Cheuk-yan', 'James To', 'Chan Kam-lam', 'Lau Wong-fat', 'Emily Lau', 'Albert Ho']

print(parties)
['DAB', 'Labour', 'Democratic', 'DAB', 'Economic Synergy', 'Democratic', 'Democratic']

rawDescription: Creating a list from specific elements of a dictionary


code:
for k in sorted(somedictionary.keys()):
    doSomething(k)

rawDescription: in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order?

description: In python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order


code:
def bilinear_interpolation(x, y, points):
    '''Interpolate (x,y) from values associated with four points.

    The four points are a list of four triplets:  (x, y, value).
    The four points can be in any order.  They should form a rectangle.

        >>> bilinear_interpolation(12, 5.5,
        ...                        [(10, 4, 100),
        ...                         (20, 4, 200),
        ...                         (10, 6, 150),
        ...                         (20, 6, 300)])
        165.0

    '''
    # See formula at:  http://en.wikipedia.org/wiki/Bilinear_interpolation

    points = sorted(points)               # order points by x, then by y
    (x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = points

    if x1 != _x1 or x2 != _x2 or y1 != _y1 or y2 != _y2:
        raise ValueError('points do not form a rectangle')
    if not x1 <= x <= x2 or not y1 <= y <= y2:
        raise ValueError('(x, y) not within the rectangle')

    return (q11 * (x2 - x) * (y2 - y) +
            q21 * (x - x1) * (y2 - y) +
            q12 * (x2 - x) * (y - y1) +
            q22 * (x - x1) * (y - y1)
           ) / ((x2 - x1) * (y2 - y1) + 0.0)

rawDescription: How to perform bilinear interpolation in Python

description: Perform bilinear interpolation in Python


code:
from string import ascii_lowercase as al
def find_vo_cons(strs,val):
    vowels="aeiou"
    consonants=set(al)-set(vowels) #set containing only consonants
    le=float(len(strs))

    vowel_count=0
    consonant_count=0

    for x in strs:
        if x.lower() in vowels:
            vowel_count+=1
        elif x.lower() in consonants:
            consonant_count+=1

    if val in ("V","v"):
        return vowel_count/le
    elif val in ("C","c"):
        return consonant_count/le

def main():
    VOCO = input("Search for VOWELS(v) or CONSONANTS(c): ")
    dic={"v":"Vowels","c":"Consonants"}
    strs=  input("Enter the string: ")
    print ("The average of {0} count is {1}".format(dic[VOCO.lower()],find_vo_cons(strs,VOCO)))

main()

rawDescription: I can't seem to make it find the average consonants/vowels after the user inputs it


code:
import datetime
target_time = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond = 0)
now = datetime.datetime.now()
if target_time < now:
    target_time += datetime.timedelta(1)
time_to_go = target_time - now
print(time_to_go)

rawDescription: Python: TimeDate Issue

description: Python: TimeDate Issue


code:
dict(enumerate(winners, 1903))
['{}:{}'.format(winner, year) for year, winner in enumerate(winners, 1903)]

rawDescription: Add a Year to each item in list or Dictionary


code: result = [item for sublist in map(None, a, b) for item in sublist][:-1]

rawDescription: Pythonic way to mix two lists

description: Pythonic way to mix two lists


code: data = dict(zip(strings, numbers))

rawDescription: initialize python dictionary containing a strings and lists

description: Initialize python dictionary containing a strings and lists


rawDescription: Pandas dataframe to list of tuples

description: Pandas dataframe to list of tuples


code:
for *names, id, num in lines:
    print(row.format(' '.join(names), id, num))

rawDescription: python-making strings line up in a column exactly n spaces from left

description: Python-making strings line up in a column exactly n spaces from left


code:
datafile = DatafileModel()
datafile.data = numpy.array((1000,1000))
datafile.save()

rawDescription: pandas dataframe as field in django

description: Pandas dataframe as field in django


rawDescription: Array expansion in numpy

description: Array expansion in numpy


code:
class PeekableQueue:
    def __init__(self, item_getter, maxpeek=50):
        self.getter = item_getter
        self.maxpeek = maxpeek
        self.b = [next(item_getter) for _ in range(maxpeek)]
        self.i = 0

    def pop(self):
        result = self.b[self.i]
        self.b[self.i] = next(self.getter)
        self.i += 1
        if self.i >= self.maxpeek:
            self.i = 0
        return result

    def peek(self, n):
        if not 0 <= n <= self.maxpeek:
            raise ValueError("bad peek argument %r" % n)
        nthruend = self.maxpeek - self.i
        if n <= nthruend:
            result = self.b[self.i : self.i + n]
        else:
            result = self.b[self.i:] + self.b[:n - nthruend]
        return result

q = PeekableQueue(get_tile())

rawDescription: Tetris Random Generator: random.choice with permutations versus random.shuffle


code:
from .forms import OrganizationForm

nameoforganization = session.get('name')

form = OrganizationForm(obj=nameoforganization)

rawDescription: pre-populate wtforms text field with values

description: Pre-populate wtforms text field with values


rawDescription: Suggestion for python regex and selecting columns


code:
class Bill(models.Model):
    ...

    @property
    def total_amount(self):
        return self.sold_amount * self.item.price

rawDescription: Combined value from multiple models

description: Combined value from multiple models


code:
import pandas as pd

df1 = pd.read_csv("coord1.csv")
df2 = pd.read_csv("coord2.csv")
combined = df1.merge(df2, how='outer').fillna(0)
combined.sort(list(combined.columns[:2]), inplace=True)
combined.to_csv("coord_merged.csv",index=False)

rawDescription: efficient method for merging 2 sorted files with duplicate coordinates in python

description: Efficient method for merging 2 sorted files with duplicate coordinates in python


code:
input_string = ""
while any(c.isdigit() for c in input_string) == False:
    print ("the input string must contain at least one numerical character")
    input_string = input("Please enter a combination: ")

rawDescription: String Validation after input or raw_input in Python


code:
df
ts = pd.to_datetime('2004-05-06')
df = df.set_index('Date')
df
df.loc[df.index < ts]
df.loc[df.index <= ts]

rawDescription: Subset Pandas Dataframe Everything up to a Date


code:
['www.testpage.com/x001&show=more',
 'www.testpage.com/x002&show=more',
 'www.testpage.com/x003&show=more',
 'www.testpage.com/y001&show=more',
 'www.testpage.com/y002&show=more',
 'www.testpage.com/y003&show=more',
 'www.testpage.com/z001&show=more',
 'www.testpage.com/z002&show=more',
 'www.testpage.com/z003&show=more']

rawDescription: How to apply n-times a function with map

description: Apply n-times a function with map


code: spades

rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
from random import sample

def mutate(s, num, target):
    change_locs = set(sample(range(len(s)), num))
    changed = (target if i in change_locs else c for i,c in enumerate(s))
    return ''.join(changed)

rawDescription: Randomly replace items in a list

description: Randomly replace items in a list


code:
import xml.dom.minidom

xmlObject = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xmlObject.toprettyxml()
print(pretty_xml_as_string)

rawDescription: Read an XML file with tags and indentation into a python variable


code:
from scipy import c_
left, right, params = wave_unpack(fn)
fs = params[2]
left_float  =  left.astype('f')/2**15
right_float = right.astype('f')/2**15
stereo = c_[left_float, right_float]
input = mono = stereo.mean(1)

rawDescription: How would I play audio in Python 2.6.6 while displaying text?


code:
class Base1(object):
    def create(self): ...

class Base2(object):
    def create(self): ...

class C(Base1, Base2):
    def create(self): ...

rawDescription: Class Inheritence Naming in Python

description: Class Inheritence Naming in Python


code:
adict = {}

for key, items in groupby(FilteredTable1[1:], itemgetter(0)):
    #print key
    for subitem in items:
        #print ' ', subitem
        entry_id = subitem[EntryID]
        if entry_id not in adict:
            adict[entry_id] = {'EC': [], 'Km': [], 'Kcat': []}

        entry = adict[entry_id]
        if 'ECNumber' in subitem:
            entry['EC'] = subitem[value]

        if 'Km' in subitem and 'Start Value' in subitem:
            entry['Km'] = subitem[value]
            #print subitem

rawDescription: Python - nested dictionary. Where is the bug?


code:
['hash_rate.csv',
 'difficulty.csv',
 'cost_per_tx.csv',
 'block_size.csv',
 'avg_block_size.csv']

rawDescription: Pandas: how to merge horizontally multiple CSV (key,value) files and name `value` columns in the resulting DF using filenames


rawDescription: How can a custom jinja2 tag interface with the context of a flask request


code: modules = {string: getattr(MainModule, string) for string in arr}

rawDescription: How to use from import if I would like to import the module as a String?

description: Use from import if I would like to import the module as a String


code:
import numpy as np
from scipy import stats
from mayavi import mlab

mu, sigma = 0, 0.1
x = 10*np.random.normal(mu, sigma, 5000)
y = 10*np.random.normal(mu, sigma, 5000)
z = 10*np.random.normal(mu, sigma, 5000)

xyz = np.vstack([x,y,z])
kde = stats.gaussian_kde(xyz)
density = kde(xyz)

# Plot scatter with mayavi
figure = mlab.figure('DensityPlot')
pts = mlab.points3d(x, y, z, density, scale_mode='none', scale_factor=0.07)
mlab.axes()
mlab.show()

rawDescription: How to plot a 3D density map in python with matplotlib

description: Plot a 3D density map in python with matplotlib


code: self.secondFrame = MySecondFrame()

rawDescription: Wxpython closing windows

description: Wxpython closing windows


code:
def main():
    print("In room 2")

rawDescription: How to move to the next file in python

description: Move to the next file in python


code:
stringvar = "one;two;three;four"

lst = stringvar.split(";")
stringcount = len(lst)

for idx, value in enumerate(lst):
    globals()["string"+str(idx+1)] = value
    # This is the ugliest code I've ever had to write
    # please never do this. Please never ever do this.

rawDescription: Split and Count a Python String

description: Split and Count a Python String


code:
import struct
import binascii

def unpack(fmt, data):
    """
    Return struct.unpack(fmt, data) with the optional single * in fmt replaced with
    the appropriate number, given the length of data.
    """
    # http://stackoverflow.com/a/7867892/190597
    try:
        return struct.unpack(fmt, data)
    except struct.error:
        flen = struct.calcsize(fmt.replace('*', ''))
        alen = len(data)
        idx = fmt.find('*')
        before_char = fmt[idx-1]
        n = (alen-flen)//struct.calcsize(before_char)+1
        fmt = ''.join((fmt[:idx-1], str(n), before_char, fmt[idx+1:]))
        return struct.unpack(fmt, data)

data = open('data').read()
x = list(unpack("!HLbbs*", data))
# x[-1].encode('hex') works in Python2, but not in Python3
x[-1] = binascii.hexlify(x[-1])
print(x)

rawDescription: Python: unpack format characters

description: Python: unpack format characters


code:
def iter_ancestors(resource):
    yield resource
    while hasattr(resource, '__parent__'):
        resource = resource.__parent__
        yield resource

rawDescription: Pythonic shortcut (syntax sugar) for nested self.__parent__.__parent__


code: s

rawDescription: Remove non numeric values from a Series

description: Remove non numeric values from a Series


code: bars = [rect for rect in ax.get_children() if isinstance(rect, mpl.patches.Rectangle)]

rawDescription: How do I get all bars in a matplotlib bar chart?

description: Get all bars in a matplotlib bar chart


code:
def trimmed_std(data, percentile):
    data = np.array(data)
    data.sort()
    percentile = percentile / 2.
    low = int(percentile * len(data))
    high = int((1. - percentile) * len(data))
    return data[low:high].std(ddof=0)

rawDescription: trimmed/winsorized standard deviation

description: Trimmed/winsorized standard deviation


code:
def sortedEvent(self,action):
    self.whatToDoNext=action.text()

rawDescription: How can I let action execute only now being checked ?

description: Let action execute only now being checked


code:
i = df['A'].map(len)
j = np.repeat(np.arange(len(df)), i)
k = np.concatenate(list(map(np.arange, i)))

rawDescription: Python Pandas - Split different entries into separate rows allowing only certain combinations


code:
names = lst[::3]
numbers = lst[1::3]
emails = lst[2::3]
dct = {name: (number, email)
       for name, number, email
       in zip(names, numbers, emails)}

rawDescription: How do I print the following objects of a list

description: Print the following objects of a list


code: ((x,y) for x in A for y in B)

rawDescription: Performing statistical test on every possible file combination in a folder


code:
@handler("foo")
def on_foo(self):
    return "Hello World!"

def test_addHandler():
    m = Manager()
    m.start()

    m.addHandler(on_foo)

rawDescription: Add/Change channel for handler at runtime


code:
mod = __import__('my_package.my_module', fromlist=['my_class'])
klass = getattr(mod, 'my_class')

rawDescription: How to dynamically load a Python class

description: Dynamically load a Python class


rawDescription: Convert from string containing hexadecimal characters to bytes in python 3


rawDescription: Python - Extract and reformat field names from rows of data


code: hostname = host[0]

rawDescription: How to split the return of socket,gethostbyaddr and write to file?

description: Split the return of socket,gethostbyaddr and write to file


code: x_exists = 'x' in locals() or 'x' in globals()

rawDescription: pythonic way to check if something exists?

description: Pythonic way to check if something exists


code:
points = set((row[1], row[2]) for row in data if row[4])
final_list = [d for d in data if (d[1], d[2]) in points]

rawDescription: Python fastest way to find values in big data


code:
import ctypes
import os
import sys

libc = ctypes.CDLL('libc.so.6')
fs_enc = sys.getfilesystemencoding()

rootPath = "/tmp"
path = os.path.join(rootPath, "AixLib_Mapping_Rule.xml")
path = path.encode(fs_enc)

fd = libc.open(path, 0, 0)

rawDescription: pass a path from python 2 and 3 to c++ using ctypes

description: Pass a path from python 2 and 3 to c++ using ctypes


code:
class MyCornerLabelRenderer(glr.GridLabelRenderer):
    def __init__(self):
        import images
        self._bmp = images.Smiles.getBitmap()

    def Draw(self, grid, dc, rect, rc):
        x = rect.left + (rect.width - self._bmp.GetWidth()) / 2
        y = rect.top + (rect.height - self._bmp.GetHeight()) / 2
        dc.DrawBitmap(self._bmp, x, y, True)

rawDescription: How can I show a bitmap in wxGrid header cell?

description: Show a bitmap in wxGrid header cell


code:
rrss3 = pd.merge(jj1a, jjra, on='driver_trip', how='right').fillna(0.0)
rrss3['prob'] = rrss3['prob_x'] * rrss3['prob_y']
rrss3[['driver_trip', 'prob']].sort('driver_trip')

rawDescription: pandas merge not using sql

description: Pandas merge not using sql


code:
class Bar(Foo):
    pass

rawDescription: Python's equivalent of .Net's sealed class


code: val = x[x.keys()[0]]

rawDescription: access value of a python dict() without knowing the keys

description: Access value of a python dict() without knowing the keys


code: j2 = [i for i in j if i >= 5]

rawDescription: Return list of items in list greater than some value


code:
ListOfRegionsOfInterest = []
for i in range(0, len(RegionsOfInterest)):
    Start = int(RegionsOfInterest[i].split("_")[0])
    Stop  = int(RegionsOfInterest[i].split("_")[1])
    RegionOfInterest = (Start, Stop)
    ListOfRegionsOfInterest.append( RegionOfInterest )

rawDescription: if statement depending on list len

description: If statement depending on list len


rawDescription: python pandas merging data based off 2 keys

description: Python pandas merging data based off 2 keys


code:
import pandas as pd
dataframe1 = pd.read_csv('file1.csv')
dataframe2 = pd.read_csv('file2.csv')
combined = pd.concat([dataframe1, dataframe2]) #the columns will be ordered alphabetically

rawDescription: Rearrange CSV data

description: Rearrange CSV data


code:
class B(A):
    def __init__(self):
        self.__super = super(B)

    def rec(self):
        return self.__super.rec() + 1

rawDescription: Making a class method recognize which class context it's running in


code:
def get_percentile(obs,*args):
    if len(args) == 0:
        args = [25,50,75] # default to quartiles
    lstper = []
    for arg in args:
        lstper.append(np.percentile(obs,arg))
    return lstper

class Metric(object):
    def __init__(self, values=[], percentiles=[]):
        self.max = max(values)
        self.median =np.median(values)
        self.min = min(values)
        self.percentile = get_percentile(values, percentiles)

rawDescription: Python: resolve problems with my Class

description: Python: resolve problems with my Class


code:
inventoryList = [['Steak', 10], ['Milk', 2], ['Fruits', 10], ['Canned Corn', 0.50]]
highestPriceItem = 10.0
highestPriceList = []

for item in inventoryList:
    if item[1] == highestPriceItem:
        highestPriceList.append(item[0])
print ("Item with highest wholsesale price: ",highestPriceList)

rawDescription: How to append a item from a list to another list?

description: Append a item from a list to another list


code:
__all__ = ['myfunc']  # visible names
from math import cos

def myfunc():
    """ documentation"""
    pass

rawDescription: Using pydoc on modules with imported functions


code: [(res, y) for res, y in ((func(x), y) for x, y in input_list) if res]

rawDescription: Python: [(x, y) for (x, y) in list_of_tuples if f(x) is not empty]


code:
def make_engine():
    from IPython.parallel.apps.ipengineapp import IPEngineApp
    lines1 ="a_command()"
    app1 = IPEngineApp()
    app1.url_file = './profiles/security/ipcontroller-engine.json'
    app1.cluster_id = 'e2'
    app1.startup_command = lines1
    app1.init_engine()
    app1.start()

rawDescription: IPython ipengineapp creation with keyword arguments


code:
import numpy as np
npmat = np.asarray(mat)
npmat[:,0]

rawDescription: Accessing the column of the matrix

description: Accessing the column of the matrix


code:
f_dict(listA, listB)
f_numpy(names, values)
rec_groupby(struct_array, ('names',), (('values', np.mean, 'resvalues'),))

rawDescription: Average duplicate values from two paired lists in Python using NumPy


code:
from stuf import stuf

'Hello {user.name}'.format( **stuf({'user': { 'name': 'Markus' } }) )

rawDescription: How to use a dot in Python format strings?

description: Use a dot in Python format strings


code:
def sigmoid(z):
    return 1 / (1+np.exp(-z))

rawDescription: Trying to understand Gradient Checking error in 3-layer Neural Network


rawDescription: Finding all maximal monotone subsequences in python


code:
cmds = [('file1', 'file4'), ('file2', 'file4'), ('file3', 'file4')]
for arg1, arg2 in cmds:
    subprocess.Popen([path_to_program, arg1, arg2])

rawDescription: How to iterate and execute scripts from the command line?

description: Iterate and execute scripts from the command line


rawDescription: Python Prevent readline from converting hex value


code:
for select_field in form.files:
    print(select_field.data)

rawDescription: Creating an N-Amount of Forms using WTForms


code:
def pre_save(sender, **kwargs):
    pk = kwargs['instance'].pk
    instance = sender.objects.get(pk=pk)
    tracking[sender] = instance

rawDescription: Diff django model objects with ManyToMany fields


code:
import binascii
import struct
data = '38 1A A3 44'
struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))

rawDescription: How to convert a hex-string into an unpacked IEEE 754 format number:-

description: Convert a hex-string into an unpacked IEEE 754 format number:-


code:
names = dict(list) # first name -> second name
x = input('Type the first name: ')
names[x] # search the `names` dictionary and return the second name

rawDescription: Result the second element of a list in python


code:
def passtt(self,item):
    print(item)

rawDescription: Pyqt - Combobox, how to return selected text


code:
sample = {
    "fruit": [
        {"apple": 1},
        {"banana": None}
    ],
    "veg": [],
    "result": {
        "apple": 1,
        "banana": None
    }
}
def clean_empty(d):
    if not isinstance(d, (dict, list)):
        return d
    if isinstance(d, list):
        return [v for v in (clean_empty(v) for v in d) if v]
    return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if v}

clean_empty(sample)

rawDescription: Python: How to remove all empty fields in a nested dict


code:
def g(arguments):
   pass

cached_g = mem.cache(g)

rawDescription: Multiple processes sharing a single Joblib cache


code:
from nltk.stem import snowball
stemmer = snowball.EnglishStemmer()
stemmer._EnglishStemmer__step1b_suffixes
step1b = stemmer._EnglishStemmer__step1b_suffixes
stemmer._EnglishStemmer__step1b_suffixes = list(step1b) + ['eth']
stemmer.stem('loveth')

rawDescription: How to Stem Shakespere/KJV Using nltk.stem.snowball


rawDescription: Group computation between rows on condition


code:
from itertools import combinations
x, y = 4, 3
[list(combo) for combo in combinations(range(x + 1), y) if 1 in combo]

rawDescription: Combinations Including Select Elements (Python)


code: any(f(v) for v in values for f in functions)

rawDescription: Search algorithm but for functions

description: Search algorithm but for functions


code:
import wx, sys, os
import json

CONFIGFILE = os.path.expanduser('~/tasklist.json')
class test(wx.Frame):
    def __init__(self, parent, id):
        frame = wx.Frame.__init__(self, parent, id, 'List', size = (200,500))
        self.panel = wx.Panel(self)
        self.panelbox = wx.BoxSizer(wx.VERTICAL)

        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.load()

        self.panelbox.Add(self.vbox)
        self.panelbox.Add(self.buttonbox)

        self.panel.SetSizer(self.panelbox)
        self.panelbox.Fit(self)

        self.Bind(wx.EVT_BUTTON, self.addtomenu, self.addButton)
        self.Bind(wx.EVT_BUTTON, self.finish, self.finishButton)
        self.Bind(wx.EVT_CLOSE, self.finish)

    def create_buttons(self):
        self.buttonbox = wx.BoxSizer(wx.VERTICAL)
        self.addButton = wx.Button(
            self.panel, label = "+ Add")
        self.finishButton = wx.Button(
            self.panel, label = "Finish")
        self.buttonbox.Add(self.addButton)
        self.buttonbox.Add(self.finishButton)

    def create_windtitle(self):
        item = wx.TextEntryDialog(None, "List Title")
        if item.ShowModal() == wx.ID_OK:
            answer = item.GetValue()
            self.windtitle = wx.StaticText(self.panel, -1, answer)
            self.windtitle.SetForegroundColour("blue")

    def addtomenu(self, event):
        newitem = wx.TextEntryDialog(None, "New Item")
        if newitem.ShowModal() == wx.ID_OK:
            if len(self.mylist) > 5:
                wx.StaticText(self.panel, -1, "List To Full")
            else:
                answer = newitem.GetValue()
                cb = wx.CheckBox(self.panel, -1, answer)
                self.vbox.Add(cb)
        self.panelbox.Fit(self)

    def finish(self, event):
        self.save()
        self.Destroy()
        sys.exit()

    @property
    def mylist(self):
        return [ child.GetLabel()
                 for child in self.panel.GetChildren()
                 if isinstance(child, wx.CheckBox) ]

    def save(self):
        windtitle = self.windtitle.GetLabelText()
        checkboxes = [{'checked': child.IsChecked(),
                       'label': child.GetLabel()}
                      for child in self.panel.GetChildren()
                      if isinstance(child, wx.CheckBox)]
        data = {
            'windtitle':windtitle,
            'checkboxes':checkboxes,
            }
        with open(CONFIGFILE, 'w') as f:
            json.dump(data, f)

    def load(self):
        if os.path.exists(CONFIGFILE):
            with open(CONFIGFILE, 'r') as f:
                data = json.load(f)
            title = data['windtitle']
            self.windtitle = wx.StaticText(self.panel, -1, title)
            self.vbox.Add(self.windtitle)
            for checkbox in data['checkboxes']:
                label = checkbox['label']
                cb = wx.CheckBox(
                    self.panel, -1, checkbox['label'])
                self.vbox.Add(cb)
                cb.SetValue(checkbox['checked'])
        else:
            self.create_windtitle()
        self.create_buttons()

if __name__ == "__main__":
    app = wx.PySimpleApp()  #Blood
    frame = test(parent = None, id = -1)  #Skin
    frame.Show()
    app.MainLoop()  #Heart

rawDescription: Python - Saving state of a program between restarts?


code:
for key, num in s_data:
    count += 1
    if num != previous:
        rank += count
        previous = num
        count = 0
    result[key] = rank

rawDescription: Ranking values in a Dictionary (and taking care of ex-aequos correctly)


code:
for textelement in soup.find_all(text=True):
    textelement.extract()

rawDescription: Filtering all inner text from a HTML document


code:
from bs4 import BeautifulSoup
import re

html = '''

   Lorem ipsum

   dolor

   sit amet

   consectetur adipiscing elit,

   sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

'''

soup = BeautifulSoup(html)

# remove  tag but keep content
spans = soup.find_all('span')
for tag in spans:
    tag.unwrap()

print('\n'.join(
  re.sub(r'\s+', ' ', td.text.strip())
    for td in soup.find_all('td') if td.text.strip()))

rawDescription: Unwrap element with beautifulsoup4: does it affect the .string of parent element?


code:
Camera = autoclass('android.hardware.Camera')
CameraParameters = autoclass('android.hardware.Camera$Parameters')
cam = Camera.open()
params = cam.getParameters()
params.setFlashMode(CameraParameters.FLASH_MODE_TORCH)
cam.setParameters(params)
cam.startPreview()

rawDescription: Accessing android flashlight(camera LED flash) with kivy/python


code:
from operator import itemgetter as it
from itertools import repeat
n = 3

 # sort_values = order pandas < 0.17
new_d = (zip(repeat(row["index"]), map(it(0),(row[1:].sort_values(ascending=0)[:n].iteritems())))
                 for _, row in df.iterrows())
for row in new_d:
    print(list(row))

rawDescription: Selecting top N columns for each row in data frame


code:
V = np.random.randint(2, size=(100000,100))
x = np.random.randint(2, size=100)
expected = V.astype(np.int8).dot(x.astype(np.int8))
result = np.einsum('ij,j->i', V, x)

rawDescription: Multiplication of (0,1)-matrix with a (0,1)-vector


code:
self.label = Label(self, text="TEXT TO BE INSERTED")
self.label.pack()

rawDescription: Run a function inside a tkinter

description: Run a function inside a tkinter


code: '2010 Ferrari 599XX'.split(None, 1)

rawDescription: Adding characters to certain laces in string


rawDescription: Capturing TM in Regex python

description: Capturing TM in Regex python


rawDescription: How to bind a method to class during its metaclass's __init__ method?

description: Bind a method to class during its metaclass's __init__ method


rawDescription: Combining list elements into one element in python


rawDescription: Python interpolare a function or array in a 2D (or nD) grid of parameters


code:
heap = [(-value, key) for key,value in the_dict.items()]
largest = heapq.nsmallest(10, heap)
largest = [(key, -value) for value, key in largest]

rawDescription: How to maintain dictionary in a heap in python?

description: Maintain dictionary in a heap in python


code:
class Test_user_view(unittest.TestCase):
    def test_it(self):
        req = DummyRequest()
        req.db = DummyDB()
        req.matchdict = {'uid': '3'}
        result = user_view(req)
        self.assertEqual(result['user'].id, 3)

rawDescription: How to get an actual Pyramid request when unit testing

description: Get an actual Pyramid request when unit testing


rawDescription: Issues with Bytes from a Microcontroller in Python


code:
def ordered_permutations(list1, list2):
    perms = []
    if len(list1) + len(list2) == 1:
        return [list1 or list2]
    if list1:
        for item in ordered_permutations(list1[1:], list2):
            perms.append([list1[0]] + item)
    if list2:
        for item in ordered_permutations(list1, list2[1:]):
            perms.append([list2[0]] + item)
    return perms

rawDescription: Permutations of the elements of two lists with order restrictions


code:
import lxml.etree as et

#...

self.xml = et.XML(filters.filtersxml)
self.tree_widget = QTreeWidget(parent)

def add_items(parent, xmlroot):
    output = []
    for i in xmlroot.getchildren():
        item = QTreeWidgetItem(parent, [i.get('name')])
        output.append(item)
        if len(i.getchildren()) != 0:
            add_items(item, i)
    return output

items = add_items(None, self.xml)
self.tree_widget.addTopLevelItems(items)
self.tree_widget.setCurrentItem(items[0])

rawDescription: QTreeWidget select first item

description: QTreeWidget select first item


code:
def ftimerange(start, stop, step = datetime.timedelta(minutes = 15)):
    for t in timerange(start, stop, step):
        yield t.strftime('%I:%M%p')

for s in ftimerange(nineam, fivepm):
    print(s)

rawDescription: Adjust start and end range for time list in Python


code:
for i,x in enumerate(letters):
    # ... rest of your loop
    letters[i] = x

rawDescription: Python: Changing values in a String with a for loop


code:
class Site(models.Model):
    name = models.CharField(max_length=200)
    prefix = models.CharField(max_length=1)
    secret = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

rawDescription: Add django model manager code-completion to Komodo


rawDescription: Create numpy array from matrix declared inside .m matlab file


code:
import numpy.fft

def convolve_many(arrays):
    """
    Convolve a list of 1d float arrays together, using FFTs.
    The arrays need not have the same length, but each array should
    have length at least 1.

    """
    result_length = 1 + sum((len(array) - 1) for array in arrays)

    # Copy each array into a 2d array of the appropriate shape.
    rows = numpy.zeros((len(arrays), result_length))
    for i, array in enumerate(arrays):
        rows[i, :len(array)] = array

    # Transform, take the product, and do the inverse transform
    # to get the convolution.
    fft_of_rows = numpy.fft.fft(rows)
    fft_of_convolution = fft_of_rows.prod(axis=0)
    convolution = numpy.fft.ifft(fft_of_convolution)

    # Assuming real inputs, the imaginary part of the output can
    # be ignored.
    return convolution.real

rawDescription: Faster convolution of probability density functions in Python


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

column_labels = list('ABCDEFGH')
row_labels = list('WXYZ')
fig, ax = plt.subplots()
data = np.array([[ 0.96753494,  0.52349944,  0.0254628 ,  0.5104103 ],
         [ 0.07320069,  0.91278731,  0.97094436,  0.70533351],
         [ 0.30162006,  0.49068337,  0.41837729,  0.71139215],
         [ 0.19786101,  0.15882713,  0.59028841,  0.06242765],
         [ 0.51505872,  0.07798389,  0.58790067,  0.44782683],
         [ 0.68975694,  0.53535385,  0.15696023,  0.35641951],
         [ 0.66481995,  0.03576846,  0.9623601 ,  0.96006395],
         [ 0.45865404,  0.50433582,  0.18182575,  0.35126449],])
data -= 0.5
data[3,:] = np.nan
data = np.ma.masked_invalid(data)
heatmap = ax.pcolor(data, cmap=plt.cm.seismic,
                    vmin=np.nanmin(data), vmax=np.nanmax(data))

# http://stackoverflow.com/a/16125413/190597 (Joe Kington)
ax.patch.set(hatch='x', edgecolor='black')

# draw a hatched rectangle wherever the data is negative
# http://matthiaseisen.com/pp/patterns/p0203/
mask = data < 0
for j, i in np.column_stack(np.where(mask)):
      ax.add_patch(
          mpatches.Rectangle(
              (i, j),     # (x,y)
              1,          # width
              1,          # height
              fill=False,
              edgecolor='blue',
              snap=False,
              hatch='x' # the more slashes, the denser the hash lines
          ))

fig.colorbar(heatmap)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

rawDescription: Python: Leave Numpy NaN values from matplotlib heatmap and its legend


rawDescription: Python 3.4 : LXML : Parsing Tables

description: Python 3.4 : LXML : Parsing Tables


code:
x = np.arange(10)
y = np.arange(5)
x[:, np.newaxis] - y

rawDescription: Difference between every row and column in two DataFrames (Python / Pandas)


code:
import matplotlib.pyplot as plt

x = y = [1,2,3,4,5]

fig, ax = plt.subplots()

ax.plot(x,y)
leg = ax.legend(['line 1'], loc=6, frameon=False)

plt.draw()

p = leg.get_window_extent()

ax.annotate('Annotation Text', (p.p0[0], p.p1[1]), (p.p0[0], p.p1[1]),
            xycoords='figure pixels', zorder=9)

plt.show()

rawDescription: Get Matplotlib legend location?

description: Get Matplotlib legend location


rawDescription: Replace a list slice with a packed tuple


code: emails = [p.email for p in participants]

rawDescription: make a list of recipients to use it at send_mail

description: Make a list of recipients to use it at send_mail


code: ("902".isdigit(), ("2".isdigit() == True), True)

rawDescription: Why does this Python boolean comparison return a triple?


code:
def fn_4d(A,B,C, fn):
    shape = list(A.shape)
    A = A.reshape(-1,A.shape[-2], A.shape[-1])
    B = B.reshape(-1,B.shape[-2], B.shape[-1])
    C = np.array(C).reshape(-1)
    A2 = fn(A,B,C)
    shape[-2] += 1
    A2 = A2.reshape(shape)
    return A2

rawDescription: Insertion of non aligned elements in 4-dimensional matrices in numpy


code:
import numpy as np
np.linspace(0, 4, 5)
np.linspace(0, 4, 10)

rawDescription: Code for logistic equation

description: Code for logistic equation


code: s.connect(('remote.host.com', 10000))

rawDescription: Can sockets be used to connect multiple computers on different networks in python?


rawDescription: Create multi-dimensional list from list

description: Create multi-dimensional list from list


code:
friend_name = input("enter your friends name")
yourname = input("enter your name")
print(awesome(friend_name))
print(awesome(yourname))

rawDescription: Vowel count only for one word?

description: Vowel count only for one word


code:
def mousePressEvent(self, e):
    print("Square got mouse press event")
    print("Event came to us accepted: %s"%(e.isAccepted(),))
    QtGui.QGraphicsRectItem.mousePressEvent(self, e)

rawDescription: PyQt Node interface - Parrent to ItemIsMovable object


code:
orig=[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 123, 0]]
id(orig)
copy2=orig[:]   #different index
id(copy2)
id(copy2[0]) == id(orig[0])  # inner list have same id

rawDescription: Changing a value in one list changes the values in another list with a different memory ID


code:
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return 'You want path: %s' % path

rawDescription: How would you make a file browser using python, for example with flask? Because of its url-mapper, file/folder to its functions?


code:
Category, Year = set(), set()
for row in DataCaptured:
    Year.add(row[0])
    Category.add(row[1])

rawDescription: How to create a list in Python with the unique values of a CSV file?

description: Create a list in Python with the unique values of a CSV file


code:
one
two
three

rawDescription: Python - list of dicts into function that only accepts *dicts


rawDescription: Dictionary with named values?

description: Dictionary with named values


rawDescription: How do I write a string equation solver in python?

description: Write a string equation solver in python


code:
csv.register_dialect('pipeseparated', delimiter = '|')

writer = UnicodeWriter(open("export.csv", "wb"), dialect='pipeseparated')

rawDescription: It is possible export table sqlite3 table to csv or similiar?


rawDescription: Finding the collatz conjecture that uses n steps to get to one using python


code:
# a.py
from b import B

class A: whatever

# b.py
from a import A

class B: whatever

rawDescription: Avoiding circular (cyclic) imports in Python?


code:
class B(object):
    def __init__(self):
        self.a = A()

rawDescription: Dynamically adding class instance to Python instance à la __setattr__


rawDescription: Python/Numpy subarray selection

description: Python/Numpy subarray selection


code:
from bs4 import BeautifulSoup

data = """

      GPU Name:
      BLABLA

      GPU Variant:
      BLABLA

      Process Size:
      BLABLA

      Transistors:
      BLABLA

      Process Size:

        Something

                Something Else

"""

soup = BeautifulSoup(data)
section = soup.find_all("td")

for section in section:
    if section.parent(text="GPU Name:"):
        print(section.text)
    elif section.parent(text="GPU Variant:"):
        print (section.text)
    elif section.parent(text="Process Size:"):
        print ('/'.join(item.strip() for item in section.find_all(text=True)))
    elif section.parent(text="Transistors:"):
        print (section.text)

rawDescription: How to deal with a different format in a specific tag using BeautifulSoup

description: Deal with a different format in a specific tag using BeautifulSoup


code:
from collections import namedtuple
import numpy as np

Info = namedtuple('Info', 'forecolor edge texture')

dict1 = {'someFileName.jpg': Info(np.array([...], dtype=np.uint8),
                                  np.array([...], dtype=np.uint8),
                                  np.array([...], dtype=np.uint8))}

rawDescription: Python: Iterate over two dictionaries that has lists as its values


code: DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter']

rawDescription: Can i use different databases for different apps in django

description: Use different databases for different apps in django


rawDescription: Natural Naming Scheme for a dynamic set of members


code:
from html.parser import HTMLParser

dictionary = {}

# Custom html parser which will add word and definition pairs
# to the dict 'dictionary'
class html_to_dict_parser(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    # These variables will tell the parser what data it's reading at the moment
    self.in_word_label = False
    self.in_definition = False
    self.has_definition = False

  # Called everytime the parser encounters a new tag
  # e.g.  or

  def handle_starttag(self, tag, attrs):
    if tag == 'b':
      self.in_word_label  = True
    elif tag == 'p':
      self.in_definition  = True

  # Similar to above
  def handle_endtag(self, tag):
    if tag == 'b':
      self.in_word_label = False
    elif tag == 'p':
      self.in_definition  = False

  # Called when the parser encounters the contents of a tag
  # e.g. 'Some word' in '
Some word

  def handle_data(self, data):
    if self.in_word_label:
      # Inside a  tag
      self.latest_word = data.lower()
      self.has_definition = True
    elif self.in_definition and self.has_definition:
      # Inside a
 tag which also contained a  tag
      dictionary[ self.latest_word ] = data
      self.has_definition = False

# Run the parser!
parser = html_to_dict_parser()
with open('dict.html') as html_file:
  parser.feed(html_file.read())

parser.close()
print(dictionary)

rawDescription: zConvert an HTML file into a Python dictionary

description: ZConvert an HTML file into a Python dictionary


code:
result = []
sample_counts = collections.Counter(samples)
while sum(sample_counts.itervalues()):
    # pick up one of each of the remaining samples and chain their rows
    # together in result
    s = set(key for key, value in sample_counts.iteritems() if value)
    result = itertools.chain(result, X[contains(X[:, 1], s), :])
    sample_counts -= collections.Counter(dict.fromkeys(s, 1))
# create a matrix of the final result
result = numpy.array(list(result))

rawDescription: Selecting rows from array under many conditions


code:
df.salary.diff()
df.salary.diff() <= 0

rawDescription: How to split DataFrame using some constraint?

description: Split DataFrame using some constraint


code:
d = DerivedMock()
assert isinstance(d, Derived)
assert repr(d).startswith("<Mock name='DerivedeMock' spec='Derived'")

assert d.one() == 'uno'
assert d.two() == 'dos'
assert d.three() == 'tres'

rawDescription: How to mock a class hierarchy

description: Mock a class hierarchy


code:
def assert_is_calls(m, calls, any_order=False):
   assert len(m.mock_calls) == len(calls)
   m.assert_has_calls(calls, any_order=any_order)

rawDescription: Checking whether function has been called multiple times with different parameters


rawDescription: Make a list of months and years in Pandas


rawDescription: Pyspark RDD collect first 163 Rows

description: Pyspark RDD collect first 163 Rows


code: sum(v['amount'] for v in basket.values() if v['group'] == 4) # 8

rawDescription: For a dictionary inside another dictionary how do you sort it by the value and compare different items within the dictionary


code: DictOut.setdefault(key, [])

rawDescription: How to extract from this list of tuples and convert into this dictionary?

description: Extract from this list of tuples and convert into this dictionary


code:
pax_one_bags = driver.find_element_by_id("ctl00_MainContent_passengerList_PassengerGridView_ctl02_baggageOutDropDown")
pax_one_bags_select = Select(pax_one_bags)

pax_one_bags.click()
pax_one_bags_select.options[1].click()

rawDescription: How to select an option from a dropdown menu via where it is in the list?

description: Select an option from a dropdown menu via where it is in the list


rawDescription: use variable to specify format in python

description: Use variable to specify format in python


rawDescription: How to implement the concept of cellular automata in python

description: Implement the concept of cellular automata in python


rawDescription: Filtering tuples in a list

description: Filtering tuples in a list


code: sorted(zoo)

rawDescription: Python Max Function

description: Python Max Function


code:
__metaclass__
__hash__
_get_next_or_previous_in_order
__ne__
date_error_message
description
_perform_date_checks
delete
clean
objects
unique_error_message
_set_pk_val
_deferred
save_base
pk
serializable_value
full_clean
__init__
code
save
__str__
validate_unique
clean_fields
__repr__
_perform_unique_checks
__reduce__
_get_unique_checks
prepare_database_save
_get_pk_val
__eq__
lookups
_get_next_or_previous_by_FIELD
Meta
_get_FIELD_display

rawDescription: PyCharm doesn't understand custom Manager of model


rawDescription: Open URL "silently" in python or similar


rawDescription: How to create 2 column binary numpy array from string list?

description: Create 2 column binary numpy array from string list


code:
#!/usr/bin/env python3

from fractions import Fraction, gcd
from functools import reduce

def lcm(a, b):
    return a * b // gcd(a, b)

def common_integer(*numbers):
    fractions = [Fraction(n).limit_denominator() for n in numbers]
    multiple  = reduce(lcm, [f.denominator for f in fractions])
    ints      = [f * multiple for f in fractions]
    divisor   = reduce(gcd, ints)
    return [int(n / divisor) for n in ints]

rawDescription: How to get a common integer in python from a float list?

description: Get a common integer in python from a float list


code:
def create_random_chromosomes(genes):
    temp_chromosomes = []
    chromosomes = []
    for i in range(2000):
        print(genes)
        randomgenes = genes[:]
        random.shuffle(randomgenes)
        temp_chromosomes.append(randomgenes)
    print(temp_chromosomes)
    for element in temp_chromosomes:
        if element not in chromosomes:
            chromosomes.append(element)
    return chromosomes

rawDescription: python random.shuffle() in a while loop

description: Python random.shuffle() in a while loop


code:
from setuptools import setup

setup(
    # ...
    install_requires=['module']
)

rawDescription: python auto install package

description: Python auto install package


code:
expr = '100.50*num*discount'
decistmt(expr)

rawDescription: Convert ast.Num to decimal.Decimal for precision in python


rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


code:
inp = normal(size=1000)
h = hist(inp)

rawDescription: How can I normalize a histogram such that the sum of the heights is equal to 1?

description: Normalize a histogram such that the sum of the heights is equal to 1


code:
rules = [mkrule(r) for r in [
    #" /// ",          # this rule creates problems
    "A// /UH",
    "ARE/ / /AH-R",
    "AR/ /O/UH-R",
    "AR//#/EH-R",
    "AS/ ^/#/AE-A-S",
    "A//WA/UH",
    "AW///AW",
    ...
]]

rawDescription: Python pattern matching of rules to parse text to phonemes


code:
import asyncio

@asyncio.coroutine
def begin():
    print("Starting to wait.")
    yield from asyncio.sleep(10)
    yield from end()

@asyncio.coroutine
def end():
    print("completed")

if __name__ == "__main__":
    try:
        loop = asyncio.get_event_loop()
        loop.create_task(begin())
        loop.run_forever()
    except KeyboardInterrupt:
        print("Goodbye!")

rawDescription: asyncio's call_later raises 'generator' object is not callable with coroutine object

description: Asyncio's call_later raises 'generator' object is not callable with coroutine object


code:
if (start <= lastsequence.end + 1):
    sequence = Sequence(lastsequence, start, end)

rawDescription: Don't create the object if a condition isn't verfied


code:
context = threading.local()
context.name = None

class ContextFilter(logging.Filter):

    def filter(self, record):
        if context.name is not None:
            record.name = "%s.%s" % (context.name, record.name)
        return True

rawDescription: How can you make logging module functions use a different logger?

description: Make logging module functions use a different logger


code:
def rw_in_range(start, low, high):
    print((' ' * start) + 'S')
    new_start=start + random_step()
    if new_start<low or new_start>high:
        return 0
    numberOfSteps = rw_in_range(new_start, low, high)
    return numberOfSteps + 1

rawDescription: Python: How To Recursively Simulate a Random Walk Within a Range (No Loops)


code: zip(*[L[i:] for i in range(3)])

rawDescription: Assorting elements in a list into a list of lists of specific lengths


code:
class thread(models.Model):
     message = models.ForeignKey(message, on_delete=models.CASCADE)
     ...

rawDescription: Django not cascading on delete

description: Django not cascading on delete


code:
from wand.image import Image as WImage
img = WImage(filename='hat.pdf')
img

rawDescription: View pdf image in an iPython Notebook

description: View pdf image in an iPython Notebook