code:
def count_pattern(lst, *pattern):
    return ''.join(l).count(''.join(pattern))

rawDescription: counting occurrence of consecutive elements in a list (python)

description: Counting occurrence of consecutive elements in a list (python)


code:
Sam
John

rawDescription: Extract data using HTMLParser

description: Extract data using HTMLParser


code:
def extract_urls(your_text):
  url_re = re.compile(r'\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))')
  for match in url_re.finditer(your_text):
    yield match.group(0)

rawDescription: Regex to extract all URLs from a page

description: Regex to extract all URLs from a page


code:
import csv
from datetime import datetime

with open('Unstructured.csv', 'rt') as csvfile:
    csvReader = csv.reader(csvfile)
    data = []

    for row in csvReader:
        try:
            data.append([datetime.strptime(row[0], "%m/%d/%Y").strftime("%Y-%m-%d"), row[1]])
        except ValueError:
            continue

    for i in data:
        print(i)

rawDescription: Selecting all rows with dates in a unstructured csv


code:
from random import shuffle
random.shuffle(your_lis)
your_lis = your_lis[:10000]

rawDescription: How to delete random items in a list to keep the list in a certain length?

description: Delete random items in a list to keep the list in a certain length


code:
def valid(s):
    if s.startswith('1*'):
        return True, s[2:]
    if s.startswith('1'):
        return True, s[1:]
    if s.startswith('('):
        success, rest = valid(s[1:])
        if not success or not rest.startswith('|'): return False, s
        success, rest = valid(rest[1:])
        if not success or not rest.startswith(')'): return False, s
        return True, rest[1:]
    return False, s

def check(s):
    return valid(s) == (True, '')

rawDescription: Evaluating a string using recursion

description: Evaluating a string using recursion


code:
#!/usr/bin/env python
from datetime import datetime, timedelta

ZERO, DAY = timedelta(0), timedelta(days=1)
times = (datetime.strptime(time12h_string, '%I:%M %p')
         for time12h_string in Train_arrival_time[1:])
previous_time = next(times)
time_in_transit = [ZERO]
for time24h in times:
    time24h = datetime.combine(previous_time, time24h.time())
    while time24h < previous_time: # time on the next station should not be ealier
        time24h += DAY
    time_in_transit.append(time24h - previous_time + time_in_transit[-1])
    previous_time = time24h

rawDescription: Convert a 12 hour time format to 24 hour time format (keeping record of the day) in python


code:
def add():
    global x
    x += 1
    l.configure(text=x)

rawDescription: How to make a Tkinter label update?

description: Make a Tkinter label update


code:
def populate(self):
    self.m.clear()
    root = self.m.invisibleRootItem()
    selModel = self.t.selectionModel()
    for item in self.l:
        e = QtGui.QStandardItem()
        e.setText(item[0])
        root.appendRow(e)

        if item[1]:
            idx = self.m.indexFromItem(e)
            selModel.select(idx, selModel.Select)

rawDescription: QTableView item selection based on a QStandardItem data attribute


code:
data_dictionary = dict()
line_no = 0

fields = 0
output = []

csv_data = csv.reader('C:\filepath')
for line in csv_data:
  if line_no == 0:
    #read the first line as the keys for the final dict
    fields = line
    line_no+=1
    continue

  field_index = 0
  one_entity = {}
  for answer in line:
    one_entity[fields[field_index]] = answer.strip()
  output.append(one_entity)
  line_no+=1

rawDescription: How to write into, or create a dictionary, using indexes in a row from another file

description: Write into, or create a dictionary, using indexes in a row from another file


code: phoneNum = charToNum(char) + phoneNum

rawDescription: Python String Logic Error

description: Python String Logic Error


code:
a = Cached(100)
b = Cached(200)
c = Cached(100)
a is b
a is c

rawDescription: Reuse existing objects for immutable objects?


code: recipeinfo == (serve, [(name, amount, unit), (name, amount, unit), ...])

rawDescription: Splitting up a pickled array into separate variables?


code:
re.compile("[A-Za-z_]"       # letter or underscore
       "[A-Za-z0-9_]*"   # letter, digit or underscore
      )

rawDescription: How to assign a value to a variable when writing the value takes multiple lines (python)

description: Assign a value to a variable when writing the value takes multiple lines (python)


code: lst = [nested for nested in lst if nested]

rawDescription: How to remove blank 2D list rows?

description: Remove blank 2D list rows


code: df = pd.DataFrame(np.random.randint(1,10,(10,6)), columns=list('abc')+['INT001','INT002','INT003'])

rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


code: delta = df[['END_DATE', 'CURRENT_DATE']].min(axis=1).subtract(df.START_DATE).dt.days.add(1)

rawDescription: vectorization of date range function for transformation of pandas dataframe

description: Vectorization of date range function for transformation of pandas dataframe


code:
s = "Word NUM123 a8#fc0 ABcd12 0102--212 abC4"
re.findall(rx, s)

rawDescription: Python Regex Query Syntax

description: Python Regex Query Syntax


rawDescription: Highly challenging queryset filtering, sorting and annotation (in Django-based app)


rawDescription: How to retrieve sub documents in a Array from mongoDB using python script

description: Retrieve sub documents in a Array from mongoDB using python script


code: src_path = "/home/data/%s/file.zip" % pkg_name

rawDescription: Is there any way to access variable like $var (similar to shell scripting) in python?


code:
import zope.interface
import zope.component
import zope.schema.interfaces

import z3c.form.interfaces
from z3c.form.widget import FieldWidget
from z3c.form.browser.text import TextWidget
from z3c.form import converter

class IIntWidget(z3c.form.interfaces.ITextWidget):
    """Int Widget"""

class IntWidget(TextWidget):
    zope.interface.implementsOnly(IIntWidget)
    klass = u'int-widget'
    value = u''

@zope.component.adapter(zope.schema.interfaces.IField,
                        z3c.form.interfaces.IFormLayer)
@zope.interface.implementer(z3c.form.interfaces.IFieldWidget)
def IntFieldWidget(field, request):
    """IFieldWidget factory for IntWidget."""
    return FieldWidget(field, IntWidget(request))

zope.component.provideAdapter(IntFieldWidget)

rawDescription: How to format an integer widget on the controlpanel using plone.app.registry

description: Format an integer widget on the controlpanel using plone.app.registry


code:
df1 = df.set_index(['fruit', 'veg'])
df1
df1.reindex(fruit_x_veg, fill_value='UNKNOWN')

rawDescription: ensuring the Cartesian product of keys appears in a Pandas table

description: Ensuring the Cartesian product of keys appears in a Pandas table


code:
import types

class application(web.application):
    def _delegate(self, f, fvars, args=[]):
        def handle_class(cls):
            meth = web.ctx.method
            if meth == 'HEAD' and not hasattr(cls, meth):
                meth = 'GET'
            if not hasattr(cls, meth):
                if hasattr(cls, '_default'):
                    tocall = getattr(cls(), '_default')
                    return tocall(*args)
                raise web.nomethod(cls)
            tocall = getattr(cls(), meth)
            return tocall(*args)

        def is_class(o): return isinstance(o, (types.ClassType, type))
        ...

rawDescription: web.py: How to selectively hide resources with 404s for any HTTP method?

description: Web.py: How to selectively hide resources with 404s for any HTTP method


code:
formatter = logging.PathTruncatingFormatter(
    '%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M'
    )

rawDescription: python logging - how do I truncate the pathname to just the last few characters or just the filename?

description: Python logging - how do I truncate the pathname to just the last few characters or just the filename


code:
def example(format_str, year, value):
  format_to_year_to_value_dict = defaultdict(lambda: defaultdict(list))

  format_to_year_to_value_dict[format_str][year].append(value)

rawDescription: How to initialize nested dictionaries in Python

description: Initialize nested dictionaries in Python


code:
df['val1 + val2 by Name'] = grouped.transform(sum).sum(axis=1)
df

rawDescription: how to apply functions to grouped dataframes in Python pandas?

description: Apply functions to grouped dataframes in Python pandas


code:
def get_clothes():
    return (t for t in allThings if t.garment)

def get_hats():
    return (t for t in get_clothes() if t.headgear)

rawDescription: Optimise filtering lists in Python 2.7

description: Optimise filtering lists in Python 2.7


code:
subset = 'a'
largest_key_within_subset = max((i for i in my_dict if i[0] == subset), key=itemgetter(1))

rawDescription: Return the largest value of a given element of tuple keys in a dictionary


rawDescription: Replace string based on a dictionary

description: Replace string based on a dictionary


rawDescription: Gradient calculation with python

description: Gradient calculation with python


code:
import subprocess
p = subprocess.Popen(["/usr/bin/du", "-k", "--max-depth", "1"], stdout=subprocess.PIPE)
(output, stderr) = p.communicate()

rawDescription: Top 5 Folders Consuming The Most Space?

description: Top 5 Folders Consuming The Most Space


code:
g2 = 2 * g
g2
type(g2)

rawDescription: creating class object that normally looks like a float

description: Creating class object that normally looks like a float


rawDescription: Most efficient way to implement numpy.in1d for muliple arrays


rawDescription: Split python dictionary to result in all combinations of values


rawDescription: Get list of column names for columns that contain negative values


code:
def generator3(parameters, strings):
    # replace strings with a generator of generators for the individual charachters
    strings = (it.islice((char for string_char in string_ for char in (',', string_char)), 1, None)
               for string_ in strings)

    # interpolate strings with the notices
    strings = (it.chain(('The strings are:',), string_) for string_ in strings)

    # nest them in tuples so they're ate the same level as the other generators
    separators = it.chain((('First line',),), it.cycle((('Some later line',),)))

    # replace the parameters with the appropriate tuples
    parameters = (('The parameter is:', p) if p else ('The parameter vanishes.',)
                  for p in parameters)

    # combine the separators, parameters and strings
    output = it.izip(separators, parameters, strings)

    # flatten it twice and return it
    output = it.chain.from_iterable(output)
    return it.chain.from_iterable(output)

rawDescription: itertools or hand-written generator - what is preferable?

description: Itertools or hand-written generator - what is preferable


code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation

class AnimRect(object):
    '''Animate a rectangle'''
    def __init__(self):
        self.fig = plt.figure(figsize = (5,5))
        # create the axes
        self.ax = plt.axes(xlim=(0,100), ylim=(0,100), aspect='equal')
        # create rectangle
        self.rect = plt.Rectangle((70,20), 10, 10,
                                  fill=True, color='gold', ec='blue')
        self.ax.add_patch(self.rect)
        self.call_animation()
        plt.show()

    # initialization function
    def init(self):
        self.rect.set_xy((10.0, 10.0))
        self.rect.set_visible(False)
        return self.rect,

    # animation function
    def animate(self, i):
        self.rect.set_xy((i,i))
        self.rect.set_visible(True)
        return self.rect,

    def call_animation(self):
        # call the animator function
        self.anim = animation.FuncAnimation(self.fig, self.animate, frames=91,
                                init_func= self.init,
                                interval=20, blit=False, repeat=True)

def main():
    rect = AnimRect()

main()

rawDescription: pyplot rectangle animation leaves initial rectangle displayed

description: Pyplot rectangle animation leaves initial rectangle displayed


code: dict(zip(index, zip(*val)))

rawDescription: Mapping a 2d list and a 1d list on to a dictionary


code:
import re
s = r'''asdfsd|//ser["gnd[{}\"\"]sgd"]|//sgsdgsdgsdg'''
re.findall('ser\[(.*)\]', s)

rawDescription: regex: match text between two strings, but farthest right string

description: Regex: match text between two strings, but farthest right string


code: res = np.where(A == 2, np.where(B > C, 5, np.where(B >= D, 4, 0)), 0)

rawDescription: Many numpy array manipulations in one array


code:
code = "We Says Thanks!"
html = """\

Thank you for being a loyal customer.

       Here is your unique code to unlock exclusive content:

{code}

""".format(code=code)

rawDescription: Python Variable in an HTML email in Python


code:
import sys
print(sys.version_info)

rawDescription: Is there a way to prevent a python 3 script from being called in python 2?


code:
foo = self.gconf_client.get_string("/path/to/my/config/data/foo")
bar = self.gconf_client.get_int("/path/to/my/config/data/bar")
baz = self.gconf_client.get_bool("/path/to/my/config/data/baz")

rawDescription: access to gnome configuration information using python

description: Access to gnome configuration information using python


rawDescription: Making a simple card game in python 2.7

description: Making a simple card game in python 2.7


code:
[{'collection': collection_x, 'brochures': [brochure1, brochure2]},
 {'collection': collection_y, 'brochures': [brochure3, brochure4]}]

rawDescription: Django: how to get a dictionary with a related object as key from a querydict


code:
import random

from jinja2.environment import Environment

rawDescription: Python 3 - Replacing part of a string with imformation from the string


rawDescription: Can a tkinter button return a value from an entry on-click?


code:
from itertools import groupby

for k in df:
    ind = prev = 0
    for k, v in groupby(df[k], key=lambda x: x == 2):
        ind += sum(1 for _ in v)
        if k and prev + 1 != ind:
            print("2 appeared at {} to {}".format(prev, ind - 1))
        prev = ind

rawDescription: Identify continuous occurrences of a value in a dataframe


code:
#Inherit from QThread
class Worker(QtCore.QThread):

    #This is the signal that will be emitted during the processing.
    #By including int as an argument, it lets the signal know to expect
    #an integer argument when emitting.
    updateProgress = QtCore.Signal(int)

    #You can do any extra things in this init you need, but for this example
    #nothing else needs to be done expect call the super's init
    def __init__(self):
        QtCore.QThread.__init__(self)

    #A QThread is run by calling it's start() function, which calls this run()
    #function in it's own "thread".
    def run(self):
        #Notice this is the same thing you were doing in your progress() function
        for i in range(1, 101):
            #Emit the signal so it can be received on the UI side.
            self.updateProgress.emit(i)
            time.sleep(0.1)

rawDescription: Python PySide and Progress Bar Threading


code: pd.concat([df, xdf], axis=1)

rawDescription: Parsing strings of date ranges in Pandas


code:
Project.objects.create(topic="Department Party")
ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner")
ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter")
Project.objects.all()

rawDescription: Django Inheriting from classes

description: Django Inheriting from classes


code:
if tags.has('use_htmlmath'):
    # use supplied =t use_htmlmath
    extensions.append('sphinx.ext.htmlmath')
else:
    #fall back
    extensions.append('sphinxcontrib-mathml')

rawDescription: Conditionally include extensions?

description: Conditionally include extensions


code: table_rows = zip(col1_values, col2_values, col3_values)

rawDescription: How to render lists of column values into a table using a template (such as Jinja2)

description: Render lists of column values into a table using a template (such as Jinja2)


rawDescription: Best data structure for 3D data?

description: Best data structure for 3D data


rawDescription: Scraping data from a table in drug reports with scrapy


code:
for i in xrange(len(axlist)):
    axlist[i] = fig.add_axes(ax[i])
return axlist

rawDescription: Figure appearance is not preserved when its axes are added to new figure


code:
ids = assessment_entries_qs.values_list('id', flat=True)

# Iterating ids causes the query to actually be executed
# This query was sent to the DB:
# SELECT id FROM assessments ORDER BY RANDOM()
for id in ids:
    pass

# ids has now been "realized" and contains the *results* of the query
# e.g., [5,1,2,3,4]
# Iterating again (or slicing) will now return values rather than modify the query

for amount in amounts:
    end_mark = start + amount
    entries = ids[start:end_mark]
    # because ids was executed, entries contains definite values
    # When filter() gets actual values, it adds a simple condition
    a = assessment_entries_qs.filter(id__in=entries).update(rating=rating)
    # The query executed is something like this:
    # UPDATE assessments SET rating=? WHERE id IN (5,1)
    # "(5,1)" will change on each iteration, but it will always be a set of
    # scalar values rather than a subquery.
    start = end_mark
    rating += 1

rawDescription: Why/how does iterating over a list and calling 'pass' each time fix this function?


code:
subThread = threading.Thread(...)
subThread.daemon = True

rawDescription: How to force main thread to close if a sub thread is alive in python?

description: Force main thread to close if a sub thread is alive in python


code:
import re
p = re.compile(r'\bobject-group\b\S*(?:\s+(?!object-group\b)\S*)*')
test_str = "object-group network FTP\n description FTP Access\n network-object host BCD1\n network-object host BCD2\nobject-group network NTP\n description NTP Access\n network-object host ABC1\n network-object host ABC2\n network-object host ABC3\nobject-group service sample_service tcp\n description Ports 1 2 3\n port-object range 80 81\n port-object eq pop3\n port-object eq imap4\n port-object range 443 444\nobject-group service 8080 tcp\n description Servers"
print(re.findall(p, test_str))

rawDescription: Grouping object-group configuration using RegEx


code:
# all your plotting code goes here ...

# change the box color
plt.setp(ax1.spines.values(), color=grey2)

# change the colors of the ticks
plt.setp([ax1.get_xticklines(), ax1.get_yticklines()], color=grey2)

# change the colors of the labels
plt.setp([ax1.xaxis.get_label(), ax1.yaxis.get_label()], color=grey2)

# change the color of the tick labels
plt.setp([ax1.get_xticklabels(), ax1.get_yticklabels()], color=grey2)

# change the color of the axis offset texts (the 1e11 thingy)
plt.setp([ax1.xaxis.get_offset_text(), ax1.yaxis.get_offset_text()], color=grey2)

plt.show()

rawDescription: How to adjust color of certain features for figure with transparent background

description: Adjust color of certain features for figure with transparent background


rawDescription: Rounding Error in Python

description: Rounding Error in Python


code:
import re
from itertools import izip_longest, ifilter, imap

s1 = "Brendon, Melissa, Jason, , McGuirk"
s2 = "brandon, melissa, jxz, paula, coach"

def take_first_not_empty(*args):
    splitter = re.compile(r'\s*?,\s*').split
    words = imap(splitter, args)
    return [next(ifilter(None, vals), '') for vals in izip_longest(*words, fillvalue='')]

rawDescription: Python to filter a comma-separated list on another csv list


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

def main():
    # Contour some regular (fake) data
    grid = np.arange(100).reshape((10,10))
    plt.contourf(grid)

    # Verticies of the clipping polygon in counter-clockwise order
    #  (A triange, in this case)
    poly_verts = [(2, 2), (5, 2.5), (6, 8), (2, 2)]

    mask_outside_polygon(poly_verts)

    plt.show()

def mask_outside_polygon(poly_verts, ax=None):
    """
    Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that
    all areas outside of the polygon specified by "poly_verts" are masked.

    "poly_verts" must be a list of tuples of the verticies in the polygon in
    counter-clockwise order.

    Returns the matplotlib.patches.PathPatch instance plotted on the figure.
    """
    import matplotlib.patches as mpatches
    import matplotlib.path as mpath

    if ax is None:
        ax = plt.gca()

    # Get current plot limits
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    # Verticies of the plot boundaries in clockwise order
    bound_verts = [(xlim[0], ylim[0]), (xlim[0], ylim[1]),
                   (xlim[1], ylim[1]), (xlim[1], ylim[0]),
                   (xlim[0], ylim[0])]

    # A series of codes (1 and 2) to tell matplotlib whether to draw a line or
    # move the "pen" (So that there's no connecting line)
    bound_codes = [mpath.Path.MOVETO] + (len(bound_verts) - 1) * [mpath.Path.LINETO]
    poly_codes = [mpath.Path.MOVETO] + (len(poly_verts) - 1) * [mpath.Path.LINETO]

    # Plot the masking patch
    path = mpath.Path(bound_verts + poly_verts, bound_codes + poly_codes)
    patch = mpatches.PathPatch(path, facecolor='white', edgecolor='none')
    patch = ax.add_patch(patch)

    # Reset the plot limits to their original extents
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

    return patch

if __name__ == '__main__':
    main()

rawDescription: Fill OUTSIDE of polygon | Mask array where indicies are beyond a circular boundary?


code:
import operator
from django.db.models import Q
import django_filters

class MultiFieldFilter(django_filters.Filter):
    def __init__(self,names,*args,**kwargs):
        if len(args) == 0:
            kwargs['name'] = names[0]
        self.token_prefix = kwargs.pop('token_prefix','')
        self.token_suffix = kwargs.pop('token_suffix','')
        self.token_reducer = kwargs.pop('token_reducer',operator.and_)
        self.names = names
        django_filters.Filter.__init__(self,*args,**kwargs)

    def filter(self,qs,value):
        if value not in (None,''):
            tokens = value.split(',')
            return qs.filter(
                reduce(
                    self.token_reducer,
                    [
                        reduce(
                            operator.or_,
                            [Q(**{
                                '%s__icontains'%name:
                                    (self.token_prefix+token+self.token_suffix)})
                                        for name in self.names])
                        for token in tokens]))
        return qs

rawDescription: Search fields in multiple models in Django


code:
record = EventRecord.objects.get(...)
isinstance(record.article, Article)
record.article.article_title

rawDescription: Get Foreign Key parent of object - Django


code:
def c_string(s):
    all_chars = (chr(x) for x in range(256))
    trans_table = dict((c, c) for c in all_chars)
    trans_table.update({'"': r'\"', '\\': r'\\'})
    return "".join(trans_table[c] for c in s)

def dwarf_string(d):
    import json
    return '"' + c_string(json.dumps(d)) + '"'

rawDescription: using Python to generate a C string literal of JSON

description: Using Python to generate a C string literal of JSON


code: [(re.findall(r'\{(.*)\}', i) or [''])[0] for i in your_list]

rawDescription: Python - removing characters from a list


code:
import io
content = io.BytesIO()
np.savez(content, x=x, y=y)
content.seek(0)

rawDescription: numpy's tostring/fromstring --- what do I need to specify to restore the array

description: Numpy's tostring/fromstring --- what do I need to specify to restore the array


code:
# First column of output array as the union of first columns of a,b
out_id = np.union1d(a[:,0],b[:,0])

# Get all IDs and counts in a single arrays
id_arr = np.concatenate((a[:,0],b[:,0]))
count_arr = np.concatenate((a[:,1],b[:,1]))

# Get binned summations
summed_vals = np.bincount(id_arr,count_arr)

# Get mask of valid bins
mask = np.in1d(np.arange(np.max(out_id)+1),out_id)

# Mask valid summed bins for final counts array output
out_count = summed_vals[mask]

# Stack the ID and count arrays into a 2-column format
out = np.column_stack((out_id,out_count))

rawDescription: Updating a NumPy array with another

description: Updating a NumPy array with another


rawDescription: Read cell content in an ipython notebook


code:
import netCDF4
import time
import numpy as np

url='http://fvcom.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/Forecasts/NECOFS_GOM3_FORECAST.nc'
nc = netCDF4.Dataset(url)
ncv = nc.variables
lon = ncv['lon'][:]
lat = ncv['lat'][:]
tim = ncv['time'][:]

# find indices inside box
box = [-71.4,41,-70.2,41.5]
ii = (lon>=box[0])&(lon<=box[2])&(lat>=box[1])&(lat<=box[3])
# jj will have just indices from inside the box:
jj = np.where(ii)[0]

rawDescription: Easy, scriptable way to sub-sample unstructured THREDDS data?


code:
import re

def atoi(text):
    return int(text) if text.isdigit() else text.lower()

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    return [ atoi(c) for c in re.split('(\d+)', text) ]

names = ('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png')

rawDescription: python equivalent to php natcasesort

description: Python equivalent to php natcasesort


rawDescription: np.subtract.outer() returning more dimensions than I expect

description: Np.subtract.outer() returning more dimensions than I expect


code: images = ['image1.png', 'image2.png', 'image3.png']

rawDescription: Pre-loading images pygame

description: Pre-loading images pygame


code:
import numpy as np
np.prod(map(len, a))

rawDescription: Multiply lengths of all sub-lists in list


rawDescription: How to unpack binary formatted dates in python?

description: Unpack binary formatted dates in python


rawDescription: Add all elements of an iterable to list

description: Add all elements of an iterable to list


code:
g1 = df.groupby(['key1', 'RN'])
g1['data2'].rank(ascending=False) - 1
df['RN'] += g1['data2'].rank(ascending=False) - 1
df

rawDescription: SQL-like window functions in PANDAS: Row Numbering in Python Pandas Dataframe


code:
running = True
l_KeyPressed = False

while running:
    # get events from the queue
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN :
            if event.key == pygame.K_SPACE:
                running = False

            if event.key == pygame.K_l:
                # do something
                l_KeyPressed = True

            if event.key == pygame.K_p and lPressed:
                l_KeyPressed = False

rawDescription: Pygame nested while loop: [Errno 10054] An existing connection was forcibly closed by the remote host


code: '     hello world!'.lstrip()

rawDescription: Removing starting spaces in Python?

description: Removing starting spaces in Python


rawDescription: Extract words from continous strings

description: Extract words from continous strings


code:
def foo (x):
    return lambda f: f*x

a=[1,2,3]
fn_foo = foo(5)
[fn_foo (y) for y in a]

rawDescription: How to run an operation on a collection in Python and collect the results?

description: Run an operation on a collection in Python and collect the results


code:
for row in array:
    print(row)

rawDescription: How to store and print a list of numbers in matrix form(python)

description: Store and print a list of numbers in matrix form(python)


rawDescription: Printing all possible phrases (consecutive combinations of words) in a given string


code: do_stuff(API_like_query, lambda i: i['id'])

rawDescription: Slightly different loops in python / Minimize code


rawDescription: Python: Replacing NaN or MEAN instead of a -999 value in an array


rawDescription: importing functions from .cpp file into python

description: Importing functions from .cpp file into python


code:
from collections import Iterable
def custom_key(item):
    if isinstance(item, Iterable) and not isinstance(item, basestring):
        return [medals_map.get(ele, ele) for ele in item]
    return medals_map.get(item, item)

rawDescription: Python sorting key function supporting tuples and lists


code:
for label in ax.xaxis.get_ticklabels()[::2]:
    label.set_visible(False)

rawDescription: Python Matplotlib scatter plot adding x-axis labels


code:
conds = {
    0: lambda: condition_1,
    1: lambda: condition_1 or condition_2,
    2: lambda: condition_1 or condition_2 or condition_3
}

rawDescription: Have extra while loop conditions ... based on a condition?


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour(wx.GREEN)

        self.list = wx.ListCtrl(self, style=wx.LC_REPORT, size=(200, -1))
        column_size = self.list.GetSize()[0] / 2 - 2
        self.list.InsertColumn(0, 'Name')
        self.list.InsertColumn(1, 'Age')
        self.list.SetColumnWidth(0, column_size)
        self.list.SetColumnWidth(1, column_size)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.list, proportion=0, flag=wx.EXPAND)
        self.sizer.Add(self.panel, proportion=1, flag=wx.EXPAND)

        self.SetSizerAndFit(self.sizer)
        self.SetSize((600, 400))
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Limit the size of wxListCtrl in wxpython


code:
class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()

        self.xpathInput = QtGui.QLineEdit(self)

        self.web_view = QWebView(self)
        self.web_view.load(QUrl("http://www.indiatimes.com/"))

        self.menu = QMenu()
        self.actionShowXpath = self.menu.addAction("Show Xpath")

        #QObject.connect(
        #    self.actionShowXpath,
        #    SIGNAL("triggered()"),
        #    self,SLOT("slotshowxpath()")
        #)

        self.actionShowXpath.triggered.connect(self.show_xpath)

        menu.exec_(self.mapToGlobal(QPoint(event.x(),event.y())))

    def show_path(self):
        frame = ...
        result = frame.evaluateJavaScript("abc").toString()
        self.xpathInput.setText(result)

def start_app():
    app = QtGui.QApplication(sys.argv)
    main_window = MyWindow()
    main_window.show()
    sys.exit(app.exec_())

rawDescription: Return value from PYQt slot of QwebView to main window widget (PYQt python)


code:
def __repr__(self):
    # notice the " and ' below.
    return self.__name__ + "('" + str(self.rid) + "', '" + \
           self.name + "', " + self.date_of_birth + ", '" + self.gender + "')"

rawDescription: Python inheritance woes

description: Python inheritance woes


rawDescription: How to create a multiIndex object from series?

description: Create a multiIndex object from series


code:
def make_baz(value):
    class Baz(Foo):
        def __init__(self):
            super().__init__()  # super() needs arguments in 2.x
            self.bar = value()
    return Baz()

rawDescription: Add attribute to python class

description: Add attribute to python class


rawDescription: Django queryset: All Model1 objects where a Model2 exists with a model1 AND the given user


code:
Megan
attribute4
attribute5

rawDescription: Python Splitting a file into many files and adding in extra info


code:
def f(mod):
    import inspect
    functions=inspect.getmembers(mod,inspect.isfunction)
    return functions

rawDescription: How can A.f defined in module A get list of function defined in B if A.f was called from B


code:
import numpy
grade_list = [1, 2, 3, 4, 4, 5, 4, 3, 1, 6, 0, -1, 6, 3]
grade_list_np = numpy.array(grade_list)
indices = numpy.where(grade_list_np > 0.0)[0]
print(indices)

rawDescription: How can I convert a list to a numpy array for filtering elements?

description: Convert a list to a numpy array for filtering elements


code: [x for x in content if any(c in x for c in char)]

rawDescription: Python : Removing a List from List of List?


code:
def bar():
    pass
bar = foo(bar)

rawDescription: Nested python decorator?

description: Nested python decorator


code:
the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

rawDescription: Matplotlib table only

description: Matplotlib table only


code:
if files:
    elementId = basename(normpath(path)) + "Audio"
    element = {
      "elementId" : elementId,
      "params" : {
         "audioPath" : path,
         "sounds" : list(files)
         },
      }
    jsonObject.append(element)

rawDescription: Inserting values into specific locations in a json file with Python


code: df.plot(title='Title Here')

rawDescription: Pandas Data Frame Plotting

description: Pandas Data Frame Plotting


code:
import ast
filecontent = ast.literal_eval(filename.read().strip())

rawDescription: remove specific characters from text file string

description: Remove specific characters from text file string


code:
use_function = sqr
for i in range(0, 100):
    a_list[i] = use_function(i)

rawDescription: Is there a way to avoid useless if-else clauses inside a loop when selectign from multiple functions?


code:
np.random.seed(10)
df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
df['A'] = df['A'].mul(10)

rawDescription: Operation on column based on column name pandas


code:
import numpy as np
import  matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

x, y, width, height, angle=10.0, 6.0, 7.0, 3.0, 160.0

fig = plt.figure(figsize=(12,8))
xx, yy = np.meshgrid(range(20), range(20))
img = (2*xx + yy)/40. # something asymmetrical to understand axes

ax1 = fig.add_subplot(121)
ax1.set_aspect('equal','box')
im1 = ax1.imshow(img, interpolation='none')
ax1.set_title('UL imshow origin')
ax2 = fig.add_subplot(122)
im2 = ax2.imshow(img, interpolation='none', origin='lower')
ax2.set_title('LL imshow origin')

def oneEllipse():
    return Ellipse(xy=(x,y), width=width, height=height, angle=angle,
            facecolor='black')
    # Can't define one Ellipse and add it to two axes. Huh.

for ax in (ax1, ax2):
    ax.add_artist(oneEllipse())
    # quiver can take a bunch of different function signatures
    # comment out the second or the third line to change the signature easily
    qi = ax.quiver(np.array([x, x+1]), np.array([y, y-1]), #
                np.array([width, width*2]),np.array([height, height/2.]),
                #angles='xy', # this uses the U, V args and flips the vectors
                #angles=np.array([angle, angle]), # angles come out the same
                headwidth=2, color=['white', 'red'], zorder=10)

rawDescription: Combining matplotlib quiver and elipses doesn't work


code:
import timeit

setup = '''import random, string;
all_lines = [','.join((random.choice(string.letters),
                    str(random.random() if random.random() > 0.3 else '"NaN"')))
                    for i in range(10000)]'''
oneloop = '''[(s.split(',')[0], s.split(',')[1])
              for s in all_lines if s.split(',')[1] != '"NaN"']'''
twoloops = '''raw_data  = [(lhs, rhs)
                for lhs, rhs
                in [s.split(',') for s in all_lines]
                if rhs != '"NaN"']'''

timeit.timeit(oneloop, setup, number=1000)  # 7.77 secs
timeit.timeit(twoloops, setup, number=1000) # 4.68 secs

rawDescription: Temporary variable within list comprehension


rawDescription: How do I extract the labels from a MultiIndex?

description: Extract the labels from a MultiIndex


code:
from django.template import Template, Context
t = Template('It is {% now "l" %} today.')
t.render(Context({}))

rawDescription: How can I make django output the day of the week? both in views an in templates

description: Make django output the day of the week? both in views an in templates


code:
# Load data
import numpy as np
from pylab import *
data1 = loadtxt("TEMP_2")
a = data1[:,1]

# Fit data into normal distribution
from scipy.stats import norm
mean, stdev = norm.fit(a)

# Plot normal distribution
import matplotlib.mlab as mlab
x = np.linspace(min(a), max(a), 100)
plot(x, mlab.normpdf(x, mean, stdev))
show()

rawDescription: distribution for existing data

description: Distribution for existing data


code:
import numpy as np

np.histogram(keys, bins=bins, weights=weights)

rawDescription: Numpy Histogram | Use one dimension to match bin, and another for the actual frequency


code: [int(x) for line in data for x in line.split()]

rawDescription: list comprehension replace for loop in 2D matrix

description: List comprehension replace for loop in 2D matrix


code:
def calc_fast(L1, L2):
    L1_sums = np.zeros(len(L1[0]))
    L2_sums = np.zeros(len(L2[0]))
    for vec in L1:
        L1_sums += vec
    for vec in L2:
        L2_sums += vec
    return np.dot(L1_sums, L2_sums)

rawDescription: efficient algorithm instead of looping

description: Efficient algorithm instead of looping


code:
import os

appName = "ap01"
opts =[
    "-server",
    "-filename=c:/test.VS",
    "-display=1"
]

opts = ' '.join(opts)
os.system(r'start "" "C:\bin\{:}" {:}'.format(appName, opts) )

rawDescription: python run CMD command with options

description: Python run CMD command with options


code: df[orgi].str.contains('aureus') == True

rawDescription: Moving row values between columns based on other column values in a Pandas DataFrame


rawDescription: Return a list of matches by given phrase


code:
SAVE_DOCUMENT_STATUS = "OK"
SAVE_DOCUMENT_TIME = "0.408"
GET_DOCUMENT_STATUS = "OK"
GET_DOCUMENT_TIME = "0.361"
DVK_SEND_STATUS = "OK"
DVK_SEND_TIME = "0.002"
DVK_RECEIVE_STATUS = "OK"
DVK_RECEIVE_TIME = "0.002"
GET_USER_INFO_STATUS = "OK"
GET_USER_INFO_TIME = "0.135"
NOTIFICATIONS_STATUS = "OK"
NOTIFICATIONS_TIME = "0.002"
ERROR_LOG_STATUS = "OK"
ERROR_LOG_TIME = "0.001"
SUMMARY_STATUS_STATUS = "OK"
SUMMARY_STATUS_TIME = "0.913"

rawDescription: Extract data from HTML table using Python


code:
import re
{fn: int(re.search('(\d{4})', fn).group()) for fn in filenames}

rawDescription: Python csv processing

description: Python csv processing


code:
dh = grouped['VALUE'].apply(lambda x: pd.Series(seriesFeatures(x)))
dh
dh.unstack().reset_index()

rawDescription: Splitting a column whose elements are dictionaries into many columns


code: np.concatenate(([True], np.diff(ts.index.year) != 0))

rawDescription: Pandas Time Series - add a value to the first value in each year


code:
# Loop over all the potential origin times
for l,otime in enumerate(origin_times):
    ttime_inds = np.around((tmax + otime + ttable) / dt).astype(int)
    points = traces[np.arange(n),ttime_inds]
    sum_point = points.sum()
    sqrr_sum_point = (points**2).sum()
    # Create the stack by taking the square of the sums dived by sum of the squares normalised by the number of stations
    S[l]=sum_point#**2/(n*sqrr_sum_point)

rawDescription: Vectorizing for loops in python with numpy multidimensional arrays


code: db.GqlQuery("SELECT * FROM List WHERE user_key = :1", user_key)

rawDescription: ReferenceProperty filter

description: ReferenceProperty filter


code:
def rec_replace(string, a, b):
    if not string: #if the string is empty
        return ""
    elif string[:len(b)] == b: #if the string start with b, replace it with a
        return a + rec_replace(string[len(b):], a, b)
    else: #else, add this character and go to the next one
        return string[0] + rec_replace(string[1:], a, b)

rawDescription: Using Recursion to Replace all occurences of a substring with another substring


code:
class MyFilter:
    def __init__(self, instr, errstr):
        self.instr = instr
        self.errstr = errstr
    def __enter__(self):
        print("ENTERING filter")
        return self
    def __exit__(self, a, b, c):
        print("EXITING filter")
        self.instr.close()
        self.errstr.close()
        return False
    def __next__(self):
        line = next(self.instr)
        while True:
            try:
                t = line.decode('utf8')
                return line.strip()
            except UnicodeDecodeError:
                self.errstr.write(line)
                line = next(self.instr)
        return line
    def __iter__(self):
        return self
    def next(self):
        return self.__next__()

rawDescription: Can you skip non utf-8 data in python csv?

description: Skip non utf-8 data in python csv


code:
elements  # list of values
n  # unwanted element index

rawDescription: How to get all the elements in the list without an element at a specific index in python?

description: Get all the elements in the list without an element at a specific index in python


code: "plot '%s' with lines, '%s' with points;" % (eout,nout)

rawDescription: Calling gnuplot from python

description: Calling gnuplot from python


code:
import math
def compute_min_and_max(expression):
    min_value, max_value = float("inf"), float("-inf")
    for x in range(1001):
        res = eval(expression, None, {"sin": math.sin, "x": x/100.0})
        if min_value > res: min_value = res
        if max_value < res: max_value = res
    return(min_value, max_value)

print(compute_min_and_max("sin(x ** 2)"))

rawDescription: Find min and max value of any function over an interval


rawDescription: Parsing response from Github

description: Parsing response from Github


code:
abc
(abc)
(abc,)

rawDescription: Convert a string to a list of length one


rawDescription: print python list of lists into string

description: Print python list of lists into string


rawDescription: Generating search term suggestions with Whoosh?


code:
def changeathlete(request, athlete_id):
    mod_athlete = Athlete.objects.get(pk=athlete_id)
    if request.method == 'POST': # If the form has been submitted...
        form = AthleteForm(request.POST, instance=mod_athlete) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            return HttpResponse("Athlete changed!") # Redirect after POST
    else:
        form = AthleteForm(instance=mod_athlete) # An unbound form

    return render_to_response('edit.html', {
            'form': form,
    }, context_instance=RequestContext(request))

rawDescription: How do I access form fields in a template in Django?

description: Access form fields in a template in Django


code:
import bz2
bz2.compress(datastring)
len(bz2.compress(datastring))
len(datastring)
compressed = bz2.compress(datastring)

rawDescription: How do I store account information in python so that it can be accessed later?

description: Store account information in python so that it can be accessed later


code:
p = Pool()
for data in data_list:
  result_list = pool.map(compute, data.slices)
  analyze(result_list)
p.join()
p.close()

rawDescription: How to reuse a process pool for parallel programming in Python 3

description: Reuse a process pool for parallel programming in Python 3


code: d = [num for num in d if num]

rawDescription: Only nonzero values Python list

description: Only nonzero values Python list


code:
def decSequenceToRNA(_idxSeq, _byteSequence):
    rnaSequence = ''
    printAndLog("!", "Processing block %d (%d bytes)" % (_idxSeq, len(_byteSequence)))
    for b in _byteSequence:
        rnaSequence = rnaSequence + base10ToRNA(ord(b))
    printAndLog("+", "Block %d completed. RNA of %d nucleotides generated." % (_idxSeq, len(rnaSequence)))
    return _idxSeq, rnaSequence

def fileToRNAString(_file):
    rnaSequences = []
    if (_file and os.path.isfile(_file)):
        blockCount = 0
        blockSize = 2048
        printAndLog("!", "Converting %s into RNA string (%d bytes/block)" % (_file, blockSize))
        results = []
        p = multiprocessing.Pool()  # Creates a pool of cpu_count() processes
        with open(_file, "rb") as hFile:
            buf = hFile.read(blockSize)
            while buf:
                result = pool.apply_async(decSequenceToRNA, blockCount, buf)
                results.append(result)
                blockCount = blockCount + 1
                buf = hFile.read(blockSize)
        rnaSequences = [r.get() for r in results]
        pool.close()
        pool.join()
    else:
        printAndLog("-", "Could not find the specified file. Please verify that the file exists:" + _file)
    return rnaSequences

rawDescription: Python/Multiprocessing : Processes does not seem to start


code:
from random import choice
choice.__module__

rawDescription: Detect definition path of a decorated function


code:
regex = "(?P<init_id>\w+?)_INIT\s*?=.*?'h(?P<initValue>[0-9a-fA-F]*)"
init_dict = {}
for x in re.findall(regex, lines):
    init_dict[x.groupdict()["init_id"]] = "0x" + x.groupdict()["initValue"]

regex = "(?P<addr_id>\w+?)_ADDR\s*?=.*?'h(?P<addrValue>[0-9a-fA-F]*)"
addr_dict = {}
for y in re.findall(regex, lines):
    addr_dict[y.groupdict()["addr_id"]] = "0x" + y.groupdict()["addrValue"]

init_to_addr_hexvalue_dict = {init_dict[x] : addr_dict[x] for x in init_dict.keys() if x in addr_dict}

rawDescription: Splitting lines in a file into string and hex and do operations on the hex values


code:
my_list = ['trash', 'Loop: 1','2','3','4 Loop', 'more trash']
search_str = "Loop"

start_index = my_list.index(next(e for e in my_list if search_str in e))
end_index = my_list.index(next(e for e in my_list[start_index + 1:] if search_str in e))

result = my_list[start_index:end_index + 1]

rawDescription: Python Array Copying From Word To Word

description: Python Array Copying From Word To Word


rawDescription: Pythonic way to get list element when expectation is that list contains only a single element?


code:
x = "foo"
x if x is not None else ""
x = None
x if x is not None else ""

rawDescription: Merge two tuples into one

description: Merge two tuples into one


code:
def filter_path(value):
    # at least 2, at most 3 /'s
    if 1 < value.count('/') < 4:
        return value

rawDescription: Scrapy - Limiting middle directories (Python)


code:
matches = re.split(r'^(\w+):', text, flags=re.MULTILINE)
[(v, matches[i+1]) for i, v in enumerate(matches) if i % 2]

rawDescription: Unable to find the correct regex in python


code:
date, time = the_string.split(' ')
years, months, days = date.split('-')
hours, minute, seconds = time.split(":")

rawDescription: Splitting a string @ once using different seps


code:
import sqlite3 as sq

db = sq.connect(':memory:')

db.execute('CREATE TABLE tbl (col INTEGER)')
db.execute('CREATE TABLE tbl2 (col INTEGER)')
db.executemany('INSERT INTO tbl (col) VALUES (?)', [(0,), (1,), (2,)])
db.commit()

print('count=' + str(db.execute('SELECT count(*) FROM tbl').fetchone()[0]))

# Read and print the values just inserted into tbl
for col in db.execute('SELECT col FROM tbl').fetchall():
    print(col)
    db.execute('INSERT INTO tbl2 VALUES (?)', col)
    db.commit()

print('count=' + str(db.execute('SELECT count(*) FROM tbl').fetchone()[0]))

rawDescription: Python, SQLite3: cursor returns duplicates when a commit intervenes


code: vector = np.ones(len([x for x in long_list if conditon]))

rawDescription: better way to vectorize using numpy

description: Better way to vectorize using numpy


code:
def changePage(self,change):
    pages = [self.pageOne,self.pageTwo,self.pageThree]
    new_position = self.position + change
    if (0 <= new_postion < len(pages)):
        pages[new_position].tkraise()
        self.position = new_position
    else:
        show_frame(BlankPage)

    if new_position+1 >= len(pages):
        self.nextButton.config(text="End") #, state=tk.DISABLED)
    else:
        self.nextButton.config(text="Next") #, state=tk.NORMAL)

    if new_position-1 < 0:
        self.backButton.config(text="First") #, state=tk.DISABLED)
    else:
        self.backButton.config(text="Back") #, state=tk.NORMAL)

rawDescription: tkinter - Going Back and Forth Between Frames Using Buttons

description: Tkinter - Going Back and Forth Between Frames Using Buttons


rawDescription: Get single element from a boost::python::object list, for use in python routine


rawDescription: numpy: syntax/idiom to cast (n,) array to a (n, 1) array?

description: Numpy: syntax/idiom to cast (n,) array to a (n, 1) array


code: ['fghij', 'fghde', 'abcde']

rawDescription: Sort a list based on a string- Python

description: Sort a list based on a string- Python


code:
user = User('steve', 'martin')
user.firstname
user.firstname = 'dean'
user.firstname

rawDescription: Why do we need property in Python?

description: Why do we need property in Python


code:
list1 = ['myfile.v', 'myfile2.sv', 'myfile3.vhd', 'etcfile.v', 'randfile.sv']
p = 0
for x in list1:
    if os.path.splitext(x)[0] not in set2:
        list1[p] = x
        p += 1

del(list1[p:])
list1

rawDescription: Python list.remove(x) 2.7.5

description: Python list.remove(x) 2.7.5


code:
# tksupport.py
from tkinter import simpledialog, messagebox
from twisted.internet import task

_task = None

def install(widget, ms=10, reactor=None):
    """Install a Tkinter.Tk() object into the reactor."""
    installTkFunctions()
    global _task
    _task = task.LoopingCall(widget.update)
    _task.start(ms / 1000.0, False)

def uninstall():
    """Remove the root Tk widget from the reactor.

    Call this before destroy()ing the root widget.
    """
    global _task
    _task.stop()
    _task = None

def installTkFunctions():
    import twisted.python.util
    twisted.python.util.getPassword = getPassword

def getPassword(prompt = '', confirm = 0):
    while 1:
        try1 = simpledialog.askstring('Password Dialog', prompt, show='*')
        if not confirm:
            return try1
        try2 = simpledialog.askstring('Password Dialog', 'Confirm Password', show='*')
        if try1 == try2:
            return try1
        else:
            messagebox.showerror('Password Mismatch', 'Passwords did not match, starting over')

__all__ = ["install", "uninstall"]

rawDescription: Threading with Twisted with Tkinter

description: Threading with Twisted with Tkinter


code: directors = list(map(str.strip, directors.split(','))) if directors else []

rawDescription: DRY version of similar string processing


code:
from google.appengine.ext import testbed
    #Workaround to avoid prospective search complain until there is a proper
    #testbed stub
from google.appengine.api.prospective_search.prospective_search_stub \
    import ProspectiveSearchStub
PROSPECTIVE_SEARCH_SERVICE_NAME = "matcher"
testbed.SUPPORTED_SERVICES.append(PROSPECTIVE_SEARCH_SERVICE_NAME)

rawDescription: Testbed stub for Google app engine prospective search


code:
def rfind2(s, t):
    pos = s[::-1].find(t[::-1])
    if pos == -1:
        return pos
    return len(s) - pos - len(t)

rawDescription: rfind implementation using find

description: Rfind implementation using find


code:
from line import Line
l=Line()
l.length
l.length = 1
l.__length = 1
l.__run_equation()
l.length
help(Line)

rawDescription: Where to define a method that is used only inside __init__ and must not be called anywhere else?


code:
with open(in_filename, 'r') as infile:
    outfile=StringIO.StringIO()
    outfile.write(struct.pack('<Q', filesize))
    outfile.write(iv)

    while True:
        chunk = infile.read(chunksize)
        if len(chunk) == 0:
            break
        elif len(chunk) % 16 != 0:
            chunk += ' ' * (16 - len(chunk) % 16)

        outfile.write(encryptor.encrypt(chunk))

rawDescription: Encrypt/Decrypt an animated gif in Python without storing the final copy to HD


rawDescription: Scipy fmin argument passing

description: Scipy fmin argument passing


code: grades

rawDescription: Using beautiful soup to pull text from multiple <tr>'s


code:
def get_web_content(url):
    # Extracted code
    url_handler = urllib2.urlopen(url)
    content = url_handler.read()
    url_handler.close()
    return content

def write_to_file(content, filename, tmpdir):
    # Extracted code
    file_handler = open(os.path.join(tempdir, filename), "w")
    file_handler.write(content)
    file_handler.close()

def download_distribution(url, tempdir):
    # Original code, after extractions
    distribution_contents = get_web_content(url)
    filename = get_file_name(url)
    write_to_file(distribution_contents, filename, tmpdir)
    return True

rawDescription: python unittest howto

description: Python unittest howto


code:
# This SConstruct orchestrates building 2 subdirs
import os

Import('env')
subdirs = ['src', 'test']

for subdir in subdirs:
    SConscript(os.path.join(subdir, 'SConscript'), exports = ['env'])

rawDescription: Real Hierarchical Builds with SCons?

description: Real Hierarchical Builds with SCons


code:
tmp1 = repeat(f, n-1)
tmp2 = f(x)
return tmp1(tmp2)

rawDescription: Evaluating call expression

description: Evaluating call expression


code:
def data_from_matrix(m):
    return [(len(m) - 1 - sum(row)) // 2 for row in m]

rawDescription: Getting data from a comparison matrix in python


code:
class SingleTCPHandler(SocketServer.BaseRequestHandler):
    """ One instance per connection. """
    def __init__(self, callback, *args, **keys):
        self.callback = callback
        SocketServer.BaseRequestHandler.__init__(self, *args, **keys)

    def handle(self):
        data = Net.recv_from_socket(self.request)
        self.callback(data)

rawDescription: Proper way to add functionality to handle() in a python TCP Server?


code: map(average, zip(*vd.values()))

rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code:
import copy
class A(object):
    pass

obj = A()
new_obj = copy.deepcopy(obj)

obj

new_obj

obj is new_obj

rawDescription: Copying class instances

description: Copying class instances


code:
with app.test_request_context(method='POST'):
    form = Product(request.form)
    # form5.category.data == None

    form = Product(request.form, category=2)
    # form5.category.data == 2

with app.test_request_context(method='POST', data={'category': 1}):
    form = Product(request.form)
    # form5.category.data == 1

    form = Product(request.form, category=2)
    # form5.category.data == 1

rawDescription: Setting a default value in the selectfield, using wtforms and flask


code:
def steps(path):
    if len(path) > 0:
        for i in range(1, len(path)):
            for step in steps_between(path[i - 1], path[i]):
                yield step
        yield path[-1]

def steps_between(start, end):
    x0, y0 = start
    x1, y1 = end

    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1

    if y0 > y1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    if y0 < y1:
        ystep = 1
    else:
        ystep = -1

    deltax = x1 - x0
    deltay = abs(y1 - y0)
    error = -deltax / 2

    y = y0
    for x in range(x0, x1):
        if steep:
            yield (y, x)
        else:
            yield (x, y)

        error += deltay
        if error > 0:
            y += ystep
            error -= deltax
            if steep:
                yield (y, x)
            else:
                yield (x, y)

rawDescription: divide ways on a map in parts of length one

description: Divide ways on a map in parts of length one


rawDescription: How to define values for RegularGridInterpolator

description: Define values for RegularGridInterpolator


code:
def is_attr_defined_on_parent(child, attr):
    for parent in child.__bases__:
        try:
            parent._meta.get_field(attr)
        except models.FieldDoesNotExist:
            continue
        else:
            return True
    return False

rawDescription: How to detect parent class fields

description: Detect parent class fields


rawDescription: term by term division in python (division termino a termino en python )

description: Term by term division in python (division termino a termino en python )


code: arr

rawDescription: Efficient 2d cumsum

description: Efficient 2d cumsum


code:
import re
reg = r'^([\w]+-[\w]+)'
re.match(reg, a).group()

rawDescription: Python: Split text after the second occurrence of character


code:
def my_sqrt(num):
    import math #load a module
    return math.sqrt(num) #call the function

rawDescription: subscripting python module

description: Subscripting python module


code:
a = Parent()
a.resource_setup()
a.parent_method()

b = Parent()
b.parent_method()

rawDescription: Accessing class method vairable in instance method


code:
class Computer(object):
    def boot_message(self):
        return 'I am a computer'

class AppleComputer(Computer):
    def boot_message(self):
        return super(AppleComputer, self).boot_message() + ' with a really shiny logo'

rawDescription: How to extend class method

description: Extend class method


code:
#!/usr/bin/env python

import optparse, sys
from pipes import quote

'''
Uses Python's optparse library to simplify command argument parsing.

Takes in a set of optparse arguments, separated by newlines, followed by command line arguments, as argv[2] and argv[3:]
and outputs a series of bash commands to populate associated variables.
'''

class _ThrowParser(optparse.OptionParser):
    def error(self, msg):
        """Overrides optparse's default error handling
        and instead raises an exception which will be caught upstream
        """
        raise optparse.OptParseError(msg)

def gen_parser(usage, opts_ls):
    '''Takes a list of strings which can be used as the parameters to optparse's add_option function.
    Returns a parser object able to parse those options
    '''
    parser = _ThrowParser(usage=usage)
    for opts in opts_ls:
        if opts:
            # yes, I know it's evil, but it's easy
            eval('parser.add_option(%s)' % opts)
    return parser

def print_bash(opts, args):
    '''Takes the result of optparse and outputs commands to update a shell'''
    for opt, val in opts.items():
        if val:
            print('%s=%s' % (opt, quote(val)))
    print("set -- %s" % " ".join(quote(a) for a in args))

if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.stderr.write("Needs at least a usage string and a set of options to parse")
        sys.exit(2)
    parser = gen_parser(sys.argv[1], sys.argv[2].split('\n'))

    (opts, args) = parser.parse_args(sys.argv[3:])
    print_bash(opts.__dict__, args)

rawDescription: Using Python to parse complex arguments to shell script


rawDescription: How to calculate ts1 - ts2.interpolate(index=ts1.index)

description: Calculate ts1 - ts2.interpolate(index=ts1.index)


code:
state = {'id': 15, 'name': 'New York', 'population': 19750000}
print("{:>3s} {:20s} {:>12s}".format("Id", "State", "Population"))
print("{id:3d} {name:20s} {population:12d}".format(**state))

rawDescription: Python3 .format() align usage

description: Python3 .format() align usage


rawDescription: To sum column with condition

description: To sum column with condition


rawDescription: Python: nested list and dictionary comparison


code:
def build_instructions(obj, q):
    """
    Breaks down a query string into a series of actionable instructions.

    Each instruction is a (_type, arg) tuple.
    arg -- The key used for the __getitem__ or __setitem__ call on
           the current object.
    _type -- Used to determine the data type for the value of
             obj.__getitem__(arg)

    If a key/index is missing, _type is used to initialize an empty value.
    In this way _type provides the ability to
    """
    arg = []
    _type = None
    instructions = []
    for i, ch in enumerate(q):
        if ch == "[":
            # Begin list query
            if _type is not None:
                arg = "".join(arg)
                if _type == list and arg.isalpha():
                    _type = dict
                instructions.append((_type, arg))
                _type, arg = None, []
            _type = list
        elif ch == ".":
            # Begin dict query
            if _type is not None:
                arg = "".join(arg)
                if _type == list and arg.isalpha():
                    _type = dict
                instructions.append((_type, arg))
                _type, arg = None, []

            _type = dict
        elif ch.isalnum():
            if i == 0:
                # Query begins with alphanum, assume dict access
                _type = type(obj)

            # Fill out args
            arg.append(ch)
        else:
            TypeError("Unrecognized character: {}".format(ch))

    if _type is not None:
        # Finish up last query
        instructions.append((_type, "".join(arg)))

    return instructions

rawDescription: Python recursive setattr()-like function for working with nested dictionaries


code:
def __init__(self):
    try:
        self.__doc__ = next(cls.__doc__ for cls in inspect.getmro(type(self)) if cls.__doc__ is not None)
    except StopIteration:
        pass

rawDescription: Inherit a parent class docstring as __doc__ attribute


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

# Generate some data...
data = np.random.random((12, 10))
correlation_mat = np.cov(data)
correlation_mat /= np.diag(correlation_mat)

num = data.shape[0]

fig, ax = plt.subplots(figsize=(20,11))
ticks = ['$F_{sum}$', '$F_{dif}$', '$x_{sum}$', '$x_{dif}$', '$y_{sum}$',
         '$y_{dif}$', '$HLR_a$', '$e1_a$', '$e2_a$', '$HLR_b$', '$e1_b$',
         '$e2_b$']
ticks = ticks[::-1]

ax.matshow(correlation_mat, aspect='auto', cmap='cool')
ax.set(title='Correlation Matrix', xticks=range(num), xticklabels=ticks,
       yticks=range(num), yticklabels=ticks)
ax.tick_params(labelsize=25)

for (i, j), val in np.ndenumerate(correlation_mat):
    ax.annotate('{:0.2f}'.format(val), (j,i), ha='center', va='center', size=25)

plt.show()

rawDescription: Setting x-axis frequency in table for Python


code:
task_list = []
for prio, work in tsv_file:
    task_list += [work] * int(prio)

do_this = random.choice(task_list)

rawDescription: Get random element by given priority

description: Get random element by given priority


code: merge

rawDescription: Applying a function to a pandas col

description: Applying a function to a pandas col


code:
def bar(): return ['spam', 'eggs']

dis.dis(bar)

rawDescription: Hard coded variables in python function

description: Hard coded variables in python function


rawDescription: Python list-like string representation of numpy array


code: np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4') # or dtype=np.dtype('>f4'), or np.float32  on a big-endian system

rawDescription: convert binary string to numpy array

description: Convert binary string to numpy array


code:
# do what you're doing
range = [data.min(),data.max()]
heights,edges = np.histogram(data, bins=np.ceil((range[1]-range[0])*0.95), range=range)
edges = edges[:-1]+(edges[1]-edges[0]) # shift first x coordinate to edges[1]

fig, ax = plt.subplots()
ax.plot(edges,heights)

rawDescription: Numpy.histogram joining bins

description: Numpy.histogram joining bins


code: {'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Referer': 'http://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=293', 'Origin': 'http://www.transtats.bts.gov', 'Upgrade-Insecure-Requests': 1, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Cookie': 'ASPSESSIONIDQADBBRTA=CMKGLHMDDJIECMNGLMDPOKHC', 'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded'}

rawDescription: Python Requests Not Returning Same Header as Browser Request/cURL


code:
class Review(models.Model):
    name = models.CharField(max_length=1024)
    text = models.TextField()
    author = models.ForeignKey(UserProfile)
    place = models.ForeignKey(place)

    price_rating = models.IntegerField(null=True)
    location_rating = models.IntegerField(null=True)
    # ...

rawDescription: Database design for Django review website


rawDescription: tkinter - ask the user for files directory and then run a script

description: Tkinter - ask the user for files directory and then run a script


code:
from collections import Counter
a=[     ['item1', 'item2', 'element2'],
        ['item3', 'item4', 'element3'],
        ['item5', 'item6', 'element1'],
        ['item7', 'item8', 'element3']]
freq = Counter(item[-1] for item in a)
sorted(a, key=lambda i: freq[i[-1]], reverse=True)
from pprint import pprint
pprint(_)

rawDescription: Sorting a List of List in Python by frequency


code:
Kxu = Kx[:,:,np.newaxis]*u
Kyv = Ky[:,:,np.newaxis]*v
Arg = Kxu[:,:,:,np.newaxis] + Kyv[:,:,np.newaxis,:]

rawDescription: Numpy multiplication of vectors of different size avoiding for loops


code:
class klass(object):
    pass

for i in [1,2]:
    def f(self, i=i):
        print(i)
    setattr(klass, 'f' + str(i), f)

rawDescription: MetaPython: Adding Methods to a Class

description: MetaPython: Adding Methods to a Class


code:
import re
s = '34% passed 23% failed 46% deferred'
pattern = re.compile(r'(\w+)%\s(\w+)')
{value: key for key, value in pattern.findall(s)}

rawDescription: regex to split %ages and values in python

description: Regex to split %ages and values in python


code:
class McDonaldSpider(BaseSpider):
    name = "mcdonalds"
    allowed_domains = ["mcdonalds.com.sg"]
    start_urls = ["https://www.mcdonalds.com.sg/locate-us/"]

    def parse(self, response):
        # This receives the response from the start url. But we don't do anything with it.
        url = 'https://www.mcdonalds.com.sg/wp-admin/admin-ajax.php'
        payload = {'action': 'ws_search_store_location', 'store_name':'0', 'store_area':'0', 'store_type':'0'}
        return FormRequest(url, formdata=payload, callback=self.parse_stores)

    def parse_stores(self, response):
        data = json.loads(response.body)
        for store in data['stores']['listing']:
            yield McDonaldsItem(name=store['name'], address=store['address'])

rawDescription: Scrapy, scrapping data inside a javascript


code:
q = [sum(activity_data['Activity']*activity_data['Class'].map(weight_lookuptable[c])) for c in activity_data['Class']]
new_q = activity_data["Activity"].dot(weight_lookuptable)
np.allclose(q, new_q)

rawDescription: Speeding up all-to-all comparisons with a lookup table on Numpy and/or Pandas


rawDescription: Methods of creating a structured array

description: Methods of creating a structured array


code: list(zip(*lst))

rawDescription: Reshape list of lists based on position of the element


code:
def memo(f):
    # Author: Peter Norvig
    """Decorator that caches the return value for each call to f(args).
    Then when called again with same args, we can just look it up."""
    cache = {}
    def _f(*args):
        try:
            return cache[args]
        except KeyError:
            cache[args] = result = f(*args)
            return result
        except TypeError:
            # some element of args can't be a dict key
            return f(*args)
    _f.cache = cache
    return _f

L.sort(key=make_lazy(memo(f1), memo(g)))
report_calls(f1, g)

rawDescription: Avoiding unnecessary key evaluations when sorting a list


code:
for func in args.funcs:
    func()

rawDescription: python argparse set behaviour when no arguments provided

description: Python argparse set behaviour when no arguments provided


code:
for item in list1:
    if item == 'test_input_1':
        # you found it!
        print ("Found: test_input_1")

rawDescription: regex filtering repeatating items with numerics

description: Regex filtering repeatating items with numerics


rawDescription: Downloading and accessing data from github python


rawDescription: Delete newline / return carriage in file output


code: hasattr("abc", "__iter__")

rawDescription: pythonic way to convert variable to list

description: Pythonic way to convert variable to list


code:
import shapely.geometry
import descartes
import matplotlib.pyplot as plt

lines = ([(0, 0), (1, 0), (0, 1)],
         [(0, 0), (1, 1)],
         [(0.5, 0.5), (1, 0.5)],
         )
lines = shapely.geometry.MultiLineString(lines)
# "0.05" is the _radius_ in data coords, so the width will be 0.1 units.
poly = lines.buffer(0.05)

fig, ax = plt.subplots()
patch = descartes.PolygonPatch(poly, fc='gray', ec='black')
ax.add_artist(patch)

# Rescale things to leave a bit of room around the edges...
ax.margins(0.1)

plt.show()

rawDescription: matplotlib path linewidth connected to figure zoom

description: Matplotlib path linewidth connected to figure zoom


code:
if value_to_accept is not None:
    return [x for x in a_list if x.smth == value_to_accept]
if value_to_reject is not None:
    return [x for x in a_list if x.smth != value_to_reject]
return []

rawDescription: Python: Subsetting a list according to the attribute


code:
import random
import tkinter as tk

def roll(n):
    return random.randint(1, n)

def calc():
    thing = var.get()
    if (thing == 'Barbarian'):
        print ()

# define a callback function in order to set the content of the label widget dependent on the selection
# reads the current content of StringVar `selection`, gets the desired value from the dict `d` and
# writes it to the StringVar `view_text`
def observe_option_menu(*args):
    view_text.set(d.get(selection.get()))

root = tk.Tk()
root.geometry("%dx%d+%d+%d" % (550, 80, 200, 150))
root.title("Gold Calculator")

# create another StringVar and connect a callback function to it.
# hence trance as the 'w' flag, this callback will be fired whenever someone writes to the variable
selection = tk.StringVar(root)
selection.set('-Select a class-')
selection.trace('w', observe_option_menu)

choices = ['Barbarian', 'Bard', 'Cleric', 'Druid', 'Fighter', 'Monk', 'Paladin', 'Ranger', 'Rougue', 'Sorcerer', 'Warlock', 'Wizard']

# lists `texts` contains sample data in order to get key-value-pairs to combine selection with text of label
texts =  ['VniC', '3DhO', 'CWm0', '8Cf9', 'avNN', 'SUnD', 'lp3R', 'Gtgk', 'FwvV', 'XzH1', 'CyGO', 'UASr']

# create a dict `d` out from the lists given above, you could use a dict directly instead of two seperate lists
d = dict(zip(choices, texts))

view_text = tk.StringVar(root)
view_text.set('Content depends on selection')

option = tk.OptionMenu(root, selection, *d.keys())
option.pack(side='left', padx=10, pady=10)

button = tk.Button(root, text="Calculate Gold", command=calc)
button.pack(side='left', padx=20, pady=10)

# create a Label widget `label` and place it using pack geometry manager
label = tk.Label(root, textvariable=view_text)
label.pack(side='left', padx=20, pady=10)

root.mainloop()

rawDescription: How do you import two different text widgets into one frame in Python?

description: Import two different text widgets into one frame in Python


code:
def foo():
    from itertools import izip, imap, takewhile
    with open("temp.txt") as fin:
        def skip(fin):
            # Take/Read all lines from the file and discard which are empty
            takewhile(lambda name: name.strip() == "", fin)
        try:
            while fin:
                # Skip all empty lines
                skip(fin)
                # The next line is the file name
                fname = next(fin).strip()
                # All subsequent lines until the empty line is the content
                # Split the lines and transpose it
                # Yield the file name and the transposed content
                yield fname, zip(*(imap(str.split, takewhile(lambda n:n.strip(), fin))))
        except StopIteration:
            pass

rawDescription: Saving columns under separate headers in a text file to separate lists


code:
from ast import literal_eval
type(literal_eval('1.01'))
type(literal_eval('1'))
type(literal_eval('1+0j'))

rawDescription: Determing the type of number stored as a string


code:
urlpatterns = [
    url(r'^permalink/$', QuerystringRedirect.as_view(), name="original_view"),
    url(r'^permalink/(?P<id>\d+)/$', views.permalink, name="target_view"),
]

rawDescription: How to redirect url pattern with variables from urls.py in Django?

description: Redirect url pattern with variables from urls.py in Django


code:
with open("input.txt", "r") as inp, open("output.txt","w") as outfile:
    for ind, line in enumerate(inp,1):
        if ind % 3 == 0:
            outfile.write(line.rstrip()+"\n")
        else:
            outfile.write(line.rstrip() + "\t")

rawDescription: Outputting appeded list of items into a file


code: ham

rawDescription: How to define a __str__ method for a class?

description: Define a __str__ method for a class


code:
def names(all=False):
    """Get the interface attribute names

    Return a sequence of the names of the attributes, including
    methods, included in the interface definition.

    Normally, only directly defined attributes are included. If
    a true positional or keyword argument is given, then
    attributes defined by base classes will be included.
    """

rawDescription: Why would a subclass of a subclass of zope.interface.Interface not inherit its parents names?


rawDescription: Modification of a Dictionary in PYTHON

description: Modification of a Dictionary in PYTHON


code:
a = [1,2,3,4,5]
b = [elem * (i+1) for i, elem in enumerate(a)]
b

rawDescription: calculations using both a value from a list and the index of that value?

description: Calculations using both a value from a list and the index of that value


code:
df = pd.DataFrame({"A": range(1000), "B": range(1000)})
df
df[:5]

rawDescription: How to preview a part of a large pandas DataFrame?

description: Preview a part of a large pandas DataFrame


code:
import numpy as np
from scipy.interpolate import griddata
class d():
    def __init__(self):
        A0 = open("test.txt","rb") # i just copypasted your data into a txt (without first row), and reading it in in this class, so that the names are the same as yours
        A1 = A0.readlines()
        A = np.zeros((len(A1),3))
        for i, l in enumerate(A1):
            li = l.split()
            A[i,0] = float(li[0])
            A[i,1] = float(li[1])
            A[i,2] = float(li[2])
        self.Lon = A[:,0]
        self.Lat = A[:,1]
        self.Z = A[:,2]

data = d()
numcols, numrows = 30, 30
xi = np.linspace(data.Lon.min(), data.Lon.max(), numrows)
yi = np.linspace(data.Lat.min(), data.Lat.max(), numcols)
xi, yi = np.meshgrid(xi, yi)

x, y, z = data.Lon, data.Lat, data.Z
points = np.vstack((x,y)).T
values = z
wanted = (xi, yi)
zi = griddata(points, values, wanted)
import pylab as plt
fig = plt.figure(0, figsize=(8,4.5))
im = plt.contourf(xi, yi, zi)
plt.colorbar()
fig2 = plt.figure(1, figsize=(8,4.5))
im = plt.scatter(xi, yi, c= zi)
plt.colorbar()
plt.show()

rawDescription: use of matlab meshgrid

description: Use of matlab meshgrid


code: OrderedDict(sorted(named_sets.items(), key=lambda i: i[0].lower()))

rawDescription: How to do case insensitive sort of a dictionary and store them in OrderedDict

description: Do case insensitive sort of a dictionary and store them in OrderedDict


code: from tasks import your_function

rawDescription: Asynchronous Flask functions

description: Asynchronous Flask functions


code:
possibleusershipplaces = {"1","2","3","4","5","6","7","8","9"}

for players_chosen_hit  in iter(lambda:input('Please tell me where the hit is: 1-9  (q to quit) '),"q"):
    if players_chosen_hit.isdigit() and players_chosen_hit in possibleusershipplaces:
        players_chosen_hit = int(players_chosen_hit)

rawDescription: Python - Error Checking

description: Python - Error Checking


code:
# use iteritems on Python2
shared1 = {k: v for k, v in A.items() if i in B}

rawDescription: Hashing or dictionaries for Venn diagram of dictionaries?


code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class stackedExample(QWidget):
    def __init__(self):
        super(stackedExample, self).__init__()
        self.leftlist = QListWidget()
        self.leftlist.insertItem(0, 'Contact')
        self.leftlist.insertItem(1, 'Personal')
        self.leftlist.insertItem(2, 'Educational')

        self.stack1 = QWidget()
        self.stack2 = QWidget()
        self.stack3 = QWidget()

        self.stack1UI()
        self.stack2UI()
        self.stack3UI()

        # Renamed self.stack to self.stack since the convention is to start
        # class names with a capital but regular variables with a lower case.
        self.stack = QStackedWidget(self)
        self.stack.addWidget(self.stack1)
        self.stack.addWidget(self.stack2)
        self.stack.addWidget(self.stack3)

        hbox = QHBoxLayout(self)
        hbox.addWidget(self.leftlist)
        hbox.addWidget(self.stack)

        self.setLayout(hbox)
        self.leftlist.currentRowChanged.connect(self.display)
        self.setGeometry(300, 50, 10, 10)
        self.setWindowTitle('StackedWidget demo')
        self.show()

    def stack1UI(self):
        layout = QFormLayout()
        layout.addRow("Name", QLineEdit())
        layout.addRow("Address", QLineEdit())
        # self.setTabText(0,"Contact Details")
        self.stack1.setLayout(layout)

    def stack2UI(self):
        layout = QFormLayout()
        sex = QHBoxLayout()
        sex.addWidget(QRadioButton("Male"))
        sex.addWidget(QRadioButton("Female"))
        layout.addRow(QLabel("Sex"), sex)
        layout.addRow("Date of Birth", QLineEdit())

        self.stack2.setLayout(layout)

    def stack3UI(self):
        layout = QHBoxLayout()
        layout.addWidget(QLabel("subjects"))
        self.physicsCheckBox = QCheckBox("Physics")
        layout.addWidget(self.physicsCheckBox)
        self.physicsCheckBox.stateChanged.connect(self.physicsCheckBoxStateChanged)

        layout.addWidget(QCheckBox("Maths"))
        self.stack3.setLayout(layout)

    def physicsCheckBoxStateChanged(self, state):
        isChecked = bool(state) # Convert from Qt.CheckState
        print("physicsCheckBox: {}".format(isChecked))

    def display(self, i):
        self.stack.setCurrentIndex(i)

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

if __name__ == '__main__':
    main()

rawDescription: Setting up stateChanged signal in QStackedWidget, pyqt


code:
result = my_func()
if result:
    use_list(result)
else:
    empty_list()

rawDescription: Testing if a function returns a list or a bool


code:
from matplotlib import pyplot as plt
from scipy.misc import lena, ascent

source = lena()
template = ascent()
matched = hist_match(source, template)

def ecdf(x):
    """convenience function for computing the empirical CDF"""
    vals, counts = np.unique(x, return_counts=True)
    ecdf = np.cumsum(counts).astype(np.float64)
    ecdf /= ecdf[-1]
    return vals, ecdf

x1, y1 = ecdf(source.ravel())
x2, y2 = ecdf(template.ravel())
x3, y3 = ecdf(matched.ravel())

fig = plt.figure()
gs = plt.GridSpec(2, 3)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1], sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(gs[0, 2], sharex=ax1, sharey=ax1)
ax4 = fig.add_subplot(gs[1, :])
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()

ax1.imshow(source, cmap=plt.cm.gray)
ax1.set_title('Source')
ax2.imshow(template, cmap=plt.cm.gray)
ax2.set_title('template')
ax3.imshow(matched, cmap=plt.cm.gray)
ax3.set_title('Matched')

ax4.plot(x1, y1 * 100, '-r', lw=3, label='Source')
ax4.plot(x2, y2 * 100, '-k', lw=3, label='Template')
ax4.plot(x3, y3 * 100, '--r', lw=3, label='Matched')
ax4.set_xlim(x1[0], x1[-1])
ax4.set_xlabel('Pixel value')
ax4.set_ylabel('Cumulative %')
ax4.legend(loc=5)

rawDescription: Histogram matching of two images in Python 2.x?


rawDescription: Python: porting to cvxopt quadratic programming from MATLAB's quadprog


code:
d = {'mohammed': '123456789', 'john': '1230012'}

found = False
for k,v in d.items():
    if k == 'mohammed' and v == '123456789':
        print("Match")
        found = True

if not found:  # equivalently, if found == False:
    print("No Match")

rawDescription: Unexpected Behaviour of if statement inside loop over d.items()


rawDescription: SQLAlchemy freezing application

description: SQLAlchemy freezing application


code:
for line in lines:
    split_line = line.split(" -> ")
    head = split_line[0]
    tail = split_line[1]

rawDescription: How to split some parts of a line?

description: Split some parts of a line


code:
with open(valid_phonemes) as v_ph:
    valid_phoneme_set = set(line.strip() for line in v_ph)

rawDescription: Phonemes and graphemes

description: Phonemes and graphemes


code:
d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)

rawDescription: Copying a key/value from one dictionary into another


code:
def all_same(items):
    return all(x == items[0] for x in items)
property_list = ["one", "one", "one"]
all_same(property_list)
property_list = ["one", "one", "two"]
all_same(property_list)
all_same([])

rawDescription: Python: determine if all items of a list are the same item


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

f = plt.figure(figsize(10,7.5))
m = Basemap(projection="mill", lon_0=0)

m.drawcoastlines()
m.drawparallels(np.arange(-90,91,30),labels=[1,0,0,0])
m.drawmeridians(np.arange(-180,181,60), labels=[0,0,0,1])

x,y = m(lon, lat)
m.plot(x, y, color="red", latlon=False, marker='.', linestyle='None')

rawDescription: Plotting a wrapped path in Basemap

description: Plotting a wrapped path in Basemap


code: new_data = np.vstack([data[item] for item in ['a','b','c']]).T

rawDescription: Converting (part of) a numpy recarray into a 2d array?


code:
POWERS_OF_TEN = {10**n for n in range(7)}  # handle strings over 10M chars long

string = "This is a sentence and it has %d characters"
length = len(string) - len('%d') + len("%d" % len(string))
correction = len(string)+1 in POWERS_OF_TEN
string %= length+correction
print(string)  # This is a sentence and it has 43 characters

rawDescription: Using len() in a string

description: Using len() in a string


rawDescription: Sorting the order of bars in pandas/matplotlib bar plots


code:
def OnMenuItemSelected(self, evt):
    dataObj = self.menuIdMap[evt.GetId()]
    dataObj.doSomething()

rawDescription: Reserving a range of IDs in wxPython

description: Reserving a range of IDs in wxPython


code:
Setup
data = {'odjeli': {'informatika': 'I901', 'matematika': 'M505', 'biologija': 'B020'},
'profesori': [{'ime': 'Pero', 'prezime': 'Peric', 'odjel': 'I901'},
              {'ime': 'Ivo', 'prezime': 'Ivic', 'odjel': 'B020'},
              {'ime': 'Mara', 'prezime': 'Maric', 'odjel': 'I901'}],
'predmeti': [{'odjel': 'I901', 'popis': ['matematika', 'programiranje', 'web aplikacije']},
             {'odjel': 'M505', 'popis': ['analiza', 'statistika', 'fizika', 'algebra']},
             {'odjel': 'B020', 'popis': ['biologija', 'kemija', 'matematika']}]}

rawDescription: Merge two dictionary values to one and add it to another dictionary in Python


rawDescription: Python sympy - simplify nonzero factors from an equation


code:
# Gevent monkeypath
from gevent import monkey
monkey.patch_all()

# Gevent imports
import gevent

# Python immports
import functools

# Tornado imports
import tornado.ioloop
import tornado.web
import tornado.httpserver

# Request imports
import requests

# Asynchronous gevent decorator
def gasync(func):
    @tornado.web.asynchronous
    @functools.wraps(func)
    def f(self, *args, **kwargs):
        #self._auto_finish = False
        return gevent.spawn(func, self, *args, **kwargs)
    return f

# Constants
URL_TO_FETCH = 'http://google.co.uk/'

# Global
I = 0

class MainHandler(tornado.web.RequestHandler):
    @gasync
    def get(self):
        global I
        r = requests.get(URL_TO_FETCH)
        I += 1
        print('Got page %d (length=%d)' % (I, len(r.content)))
        self.write("Done")
        self.finish()

# Our URL Mappings
handlers = [
   (r"/", MainHandler),
]

def main():
    # Setup app and HTTP server
    application = tornado.web.Application(handlers)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(9998)

    # Start ioloop
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

rawDescription: How to improve the performance of the combination of gevent and tornado?

description: Improve the performance of the combination of gevent and tornado


code: keywords = [line.strip() for line in f]

rawDescription: Search for a word in two files and print the the two lines with tabular separation


code:
nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]
[tuple(l) for l in nested_lst]

rawDescription: How to convert nested list of lists into a list of tuples in python 3.3?

description: Convert nested list of lists into a list of tuples in python 3.3


rawDescription: Python: How to condition the execution of a part of a function on the return values


code:
# object's class is type
object.__class__ = type
# PyType_Ready(type) sets:
type.__bases__ = (object,)
type.__class__ = type(object)

rawDescription: how does Cpython implement its type Objects, i.e. type's type is always type?

description: How does Cpython implement its type Objects, i.e. type's type is always type


code:
def f(x):
    return x + 1

results = Pool().map(f, [1, 4, 5])
print(results) # [2, 5, 6]

rawDescription: Python threading module in loops with parameters?


code:
import numpy as np
from scipy.spatial import ConvexHull

points = np.random.rand(30, 2)   # 30 random points in 2-D
hull = ConvexHull(points)

#Get centoid
cx = np.mean(hull.points[hull.vertices,0])
cy = np.mean(hull.points[hull.vertices,1])

rawDescription: Scipy: Centroid of convex hull

description: Scipy: Centroid of convex hull


code:
import re

replacements = {
    'sin' : 'np.sin',
    'cos' : 'np.cos',
    'exp': 'np.exp',
    'sqrt': 'np.sqrt',
    '^': '**',
}

allowed_words = [
    'x',
    'sin',
    'cos',
    'sqrt',
    'exp',
]

def string2func(string):
    ''' evaluates the string and returns a function of x '''
    # find all words and check if all are allowed:
    for word in re.findall('[a-zA-Z_]+', string):
        if word not in allowed_words:
            raise ValueError(
                '"{}" is forbidden to use in math expression'.format(word)
            )

    for old, new in replacements.items():
        string = string.replace(old, new)

    def func(x):
        return eval(string)

    return func

if __name__ == '__main__':

    func = string2func(input('enter function: f(x) = '))
    a = float(input('enter lower limit: '))
    b = float(input('enter upper limit: '))
    x = np.linspace(a, b, 250)

    plt.plot(x, func(x))
    plt.xlim(a, b)
    plt.show()

rawDescription: How to plot a math function from string?

description: Plot a math function from string


code:
student_identifier = db.Table('student_identifier',
    db.Column('class_id', db.Integer, db.ForeignKey('classes.class_id')),
    db.Column('user_id', db.Integer, db.ForeignKey('students.user_id'))
)

class Student(db.Model):
    __tablename__ = 'students'
    user_id = db.Column(db.Integer, primary_key=True)
    user_fistName = db.Column(db.String(64))
    user_lastName = db.Column(db.String(64))
    user_email = db.Column(db.String(128), unique=True)

class Class(db.Model):
    __tablename__ = 'classes'
    class_id = db.Column(db.Integer, primary_key=True)
    class_name = db.Column(db.String(128), unique=True)
    children = db.relationship("Student",
                    secondary=student_identifier)

s = Student()
c = Class()
c.children.append(s)
db.session.add(c)
db.session.commit()

rawDescription: Flask sqlalchemy many-to-many insert data


code: K.append(max(l, key=lambda x: x[0]))

rawDescription: Python: List is a int, TypeError

description: Python: List is a int, TypeError


code:
strFile = ''.join(strFile.split())
f = open(filename, 'w')
f.write(strFile)
f.close()

rawDescription: Simple way to perform various replacements of string in a txt and erase whitespaces with python


rawDescription: How can I get all the plain text from a website with Scrapy?

description: Get all the plain text from a website with Scrapy


code: ['AAAGCATT', 'AATACATT', 'AATGAATT']

rawDescription: Changing multiple positions in a list

description: Changing multiple positions in a list


rawDescription: how to access key values in a json files dictionaries with python

description: Access key values in a json files dictionaries with python


code:
Civic96
Camry98
Sentra98

rawDescription: Print original input order of dictionary in python


code:
from storages.backends.s3boto import S3BotoStorage

from django.contrib.staticfiles.storage import ManifestFilesMixin

class CustomS3Storage(ManifestFilesMixin, S3BotoStorage):
    pass

StaticRootS3BotoStorage = lambda: CustomS3Storage(location='static')
MediaRootS3BotoStorage  = lambda: S3BotoStorage(location='uploads')

rawDescription: Django 1.8 Cache busting + Amazon S3

description: Django 1.8 Cache busting + Amazon S3


code:
ws1 = wb1.get_sheet_by_name('Sheet1')
ws2 = wb1.get_sheet_by_name('Sheet2')
ws3 = wb1.get_sheet_by_name('Sheet3')

rawDescription: Adding cell values from multiple sheets in Excel workbook via Python


rawDescription: How can I tranform this (100, 100) numpy array into a grayscale sprite in pygame?

description: Tranform this (100, 100) numpy array into a grayscale sprite in pygame


code:
from itertools import dropwhile

output = list(dropwhile(lambda l: 'def set' not in l, lines))

rawDescription: Adding extra statements in a python list comprehension


code:
from xml.etree import ElementTree as ET

source = '''<ROWSET>
<ROW>
<element>Element1</element>
<element_id>01</element_id>
</ROW>
<ROW>
<element>Element2</element>
<element_id>02</element_id>
</ROW>
<ROW>
<element>Element3</element>
<element_id>03</element_id>
</ROW>
</ROWSET>'''
root = ET.fromstring(source)
target_element_value = 'Element2'
result = root.find('.//ROW[element="' + target_element_value + '"]/element_id')
print(result.text)

rawDescription: ElementTree, how to find neighbor element


code:
[  # make a list of:
  l[a*width:(a+1)*width]
    # get the 'a'-th slice of length 'width' of the initial list
  for a in xrange(len(l)/width)  # for 'len(l)/width' slices
]

rawDescription: How do I create bidimensional table from list?

description: Create bidimensional table from list


code:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

rawDescription: Sort a Python dictionary by value

description: Sort a Python dictionary by value


code: ripple(x)

rawDescription: Write strings to another file

description: Write strings to another file


code:
#            cv2.cvtColor(img, cv2.COLOR_GRAY2BGR, img, 3)
color_mask = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

rawDescription: Python openCV: I get an unchanged image when I use cvtColor


rawDescription: Named Stuctured Data storage in Python

description: Named Stuctured Data storage in Python


code:
myLists = dict()
for x in range(22):
    myLists[ 'list%d' % x ] = [0,0,0,0,0]

rawDescription: How Can I name a list inside a 'FOR' loop

description: Name a list inside a 'FOR' loop


code:
if(self.hp == 0):
    self.current_image = self.images[1]

rawDescription: pygame: replacing image of an item/enemy

description: Pygame: replacing image of an item/enemy


code:
for s in (s.strip () for s in open ('test', 'r') ):
    p = sys.maxint if s == 'sys.maxint' else int (s)
    print (p)

rawDescription: Reading sys.maxint from file

description: Reading sys.maxint from file


code: slime = monster_dict['Slime']

rawDescription: Instantiate an object using a string as its name in Python


code:
class MyRadioGroup(QWidget):
    def __init__(self, radioes=None):
        QWidget.__init__(self)
        self.radioes = radioes  # good idea to store a reference to it
        for radio in radioes:
            radio.checkSignal.connect(self.update)

    def update(self, value):
        print("Checked", value)

rawDescription: Custom signal not working in PySide

description: Custom signal not working in PySide


code:
from models import CarsByColor
from google.appengine.ext import db
from google.appengine.ext.mapreduce import operation as op
from google.appengine.ext.mapreduce.model import MapreduceState

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

def process(entity):
    """Process individual Car"""
    color = entity.color
    if color:
        yield op.counters.Increment('car_color_%s' % color)

class UpdateCounters(webapp.RequestHandler):
    """Create stats models CarsByColor based on the data
    gathered by mapreduce counters"""
    def post(self):
        """Called after mapreduce operation are finished"""
        # Finished mapreduce job id is passed in request headers
        job_id = self.request.headers['Mapreduce-Id']
        state = MapreduceState.get_by_job_id(job_id)
        to_put = []
        counters = state.counters_map.counters
        # Remove counter not needed for stats
        del counters['mapper_calls']
        for counter in counters.keys():
            stat = CarsByColor.get_by_key_name(counter)
            if not stat:
                stat = CarsByColor(key_name=counter,
                                name=counter)
            stat.value = counters[counter]
            to_put.append(stat)
        db.put(to_put)

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Updated.')

application = webapp.WSGIApplication(
                                     [('/mapred_update', UpdateCounters)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: Simple counter example using mapreduce in Google App Engine


code:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
    LEFT, DISABLED, NORMAL, RIDGE, END

rawDescription: Wrapping lines with long class/attributes names in Python


code:
st = {"string3", "string1"}
my_list = ['string1', 'string2', 'string3']
st.issuperset(my_list)
my_list = ['string1', 'string3']
st.issuperset(my_list)
my_list = ['string1']
st.issuperset(my_list)
my_list = ['string3']
st.issuperset(my_list)

rawDescription: Searching python list for presence of combinations of only a set of strings


code:
from ctypes import *

PyObject_HEAD = [
    ('ob_refcnt', c_size_t),
    ('ob_type', c_void_p),
]

class EVP_MD(Structure):
    _fields_ = [
        ('type', c_int),
        ('pkey_type', c_int),
        ('md_size', c_int),
        ('flags', c_ulong),
        ('init', c_void_p),
        ('update', c_void_p),
        ('final', c_void_p),
        ('copy', c_void_p),
        ('cleanup', c_void_p),
        ('sign', c_void_p),
        ('verify', c_void_p),
        ('required_pkey_type', c_int*5),
        ('block_size', c_int),
        ('ctx_size', c_int),
    ]

class EVP_MD_CTX(Structure):
    _fields_ = [
        ('digest', POINTER(EVP_MD)),
        ('engine', c_void_p),
        ('flags', c_ulong),
        ('md_data', POINTER(c_char)),
    ]

class EVPobject(Structure):
    _fields_ = PyObject_HEAD + [
        ('name', py_object),
        ('ctx', EVP_MD_CTX),
    ]

rawDescription: Expose _hashlib.pyd internals for EVP_MD_CTX?


code:
x=datetime(2011, 1, 5)
y=datetime(2011, 1, 9)
s.ix[x:y]
s.ix[x:y].asfreq(BDay())

rawDescription: Get business days between start and end date using pandas


code:
if keyword in line:
    ...

rawDescription: Reading the contents of a specific line in Python?


code:
def changeImage(self):

    ##
    ##  FUNCTION THAT UPDATES THE IMAGES AND CYCLES THROUGH THEM
    ##

    #if player is going left
    while faceWhatDirection == 1 and keyDown == True:
        self.image =self.imagesLeft[0]
        self.image =self.imagesLeft[1]

    #if player is going right
    while faceWhatDirection == 2 and keyDown == True:
        self.image =self.imagesRight[0]
        self.image =self.imagesRight[1]

    #if player is going up
    while faceWhatDirection == 3 and keyDown == True:
        self.image =self.imagesUp[0]
        self.image =self.imagesUp[1]

    #if player is going down
    while faceWhatDirection == 4 and keyDown == True:
        self.image =self.imagesDown[0]
        self.image =self.imagesDown[1]

rawDescription: Character is frozen on Pygame game

description: Character is frozen on Pygame game


code:
import requests

r = requests.get("http://www.carnextdoor.com.au/find-a-car/")

from bs4 import BeautifulSoup

soup = BeautifulSoup(r.content.replace("<!--",""))

print(soup.select("div #location_list"))

rawDescription: accessing html elements BeautifulSoup Python2.7

description: Accessing html elements BeautifulSoup Python2.7


code:
tic = time.time()
resultsAsync = [pool.apply_async(runMyODE, args=(INIT[combi,:],tval,{'para': PARA[combi,:]})) for combi in range(numComb)]
toc = time.time()

rawDescription: Python's multiprocessing: speed up a for-loop for several sets of parameters, "apply" vs. "apply_async"


code:
# add this outside your for loop
writeHeader = True

# use the following where you write to csv
if writeHeader is True:
    df.to_csv('test.csv', mode='a', header=True, index=False)
    writeHeader = False
else:
    df.to_csv('test.csv', mode='a', header=False, index=False)

rawDescription: Keep header while appending to Pandas dataframe w/ Python


code:
for stat in Character.stats:
    setattr(self, stat, parser.get(self.char_class, stat))

rawDescription: Python - Assigning attributes to a class instance using a for loop and a list


rawDescription: Merge sort a list of words

description: Merge sort a list of words


code:
import os

# List all files in current directory
files = os.listdir('.')
recent_images = sorted(files)[-5:]

rawDescription: File Counter in python or last 5 files

description: File Counter in python or last 5 files


code:
inputstr = "The boy is running on the train"
words = inputstr.split()
secondwords = iter(words)
next(secondwords)  # output is ignored
[' '.join((first, second)) for first, second in zip(words, secondwords)]

rawDescription: Split strings by 2nd space

description: Split strings by 2nd space


code:
DOWNLOADER_MIDDLEWARES = {
    'mytest.dlmw.FilterURLs': 1,
}

rawDescription: Allow redirects in Scrapy

description: Allow redirects in Scrapy


code:
import math
cartesianAngleRadians = (450-mapAngleDegrees)*math.pi/180.0

rawDescription: Drawing Arrow in (x,y) coordinate in Python