code:
## Define a Python function to launch a do-file
def dostata(dofile, *params):
    ## Launch a do-file, given the fullpath to the do-file
    ## and a list of parameters.
    import subprocess
    cmd = ["stata", "do", dofile]
    for param in params:
        cmd.append(param)
    return subprocess.call(cmd)

## Do some processing in Python

## Run a do-file
dostata("/home/roberto/Desktop/pyexample3.do", "mpg", "weight", "foreign")

rawDescription: Run Stata do file from Python

description: Run Stata do file from Python


code: {key: sum(len(dct[key]) for dct in dataset.values()) for key in 'ab'}

rawDescription: How to find the sum of the lengths of a list in a dictionary of dictionaries?

description: Find the sum of the lengths of a list in a dictionary of dictionaries


code:
import school as sch
teacher = sch.Teacher()

rawDescription: How to group mutliple modules into a single namespace?

description: Group mutliple modules into a single namespace


code:
...
{"date": "September 20, 1958", "artist": "Domenico Modugno", "song": "Nel Blu Dipinto Di Blu (Volar\u00c3\u00a9)"}
{"date": "September 20, 1958", "artist": "The Everly Brothers", "song": "Bird Dog"}
{"date": "September 20, 1958", "artist": "The Elegants", "song": "Little Star"}
{"date": "September 20, 1958", "artist": "Tommy Edwards", "song": "It's All In The Game"}
{"date": "September 20, 1958", "artist": "Jimmy Clanton And His Rockets", "song": "Just A Dream"}
{"date": "September 20, 1958", "artist": "Poni-Tails", "song": "Born Too Late"}
{"date": "September 20, 1958", "artist": "The Olympics", "song": "Western Movies"}
{"date": "September 20, 1958", "artist": "Little Anthony And The Imperials", "song": "Tears On My Pillow"}
{"date": "September 20, 1958", "artist": "Robin Luke", "song": "Susie Darlin'"}
{"date": "September 27, 1958", "artist": "Domenico Modugno", "song": "Nel Blu Dipinto Di Blu (Volar\u00c3\u00a9)"}
{"date": "September 27, 1958", "artist": "The Everly Brothers", "song": "Bird Dog"}
{"date": "September 27, 1958", "artist": "Tommy Edwards", "song": "It's All In The Game"}
{"date": "September 27, 1958", "artist": "The Elegants", "song": "Little Star"}
{"date": "September 27, 1958", "artist": "Jimmy Clanton And His Rockets", "song": "Just A Dream"}
{"date": "September 27, 1958", "artist": "Little Anthony And The Imperials", "song": "Tears On My Pillow"}
{"date": "September 27, 1958", "artist": "Robin Luke", "song": "Susie Darlin'"}
...

rawDescription: How to scrape more efficiently with Urllib2?

description: Scrape more efficiently with Urllib2


code:
def coerce(value):
    SIMPLE_TYPES = (int, long, float, bool, basestring)
    if value is None or isinstance(value, SIMPLE_TYPES):
        return value
    elif isinstance(value, datetime.date):
        return value.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    elif hasattr(value, 'to_dict'):    # hooray for duck typing!
        return value.to_dict()
    elif isinstance(value, dict):
        return dict((coerce(k), coerce(v)) for (k, v) in value.items())
    elif hasattr(value, '__iter__'):    # iterable, not string
        return map(coerce, value)
    else:
        raise ValueError('cannot encode %r' % value)

rawDescription: Python StructuredProperty to dictionary

description: Python StructuredProperty to dictionary


rawDescription: parse blocks of text from text file using Python

description: Parse blocks of text from text file using Python


code:
from visual import *
stars = []
galaxies = []
for i in  range(10):
   stars.append(sphere(...))
for j in range(20):
   galaxies.append(sphere(...))
for star, galaxy, starpos, galaxypos in zip(stars, galaxies,
                                            position, G_position):
   star.pos = starpos
   galaxy.pos = galaxypos

rawDescription: Visual module in python assign objects

description: Visual module in python assign objects


code:
# Store country_codes and continent_codes column data for further usage
oldval = np.array(df['country_codes'])
newval = np.array(df['continent_codes'])

# Mask of elements to be changed
mask = np.in1d(arr,oldval)

# Indices for each match from oldval in arr
idx = np.searchsorted(oldval,arr.ravel()[mask])

# Using the mask put selective elements from continent_codes column into arr
arr.ravel()[mask] = newval[idx]

rawDescription: Replace values in numpy 2D array based on pandas dataframe


code:
from math import log
logmax = log(Vmax / Vmin, b)
X = Xmax * log(V / Vmin, b) / logmax
V = Vmin * b ** (logmax * X / Xmax)

rawDescription: Linear X Logarithmic scale

description: Linear X Logarithmic scale


rawDescription: DataFrame to nested JSON

description: DataFrame to nested JSON


code:
@register.assignment_tag
def question_answer(venture, question):
    answers = question.answers.filter(venture=venture)
    return answers[0] if answers else None

rawDescription: Filter queryset in django templates

description: Filter queryset in django templates


code:
def pdfServingUrl(request, blob_key):
    from urlparse import urlsplit, urlunsplit
    split = list(urlsplit(request.url))
    split[2] = '/PDF?key=%s' % blob_key.urlsafe() # rewrite the url 'path'
    return urlunsplit(tuple(split))

rawDescription: How to serve pdf (or non-image) files through google app engine with python flask?

description: Serve pdf (or non-image) files through google app engine with python flask


code:
def groupedAvg(myArray, N=2):
    result = np.cumsum(myArray, 0)[N-1::N]/float(N)
    result[1:] = result[1:] - result[:-1]
    return result

rawDescription: Fast way to take average of every N rows in a .npy array


code: res.shape = (res.shape[0], res.shape[1]*res.shape[2]) ## converts to num_rasters, h*w

rawDescription: Seeking a more efficient python numpy ravel+reshape


code:
def update_view(self, data):
    pos = self.myWidgetScrollbar.get()
    self.myWidget.configure(yscrollcommand=None, state=NORMAL)
    self.myWidget.delete(1.0, END)
    self.myWidget.insert(END, data)
    self.myWidget.configure(yscrollcommand=self.myWidgetScrollbar.set, state=DISABLED)
    self.myWidgetScrollbar.get()
    self.myWidgetScrollbar.set(pos)

rawDescription: Stop Text widget from scrolling when content is changed


code:
fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(10, 4),
                                        sharex=True, sharey=True)
img_left = ax_left.scatter(x, y, c=z)
fig.colorbar(img_left, ax=ax_left)
img_right = ax_right.scatter(x_ma, y_ma, c=z_ma)
fig.colorbar(img_right, ax=ax_right)

rawDescription: Matplotlib Scatter plot filter color (Colorbar)


code:
import pandas as pd
df = pd.DataFrame({'a': range(10), 'b': range(5,15), 'c': range(7,17)})
df.plot()

rawDescription: Is it possible to plot multiline chart on Python ggplot?


code:
import numpy as np
import matplotlib.pyplot as plt
from cStringIO import StringIO

s=StringIO()
t=StringIO()

# Save fig a with one cmap to a StringIO instance. Need to explicitly define format
a=np.random.rand(20,20)
plt.imsave(s,a,cmap='jet',format='png')

# Save fig b with a different cmap
b=np.random.rand(20,20)
plt.imsave(t,b,cmap='copper',format='png')

# Return to beginning of string buffer
s.seek(0)
t.seek(0)

# Get the array of data
figa=plt.imread(s)
figb=plt.imread(t)

# Stitch the two arrays together
figc=np.concatenate((figa,figb),axis=1)

# Save without a cmap, to preserve the ones you saved earlier
plt.imsave('figc.png',figc,cmap=None)

rawDescription: concatenate two images from plt.imsave with different cmaps without installing another package

description: Concatenate two images from plt.imsave with different cmaps without installing another package


rawDescription: Random Forest not working in opencv python (cv2)


code: sum(map(s.count, ("Spot", "brown", "hair")))

rawDescription: Counting occurrences of multiple strings in another string


code:
import time
from functools import partial
from multiprocessing import Pool
from multiprocessing.managers import BaseManager

if __name__ == "__main__":

    example = [1,2,3,4,5]

    # Create our custom manager, register the Counter object with it,
    # start it, and then create our shared Counter instance.
    m = BaseManager()
    m.register('Counter', Counter)
    m.start()
    counter = m.Counter(len(example))

    p = Pool(processes=2)

    # We create a partial so that it's easier to pass the counter instance
    # along with every value in our example iterable.
    func = partial(conprintNum, counter)

    p.map(func, example)

rawDescription: How to write a progress counter/time for concurrency?

description: Write a progress counter/time for concurrency


rawDescription: ChromeDriver Quits Unexpectedly

description: ChromeDriver Quits Unexpectedly


code:
v = [1,2,3]
arr = np.arange(12).reshape(3,4)
arr
np.column_stack([arr, v])

rawDescription: Best way to add a new column to a Numpy array

description: Add a new column to a Numpy array


code:
with open('filename', 'rb') as f:
    dosomething()

# is effectively the same as

f = open('filename', 'rb')
try:
    dosomething()
finally:
    f.close()

rawDescription: Python recursive folder read

description: Python recursive folder read


code: b[:,:,newaxis] + c

rawDescription: Python, numpy : 3 dimensions broadcast

description: Python, numpy : 3 dimensions broadcast


code:
import matplotlib.dates as mdates
...
plt.gca().xaxis.major.formatter = mdates.DateFormatter('%Y/%m/%d %H:%M')

rawDescription: Is there a ready solution in matplotlib to plot times?


code:
import string
good_characters= string.ascii_letters # a-z, A-Z

rawDescription: Use an External file to replace special characters?


code:
import types
ns = types.SimpleNamespace(alfa = 1, bravo = 2, charlie = 3)
list(ns.__dict__)
sorted(ns.__dict__)

rawDescription: How to get all user defined attributes in types.SimpleNamespace type?

description: Get all user defined attributes in types.SimpleNamespace type


code:
words = ['você', 'quer', 'uma', 'maçã']
for word in words:
    word.isalpha()

rawDescription: Check whether a string is alphabetical for languages other than english


rawDescription: Print the Python Exception/Error Hierarchy


code:
import json
def json_to_series(text):
    keys, values = zip(*[item for dct in json.loads(text) for item in dct.items()])
    return pd.Series(values, index=keys)

rawDescription: Pandas expand json field across records

description: Pandas expand json field across records


code:
x0 = np.array([1.05,0.95])
x_history = np.array([[1e8,1e8]])
fx_history = np.array([[1e8]])

rawDescription: How do you stop the scipy.optimize.fmin function and start it again using the optimization history?

description: Stop the scipy.optimize.fmin function and start it again using the optimization history


rawDescription: Python logging module - time since last log


code:
True
True
False

rawDescription: Detect alternating signs

description: Detect alternating signs


rawDescription: How to hide herokuapp.com site built in Django when the site is live

description: Hide herokuapp.com site built in Django when the site is live


code:
df.groupby(np.arange(len(df))//10)
for k,g in df.groupby(np.arange(len(df))//10):
    print(k,g)

rawDescription: How to iterate over consecutive chunks of Pandas dataframe efficiently

description: Iterate over consecutive chunks of Pandas dataframe efficiently


code:
polly(**{cracker: 'cracker', wants: True})
d = {cracker: 'biscuit', wants: True}
polly(**d)

rawDescription: passing a dictionary by reference instead of using eval / how to pass a variable number of arguments

description: Passing a dictionary by reference instead of using eval / how to pass a variable number of arguments


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

# the plotting part
ax.plot(data[dataselector,0], data[dataselector,1], 'ro')
ax.plot(data[-dataselector,0], data[-dataselector,1], 'bo')

rawDescription: How do I separate a data set on a scatter plot

description: Separate a data set on a scatter plot


rawDescription: Issue with creating variables on the go in a class in python


code:
from Flask import session
# in order to use sessions you have to use a secret key for your app
app.secret_key = 'some secret key'
@app.route("/", methods=["GET", "POST"])
def start_view():
    img_list = ['filename1', 'filename2', 'filename3']

    # if this is not the first form submission
    if session.has_key('current'):
        # if we reach the end of the list show the first image again
        if int(session['current']) == len(img_list) - 1:
            session['current'] = 0
        # move to next image
        else:
            session['current'] = int(session['current']) + 1
    else:
        session['current'] = 0

    picture = 'first_image_filename' # this should be the img on load
    form = InputForm(csrf_enabled=False)
    if form.validate_on_submit():
        picture = img_list[int(session['current'])] # the filename of the next image
        form.picture.data = ""

    return render_template('04-2.html', form=form, picture=picture)

rawDescription: How to get a new object after form submittig?

description: Get a new object after form submittig


code:
from collections import defaultdict

class Graph(object):
    """ Graph data structure, undirected by default. """

    def __init__(self, connections, directed=False):
        self._graph = defaultdict(set)
        self._directed = directed
        self.add_connections(connections)

    def add_connections(self, connections):
        """ Add connections (list of tuple pairs) to graph """

        for node1, node2 in connections:
            self.add(node1, node2)

    def add(self, node1, node2):
        """ Add connection between node1 and node2 """

        self._graph[node1].add(node2)
        if not self._directed:
            self._graph[node2].add(node1)

    def remove(self, node):
        """ Remove all references to node """

        for n, cxns in self._graph.iteritems():
            try:
                cxns.remove(node)
            except KeyError:
                pass
        try:
            del self._graph[node]
        except KeyError:
            pass

    def is_connected(self, node1, node2):
        """ Is node1 directly connected to node2 """

        return node1 in self._graph and node2 in self._graph[node1]

    def find_path(self, node1, node2, path=[]):
        """ Find any path between node1 and node2 (may not be shortest) """

        path = path + [node1]
        if node1 == node2:
            return path
        if node1 not in self._graph:
            return None
        for node in self._graph[node1]:
            if node not in path:
                new_path = self.find_path(node, node2, path)
                if new_path:
                    return new_path
        return None

    def __str__(self):
        return '{}({})'.format(self.__class__.__name__, dict(self._graph))

rawDescription: Representing graphs (data structure) in Python


code:
formatter = LevelFormatter(fmt='<default log format>', level_fmts={logging.INFO: '<format string for info>'})
handler.setFormatter(formatter)

rawDescription: python logging: Different formatters for the same log file

description: Python logging: Different formatters for the same log file


code:
with open('testFile_out.txt','w') as fout:
    for line in data:
        fout.write(' '.join(line)+'\n')

rawDescription: Read file into dictionary and manipulate data


code:
import os
def free_space_up_to(free_bytes_required, rootfolder, extension=".avi"):
    file_list= files_to_delete(rootfolder, extension)
    while file_list:
        statv= os.statvfs(rootfolder)
        if statv.f_bfree*statv.f_bsize >= free_bytes_required:
            break
        os.remove(file_list.pop())

rawDescription: Find the oldest file (recursively) in a directory


code:
data = ["foo", "bar", "baz"]
X = np.arange(len(data)).reshape(-1, 1)
X

rawDescription: How to use string kernels in scikit-learn?

description: Use string kernels in scikit-learn


code:
from datetime import datetime
intDates = [20130710.0, 20130802.0, 20130806.0]
[datetime.strptime(format(d, '.0f'), '%Y%m%d') for d in intDates]

rawDescription: Converting List of Float values into Dates


code:
import csv
import io
sample = '1¶¦text "could" be\'tricky\n\'\\\\¦§2¶¦or easy¦'
input = LineTerminatorTranslator(io.StringIO(sample), '§')
list(csv.reader(input, delimiter='¶', quotechar='¦'))

rawDescription: can I use the csv module when the end of record marker is not a new line?

description: Use the csv module when the end of record marker is not a new line


code: result[objid] = new_val

rawDescription: Accessing elements in arbitarily nested structure of lists / dicts


code:
question_sets = {
    'set_1': ['disagree', 'whatevs', 'agree'], # define these lists from 1 to whatever
}

for setname, setcols in question_sets.items():
    # plug the NaNs with 0
    df[setcols].fillna(0)

    # scale each column with 0 or 1 in the question set with an ascending value
    for val, col in enumerate(setcols, start=1):
        df[col] *= val

    # create new column by summing all the question set columns
    df[setname] = df[question_set_columns].sum(axis=1)

    # delete all the old columns
    df.drop(setcols, inplace=True, axis=1)

df

rawDescription: Risks re changing NaN responses to zero in Python DataFrame


code:
login['AvailabilityDelta'] = 1
logout['AvailabilityDelta'] = -1

rawDescription: How do I get a Pandas TimeSeries for user sessions (using Pandas or Numpy)

description: Get a Pandas TimeSeries for user sessions (using Pandas or Numpy)


code:
dictionary = {}
with open('path/to/file') as infile:
    for line in infile:
        key,value = line.split(" ")
        dictionary[key] = int(value)

rawDescription: From txt file to Python dictionary

description: From txt file to Python dictionary


code: passIf = lambda client=client: client.returncode(CMD2) == 0

rawDescription: Python Lambdas and Variable Bindings

description: Python Lambdas and Variable Bindings


rawDescription: How can I get the ProgressDialog to close before I open my MessageBox?

description: Get the ProgressDialog to close before I open my MessageBox


code: [{'four': 'green', 'five': 'yellow', 'two': 'blue'}, {'seven': 'black', 'six': 'white', 'two': 'yellow'}]

rawDescription: iterate list of dictionary and append python

description: Iterate list of dictionary and append python


code:
L = set(L)
return [i for i in a if -1*i in a]

rawDescription: How to "negate"(?) a list - Python

description: "negate"(?) a list - Python


code: string = str(resp)

rawDescription: writing persian text into a text file in the way which could be read in python

description: Writing persian text into a text file in the way which could be read in python


code:
d
types = [type(x['name'], (object,), {'title': x['title']}) for x in d]
types[0]()
types[0]().title

rawDescription: Generating class dynamically from a list of values


code:
from wsgiref.util import request_uri
import sys

def logging_middleware(application, stream=sys.stdout):
    def _logger(environ, start_response):
        stream.write('REQUEST\n')
        stream.write('%s %s\n' %(
            environ['REQUEST_METHOD'],
            request_uri(environ),
        ))

        for name, value in environ.items():
            if name.startswith('HTTP_'):
                stream.write('    %s: %s\n' %(
                    name[5:].title().replace('_', '-'),
                    value,
                ))
        stream.flush()
        def _start_response(code, headers):
            stream.write('RESPONSE\n')
            stream.write('%s\n' % code)
            for data in headers:
                stream.write('    %s: %s\n' % data)
            stream.flush()
            start_response(code, headers)
        return application(environ, _start_response)
    return _logger

rawDescription: Debug/Monitor middleware for python wsgi applications


code:
import pandas as pd
df1 = pd.DataFrame([[23, 'Moscow', 'Msk', ''],
                    [34, 'Obninsk', 'Msk', 'Msk'],
                    [56, '', '', 'Spb'],
                    [17, 'Tula', 'Spb', '']],
                   columns=['ID', 'City', 'Region', '2City'])
df2 = pd.DataFrame([['Msk', 'Msk'],
                    ['Spb', 'Spb'],
                    ['Tula', 'Msk'],
                    ['Moscow', 'Msk']],
                   columns=['City', 'Office'])

df = pd.concat([df1.loc[df1[x].isin(df2['City']), x] for x in ['City', 'Region', '2City']])
df1['Join'] = df.groupby(df.index).first()
output = df1.merge(df2, left_on='Join', right_on='City', how='right')

rawDescription: VLOOKUP Excel analog in pandas python

description: VLOOKUP Excel analog in pandas python


code:
dateTime = QDateTimeEdit();
dateTime.setDisplayFormat("hh:mm");
dateTime.setFrame(False);
myTableWidget.setCellWidget(row, column, dateTime);

rawDescription: How to set the column text format of QTableWidget?

description: Set the column text format of QTableWidget


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

rawDescription: Python argparse: default value or specified value


code:
for p in place:
    for item in p:
        if item in US:
            c = "US"
            break
    else:
        c = "Non-US"
    country.append(c)

rawDescription: Check if items in one list exists in another list


rawDescription: Python: How do i get the name of the current archive?


code:
# Map items in self.values to strings (necessary if they are not strings).
print("All values: [%s]" % ", ".join(map(str, self.values)))

# Use this if the contents of self.values are strings.
print("All values: [%s]" % ", ".join(self.values))

rawDescription: Get values from Entry widgets and create list of variables Tkinter


code:
# Create dictionaries with keys as keywords and values as argument values
kwargs0 = {'arg0': 0, 'arg1': 2, 'arg2': 5}
kwargs1 = {'arg99': 1, 'arg13': None, 'arg0': 7}

# Call the function and UNPACK the dictionaries
update_database('db_name', **kwargs0)
update_database('db_name', **kwargs1)

rawDescription: Passing custom keyword arguments to a function


code:
import numpy as np
import pandas as pd
import scipy.ndimage as ndimage

df = pd.DataFrame({'RF': [ 0.3,  1.1,  0.2,  0. ,  0. ,  0. ,  0. ,  0. ,
                           1.1,  0.6,  0. , 0. ,  0. ,  0. ,  0. ,  0. ,
                           0.8,  1.1,  2.3,  1.4,  0.4,  0.2, 0. ,  0. ,
                           0. ,  0. ,  0. ,  0. ]})

consecutive = 5
mask = df['RF'] > 0
df['mask'] = mask
df['dilation'] = ndimage.binary_dilation(mask, structure=[1]*(consecutive+1))
df['erosion'] = ndimage.binary_erosion(df['dilation'],
    structure=[1]*(consecutive+1), border_value=1)
df['labeled'], nobjs = ndimage.label(df['erosion'])
df['evtId'] = np.where(df['labeled'] > 0, df['labeled']-1, np.nan)
print(df[['RF', 'evtId']])

rawDescription: How to identify approximately (threshold defined) continuous non null data using pandas?

description: Identify approximately (threshold defined) continuous non null data using pandas


rawDescription: How to print c_ubyte_Array object in Python

description: Print c_ubyte_Array object in Python


code:
if request.method == "POST":
    data = request.POST.get('radinput_Aj')
    radinputV = json.loads(data)

rawDescription: Issue storing multi valued json format dictionary into mysql table in DJango


rawDescription: Cleaning HTML tables with Pandas

description: Cleaning HTML tables with Pandas


code:
from glob import iglob
pep_files = iglob(sys.argv[1])

rawDescription: Faster way to parse file to array, compare to array in second file


rawDescription: Create overlapping groups with pandas timegrouper


code:
# if python < 3, for 'print' statement to work with 'lambda'
from __future__ import print_function

class RightObject(object):
    def __init__(self, text):
        self.text = text

    def required_method(self):
        print('executing %s' % self.text)

class WrongObject(object):
    pass

def exec_if_possible(instance, method):
    """ This function checks for attribute and if it's a function. """
    if hasattr(instance, method):
        res_func = getattr(instance, method)
        if callable(res_func): # is it a function or not?
            res_func()
        else:
            print('it is not a function')
    else:
        print('bad object')

def try_exec(instance, method):
    """ This is a straight-forward function. """
    try:
        res_func = getattr(instance, method)()
    except AttributeError as at_er:
        print(at_er)
    except TypeError as ty_er:
        print(ty_er)

right = RightObject('right one')
wrong = WrongObject()
func = 'required_method'

# This will work:
exec_if_possible(right, func)

# This will fail as expected:
exec_if_possible(right, 'text')
exec_if_possible(wrong, func)

# The same here:
try_exec(right, func)
try_exec(right, 'text')
try_exec(wrong, func)

# creating a simple crash informer:
default_func = lambda: print('default function')

# one liners, but it is not recommended to use them:
getattr(right, func, default_func)()
getattr(wrong, func, default_func)()

rawDescription: How to check method is exist in directly getattr widhout hasattr

description: Check method is exist in directly getattr widhout hasattr


code:
a = MyClass()
b = MyClass()
a == b

rawDescription: Python call __init__() method only one time


code:
import datetime

def calculate_durations(contents):
    last_stamp = None
    durations = []
    for line in contents:
        # extract time and status from the line
        timestr, status = line.split(' : ')[0].split(' Tag ')
        # fix a.m./p.m. to be AM/PM
        timestr = timestr.replace('a.m.', 'AM').replace('p.m.', 'PM')
        # load the time as a python timestamp
        timestamp = datetime.datetime.strptime(timestr, "%d/%m/%Y %I:%M:%S %p")
        # if this is the first timestamp, store the status, and consider the timestamp to be zero
        if last_stamp is None:
            durations.append((datetime.timedelta(0), status))
        # otherwise calculate the timestamp since last
        else:
            durations.append((timestamp-last_stamp, status))
        # save timestamp for next line
        last_stamp = timestamp
    return durations

def print_durations(durations):
    for stamp, status in durations:
        print("{} for {}".format(status, stamp))

rawDescription: Python putting certain texts into a dictionary from a large string


code:
class ProductHandler(BaseHandler):

    def get_product(self, key):
        data = memcache.get(key)
        if data is not None:
            return data
        else:
            data = Product.get_by_id(long(key))
            memcache.add(key, data, 6000)
            return data

    def get(self, id, html):
        product= self.get_product(id)
        if not product:
            self.error(404)
            return

        self.render_jinja(
            'view_product',
            product=product)

rawDescription: Google App Engine: Creating an Ecommerce website


code:
class Quish(object):
    def __init__(self, value):
        self.blub = value

    @property
    def blub(self):
        print('Blub gets ' + self._blub)
        return self._blub

    @blub.setter
    def blub(self, value):
        print('Blub becomes ' + value)
        self._blub = value

rawDescription: Python descriptors __get__ and __set__

description: Python descriptors __get__ and __set__


code:
for k in li:
    d[k] = d.get(k,0) + 2

rawDescription: python dict add and modify operation

description: Python dict add and modify operation


rawDescription: Why does Python remove the last character of a string?


code:
import calendar
import pprint

year = 2011
days_in_week = 8

c = calendar.Calendar()

# First month with zeroes to create full week
l = list(c.itermonthdays(year, 1))

# Slice by days_in_week
l2 = [[l[a*days_in_week:a*days_in_week+days_in_week] for a in range(len(l) / days_in_week + 1)]]
# Add zeroes if needed and slice rest
l2[-1][-1] += [0] * (days_in_week - (len(l2[-1][-1])))
if l2[-1][-1].count(0) == days_in_week:
    l2[-1] = l2[-1][:-1]

for month in range(2, 13):
    # Days in month
    l = range(1, calendar.monthrange(year, month)[1]+1)

    # Add needed zeroes to the beginning
    zeroes_at_end = l2[-1][-1].count(0)
    l = [0] * ((days_in_week - zeroes_at_end) % days_in_week) + l

    # Slice by days_in_week
    l2 += [[l[a*days_in_week:a*days_in_week+days_in_week] for a in range(len(l) / days_in_week + 1)]]
    # Add zeroes if needed and slice rest
    l2[-1][-1] += [0] * (days_in_week - (len(l2[-1][-1])))
    if l2[-1][-1].count(0) == days_in_week:
        l2[-1] = l2[-1][:-1]

pprint.pprint(l2)

rawDescription: How to write a calendar to excel?

description: Write a calendar to excel


code: {'local_tz': 'US/Eastern'}

rawDescription: Save additional attributes in Pandas Dataframe


code:
sys.getsizeof(1.0)
d = dict.fromkeys((float(i) for i in range(1500)), 2.0)
sys.getsizeof(d)

rawDescription: Python memory usage: Which of my objects is hogging the most memory?


code:
#!/usr/bin/kivy
import kivy
kivy.require('1.9.1')

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

Builder.load_string('''
<MyButton>:
    on_press: print(self.np)
''')

class MyButton(Button):
    pass

class MainApp(App):
    def build(self):
        mb1 = MyButton(text="mb1")
        mb2 = MyButton(text="mb2")
        mb1.apply_property(np=NumericProperty(100))

        layout = BoxLayout()
        layout.add_widget(mb1)
        layout.add_widget(mb2)
        return layout

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

rawDescription: Dynamically adding properties with kivy discouraged – why?


code:
def keep_secret(l: wordinput) -> list:
    return [i for i in wordinput if i != 'secret']

print(keep_secret(wordinput))

rawDescription: Avoiding to print out a certain word in a list


code:
parser = argparse.ArgumentParser()
parser.add_argument('--dict', type=FromJSON, default=FromJSON("{}"))
parser.add_argument('--ls', nargs='*', type=str, default = [])
args = parser.parse_args(['--ls', 'tomato', 'jug', 'andes', '--dict', '{"name":"man", "address": "kac", "tags":"don"}'])
args.ls
args.dict
args.dict.decode()

rawDescription: Python: Parse multiple datatypes using argparse


code: re.split(r'(\d+)', your_string)

rawDescription: How to split a string around numbers?

description: Split a string around numbers


code:
def isPower (num, base):
    if base == 1 and num != 1: return False
    if base == 1 and num == 1: return True
    if base == 0 and num != 1: return False
    testnum = base
    while testnum < num:
        testnum = testnum * base
    return testnum == num

rawDescription: how to check if a number is a power of base b?

description: Check if a number is a power of base b


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

# Read data from file into variables
cps, s_load, f_load, s_process, f_process, s_unload, f_unload = np.loadtxt('arena.txt', unpack=True)

colormap = {
    (1, 1):"r",
    (1, 2):"g",
    (1, 3):"b",
    (2, 1):"y",
    (2, 2):"m",
    (2, 3):"k",
    (3, 1):"r",
    (3, 2):"g",
    (3, 3):"b",
    (4, 1):"y",
    (4, 2):"m",
    (4, 3):"k",
}

color_mapper = lambda cps, p:[colormap[c,p] for c in cps]

# Plot a line for every line of data in your file
plt.hlines(cps, s_load, f_load, colors=color_mapper(cps, 1), lw=4, )
plt.hlines(cps, s_process, f_process, colors=color_mapper(cps, 2), lw=4)
plt.hlines(cps, s_unload, f_unload, colors=color_mapper(cps, 3), lw=4)
plt.margins(0.1)
plt.show()

rawDescription: Python plot gantt chart

description: Python plot gantt chart


rawDescription: Numpy.cumsum in reverse

description: Numpy.cumsum in reverse


code:
# Put this in a storage.py files in your app
from django.conf import settings
from django.core.files.storage import FileSystemStorage, get_storage_class
from django.utils.functional import LazyObject

class UploadsStorage(FileSystemStorage):
    def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = getattr(settings, 'UPLOADS_ROOT', None)
        super(UploadsStorage, self).__init__(location, base_url, *args, **kwargs)
        self.base_url = None  # forbid any URL generation for uploads

class ConfiguredStorage(LazyObject):
    def _setup(self):
        storage = getattr(settings, 'UPLOADS_STORAGE', None)
        klass = UploadsStorage if storage is None else get_storage_class(storage)
        self._wrapped = klass()
uploads_storage = ConfiguredStorage()

rawDescription: Opening a data file from the media directory in Django


code:
def foo(my_list, other_inputs=None):
    if other_inputs is not None:
        # Assume other_inputs is some type of iterable
        for input in other_inputs:
            my_list.bar(input)
    return my_list

rawDescription: Default empty lists vs. *args in Python

description: Default empty lists vs. *args in Python


code:
A = zeros(D.shape)
for i, j in I:
    A[i, j] = D[i, j]

rawDescription: How do I do this array indexing in numpy

description: Do this array indexing in numpy


code:
def stylesheet(href='', type='text/css', rel='stylesheet', **kwargs):
    elem = ET.Element('link', href=href, type=type, rel=rel)
    return elem

html.head.append(stylesheet(href="main.css"))

rawDescription: What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?


code:
import re
inputstring = 'School'
re.sub(r'\b[^aeoui]*', '', inputstring, flags=re.I)

rawDescription: python Using Regular Expression to find letters in a string

description: Python Using Regular Expression to find letters in a string


code:
import re

words = [ ['a', 'the', 'one'], ['reason', 'reasons'], ['for', 'of'] ]

words = ['|'.join(x) for x in words]

pattern = r'\b ({}) \s+ ({}) \s+ ({}) \b'.format(*words)

p = re.compile(pattern, re.X)

rawDescription: Python regex: Alternation for sets of words


rawDescription: Get the commands distutils passes to the compiler


code:
for item in lst:
    item.append(counts[tuple(item[1:])])

rawDescription: Append feature frequency to existing list


code:
def constantcall():
    f = open("primes.txt", "w")
    ask = int(input("how many primes? "))
    prime_numbers = primes(ask)
    f.writelines(map(lambda x: "{0}\n".format(x), prime_numbers))

if __name__ == '__main__':
    constantcall()

rawDescription: List not being written to a text file

description: List not being written to a text file


code:
c = set()
recursive_crawler('http://www.nytimes.com', c)

rawDescription: Cannot Write Web Crawler in Python

description: Cannot Write Web Crawler in Python


code:
import concurrent.futures
import asyncio
import os

def list_files():
    return os.listdir(".")

def on_got_files(fut):
   print("got files {}".format(fut.result()))
   loop.stop()

def main():
   with concurrent.futures.ProcessPoolExecutor() as executor:
       fut = loop.run_in_executor(executor, list_files)
       fut.add_done_callback(on_got_files)
       print("Listing files asynchronously")

if __name__ == "__main__":
   loop = asyncio.get_event_loop()
   loop.call_soon(main)
   loop.run_forever()

rawDescription: How do I list files in Asyncio?

description: List files in Asyncio


code: body1 = delimitedList(OneOrMore(Word(alphas + nums)) +~kw)('Body')

rawDescription: getting a grammar to read more than one keyword in the text

description: Getting a grammar to read more than one keyword in the text


code: json.dumps({'numbers': n, 'strings': s, 'x': x, 'y': y})

rawDescription: Python, writing things to json

description: Python, writing things to json


code:
config = ValuesWithCommentsConfigParser()
config.read('config.ini')
assert config.get('local', 'variable1') == 'value1 ; comment1'
assert config.get('local', 'variable2') == 'value2 # comment2'

rawDescription: Python Config parser read comment along with value


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

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(10,3000,100)
y = np.arange(10,3000,100)
X,Y = np.meshgrid(x,y)
Z = np.random.random(X.shape)*8000000
surf = ax.contourf(X,Y,Z, 8, cmap=plt.cm.jet)
ax.set_ylabel('Log Frequency (Hz)')
ax.set_xlabel('Log Frequency (Hz)')
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_minor_formatter(plt.FormatStrFormatter('%d'))
# defining custom minor tick locations:
ax.xaxis.set_minor_locator(plt.FixedLocator([50,500,2000]))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='both',reset=False,which='both',length=8,width=2)
cbar = fig.colorbar(surf, shrink=0.5, aspect=20, fraction=.12,pad=.02)
cbar.set_label('Activation',size=18)
# access to cbar tick labels:
cbar.ax.tick_params(labelsize=5)
plt.show()

rawDescription: Matplotlib so log axis only has minor tick mark labels at specified points. Also change size of tick labels in colorbar


code:
del d['get']
d.get('get', 'Not there, but working')

rawDescription: How would I implement a dict with Abstract Base Classes in Python?


code:
combined = dict()
for name in set(dictOne.keys() + dictTwo.keys()):
  combined[name] = [ dictOne.get(name, 0), dictTwo.get(name, 0) ]

rawDescription: Merging 2d arrays

description: Merging 2d arrays


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

npoints = 10
b, a = np.mgrid[-5:5:npoints*1j, -1.5:1.5:npoints*1j]

z = a + b

fig, ax = plt.subplots()
im = ax.pcolormesh(a, b, z)
fig.colorbar(im)

ax.axis('tight')
plt.show()

rawDescription: heat map using matplotlib

description: Heat map using matplotlib


Python Compilation/Interpretation Process


code:
from gi.repository import GdkPixbuf
formats = GdkPixbuf.Pixbuf.get_formats()
[f.get_name() for f in formats]

rawDescription: Displaying an image with Pygobject and Python 3 from in-memory data


code:
['my', 'first', 'list']
['another', 'list']

rawDescription: items not appending to list, or list returning as empty in python?

description: Items not appending to list, or list returning as empty in python


code:
# plt.show()
plt.savefig("Graph.png", format="PNG")

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

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


code: parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])

rawDescription: Multiple positional arguments with Python and argparse


code:
class Record(models.Model):
    name = models.CharField()

rawDescription: How do I create / access dynamic form fields in Django from within a View?

description: Create / access dynamic form fields in Django from within a View


code:
contacts = {}
pnumber = raw_input('Input number here: ')
if pnumber not in contacts: #not sure how to do this
    name = raw_input("Input name for this number: ")
    contacts[pnumber] = name

rawDescription: Python - If string in dictionary, else add to dictionary and add index


code:
import seaborn as sns
tips = sns.load_dataset("tips")

rawDescription: seaborn FacetGrid , ranked barplot separated on row and col

description: Seaborn FacetGrid , ranked barplot separated on row and col


code: ax = df2['A'].plot(kind="bar")

rawDescription: Plot specific column after DataFrame aggregation


code:
import csv

data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]

with open('ur file.csv','w') as out:
    csv_out=csv.writer(out)
    csv_out.writerow(['name','num'])
    for row in data:
        csv_out.writerow(row)

rawDescription: Save list of ordered tuples as CSV

description: Save list of ordered tuples as CSV


code:
pattern1 = r'pattern-1'
pattern2 = r'pattern-2'
pattern3 = r'pattern-3'

patterns = [pattern1, pattern2, pattern3]

compiled_combined = re.compile('|'.join(x for x in patterns), FLAGS_TO_USE)

rawDescription: Pythonic way to concatenate regex objects


code:
ft = np.fft.fft(y)
integral = sum(ft[105:121])

rawDescription: Calculating Area Under Individual Peaks in Python After FFT


code:
BeautifulSoup(html).select("div.featured__column span")
BeautifulSoup(html).select("div.featured__column span:nth-of-type(1)")
BeautifulSoup(html).select("div.featured__column span:nth-of-type(2)")
BeautifulSoup(html).select("div.featured__column span:nth-of-type(2)")[0].text
BeautifulSoup(html).select("div.featured__column span:nth-of-type(1)")[0].text

rawDescription: Extract data with BeautifulSoup

description: Extract data with BeautifulSoup


code: b3.bind('<Return>', closewindow)

rawDescription: Tkinter Initial Cursor position and Enter to press button


code:
#create flag filled with zeros with same shape as data
flag=numpy.zeros(data.shape)
#combine the two operations without temporary barray
flag[data>=threshold]=1

rawDescription: Huge difference between python and fortran difference for a small program


code:
def __init__(self):
    tk.Tk.__init__(self)
    self.geometry("1360x750")
    frameLabel = tk.Frame(self)
    self.text = tk.Text(frameLabel)
    frameLabel.pack(side=BOTTOM, fill=BOTH)
    self.text.pack(side=RIGHT)
    self.text.insert('end', 'TEST')
    self.queue = Queue.Queue()
    thread = SerialThread(self.queue)
    thread.start()
    self.process_serial()

rawDescription: can we code time in text widget?

description: Can we code time in text widget


code:
df['C'] = (df.A.shift(-1).sub(df.A, fill_value=0) / df.B.shift(-1).sub(df.B, fill_value=0)).round(2).astype(str)
df
df.dtypes

rawDescription: join corresponding column to dataframe pandas

description: Join corresponding column to dataframe pandas


code:
with open('words.txt', 'rU') as f:
    d = {w.rstrip('\n'): i for i, w in enumerate(f, start=1)}

rawDescription: translate string into positions of list of tokens

description: Translate string into positions of list of tokens


code:
# =======================================================================
# Monkey patch ElementTree
import xml.etree.ElementTree as ET

def _serialize_xml(write, elem, encoding, qnames, namespaces):
    tag = elem.tag
    text = elem.text
    if tag is ET.Comment:
        write("<!--%s-->" % ET._encode(text, encoding))
    elif tag is ET.ProcessingInstruction:
        write("<?%s?>" % ET._encode(text, encoding))
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(ET._escape_cdata(text, encoding))
            for e in elem:
                _serialize_xml(write, e, encoding, qnames, None)
        else:
            write("<" + tag)
            items = elem.items()
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (
                            k.encode(encoding),
                            ET._escape_attrib(v, encoding)
                            ))
                #for k, v in sorted(items):  # lexical order
                for k, v in items: # Monkey patch
                    if isinstance(k, ET.QName):
                        k = k.text
                    if isinstance(v, ET.QName):
                        v = qnames[v.text]
                    else:
                        v = ET._escape_attrib(v, encoding)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem):
                write(">")
                if text:
                    write(ET._escape_cdata(text, encoding))
                for e in elem:
                    _serialize_xml(write, e, encoding, qnames, None)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(ET._escape_cdata(elem.tail, encoding))

ET._serialize_xml = _serialize_xml

from collections import OrderedDict

class OrderedXMLTreeBuilder(ET.XMLTreeBuilder):
    def _start_list(self, tag, attrib_in):
        fixname = self._fixname
        tag = fixname(tag)
        attrib = OrderedDict()
        if attrib_in:
            for i in range(0, len(attrib_in), 2):
                attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])
        return self._target.start(tag, attrib)

# =======================================================================

rawDescription: Can ElementTree be told to preserve the order of attributes?


code: ''.join(map(lambda o:'%s %s\n' % o, a.items()))

rawDescription: Python dict to user format string

description: Python dict to user format string


code:
s2 = re.compile("^(DATA_ARRAY )(.*?};)", re.DOTALL|re.MULTILINE)
result = re.sub(s2, r"\1newData", inputData)

rawDescription: Replace with re.sub AFTER matching pattern


code:
import os
os.spawnl(os.P_NOWAIT, 'your_command')

rawDescription: How to generate Wireshark/tcpdump traces

description: Generate Wireshark/tcpdump traces


code:
import types
setattr(a,'method',types.MethodType(lambda self: self.__class__.__name__,a))
a.method()

rawDescription: modify method only having the method's name and instance object

description: Modify method only having the method's name and instance object


compression: true

client: MYSQL

rawDescription: How can I express this format in EBNF?

description: Express this format in EBNF


code:
import datetime
import sqlite3

class GpsCache(object):
    db_path = 'gps_cache.db'
    def __init__(self):
        self.con = sqlite3.connect(self.db_path)
        self.cur = self.con.cursor()

    def _get_period(self, dt=None):
        '''normalize time to 15 minute periods'''
        if dt.minute < 15:
           minute_period = 0
        elif 15 <= dt.minute < 30:
           minute_period = 15
        elif 30 <= dt_minute < 45:
           minute_period = 30
        elif 45 <= dt_minute:
           minute_period = 25
        period_dt = datetime.datetime(year=dt.year, month=dt.month, day=dt.day, hour=dt.hour, minute=minute_period)
        return period_dt

    def get_cache(dt=None):
        period_dt = self._get_period(dt)
        select_sql = 'SELECT * FROM GPS_CACHE WHERE date_time = "%s";' % period_dt.strftime('%Y-%m-%d %H:%M')
        self.cur.execut(select_sql)
        result = self.cur.fetchone()[0]
        return result

    def put_cache(dt=None, data=None):
        period_dt = self._get_period(dt)
        insert_sql = 'INSERT ....'  # edit to your table structure
        try:
            self.cur.execute(insert_sql)
            self.con.commit()
        except sqlite3.OperationalError:
            # assume db is being updated by another process with the current resutls and ignore
            pass

rawDescription: Limit calls to external database with Python CGI


code:
import threading
list1Lock = threading.Lock()

try:
    list1Lock.acquire()
    # change or read from the list here
finally:
    list1Lock.release()
# continue doing other stuff (the lock is released when you leave the with block)

rawDescription: Are Python built-in containers thread-safe?


code:
discountValues['UpperLimit1'] = firstLine[2] # Droped the { and } from assignment
int(discountValues['UpperLimit1'])
discountValues['PercentDiscount1'] = firstLine[4]

rawDescription: Converting dictionary value to integer

description: Converting dictionary value to integer


code:
d = {'a':0.66,'b':0.07,'c':0.04}
start = 0
end = 0
range_dict = {}
for k,v in d.items():
   end+=int(v*100)
   range_dict[k]=xrange(start,end)
   start=end

range_dict

rawDescription: Python: Range() as a dictionary value

description: Python: Range() as a dictionary value


code:
dela = sp.spatial.Delaunay
triang = dela(lattice)

rawDescription: How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay?

description: Find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay


code: bln = x[n]

rawDescription: In python 3, how can I convert a function into an attribute


code:
regex = re.compile(r'(?=(.))(?:black|sack|long|glad)', flags=re.IGNORECASE)
regex.sub(r'\1***', s)

rawDescription: How to replace multiple words in a string through Python in a case insensitive way?

description: Replace multiple words in a string through Python in a case insensitive way


code:
# Sys for stdio stuff
import sys
# re for the re.split -- this can go if you find another way to parse your data
import re

# A global (shame on me) for storing the data we're going to parse from stdin
data = []

# read lines from standard input until it's empty (end-of-file)
for line in sys.stdin:
    # Split lines on spaces (gobbling multiple spaces for robustness)
    # and trim whitespace off the beginning and end of input (strip)
    entry = re.split("\s+", line.strip())

    # Throw the array into my global data array, it'll look like this:
    # [ "0", "Brucella", "melitensis", "Brucellaceae" ]
    # A lot of this code assumes that the first field is an integer, what
    # you call "cluster" in your problem description
    data.append(entry)

# Sort, first key is expected to be an integer, and we want a numerical
# sort rather than a string sort, so convert to int, then sort by
# each subsequent column. The lamba is a function that returns a tuple
# of keys we care about for each item
data.sort(key=lambda item: (int(item[0]), item[1], item[2], item[3]))

# Our recursive function -- we're basically going to treat "data" as a tree,
# even though it's not.
# parameters:
#    start - an integer telling us what line to begin working from so we needn't
#            walk the whole tree each time to figure out where we are.
#    super - An array that captures where we are in the search. This array
#            will have more elements in it as we deepen our traversal of the "tree"
#            Initially, it will be []
#            In the next ply of the tree, it will be [ '0' ]
#            Then something like [ '0', 'Brucella' ] and so on.
#    data -  The global data structure -- this never mutates after the sort above,
#            I could have just used the global directly
def groupedReport(start, super, data):
    # Figure out what ply we're on in our depth-first traversal of the tree
    depth =  len(super)
    # Count entries in the super class, starting from "start" index in the array:
    count = 0

    # For the few records in the data file that match our "super" exactly, we count
    # occurrences.
    if depth != 0:
        for i in range(start, len(data)):
            if (data[i][0:depth] == data[start][0:depth]):
                count = count + 1
            else:
                break; # We can stop counting as soon as a match fails,
                   # because of the way our input data is sorted
    else:
        count = len(data)

    # At depth == 1, we're reporting about clusters -- this is the only piece of
    # the algorithm that's not truly abstract, and it's only for presentation
    if (depth == 1):
        sys.stdout.write("Cluster " + super[0] + ":\n")
    elif (depth > 0):
        # Every other depth: indent with 4 spaces for every ply of depth, then
        # output the unique field we just counted, and its count
        sys.stdout.write((' ' * ((depth - 1) * 4)) +
                         data[start][depth - 1] + '(' + str(count) + ')\n')

    # Recursion: we're going to figure out a new depth and a new "super"
    # and then call ourselves again. We break out on depth == 4 because
    # of one other assumption (I lied before about the abstract thing) I'm
    # making about our input data here. This could
    # be made more robust/flexible without a lot of work
    subsuper = None
    substart = start
    for i in range(start, start + count):
        record = data[i]  # The original record from our data
        newdepth = depth + 1
        if (newdepth > 4): break;

        # array splice creates a new copy
        newsuper = record[0:newdepth]
        if newsuper != subsuper:
            # Recursion here!
            groupedReport(substart, newsuper, data)
            # Track our new "subsuper" for subsequent comparisons
            # as we loop through matches
            subsuper = newsuper

        # Track position in the data for next recursion, so we can start on
        # the right line
        substart = substart + 1

# First call to groupedReport starts the recursion
groupedReport(0, [], data)

rawDescription: For-loop to count differences in lines with python


code:
class MyClass:
    def __new__(cls,**wargs):
        if "create" in wargs: # This is just an example, obviously
            if wargs["create"] >0: # you can use any test here
                # The point here is to "forget" to return the following if your
                # conditions aren't met:
                return super(MyClass,cls).__new__(cls)
        return None
    def __init__(self,**wargs): # Needs to match __new__ in parameter expectations
        print ("New instance!")
a=MyClass()         # a = None and nothing is printed
b=MyClass(create=0) # b = None and nothing is printed
c=MyClass(create=1) # b = <__main__.MyClass object> and prints "New instance!"

rawDescription: Python conditional object instantiation

description: Python conditional object instantiation


code:
class A(Base):
    __tablename__ = 'table_A'
    id = Column(Integer, primary_key=True)
    a = Column(String(32))
    b = Column(String(32))

Index('my_index', A.a, A.b)

rawDescription: Multiple columns index when using the declarative ORM extension of sqlalchemy


code:
edge = pydot.Edge("a_2>10", "literal_0_0")
graph.add_edge(edge)
edge = pydot.Edge("a_2>10", "literal_1_0")
graph.add_edge(edge)
edge = pydot.Edge("a_3>-7", "literal_0_1")
graph.add_edge(edge)
edge = pydot.Edge("a_3>-7", "literal_1_1")
graph.add_edge(edge)

rawDescription: pydot: is it possible to plot two different nodes with the same string in them?

description: Pydot: is it possible to plot two different nodes with the same string in them


code: pattern = re.compile(u'[юЮ]', re.UNICODE)

rawDescription: How to find all capital and lower case occurrences of unicode character using regex and re.sub in Python?

description: Find all capital and lower case occurrences of unicode character using regex and re.sub in Python


rawDescription: Python: Find subsets across many-to-many mapping


code:
import os
from contextlib import contextmanager
from shutil     import rmtree
from tempfile   import mkdtemp

@contextmanager
def named_pipe():
    dirname = mkdtemp()
    try:
        path = os.path.join(dirname, 'named_pipe')
        os.mkfifo(path)
        yield path
    finally:
        rmtree(dirname)

rawDescription: Wait for external program to finish writing to file


code: ip2host = {dic[key][1]:key for key in dic.keys()}

rawDescription: Scanning thorugh lists inside a dictionary of selected groups


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

data = [k.split() for k in '''0           1  4364226
1         200   269110
2         500   158824
3        1000    90368
4        2000    48609
5        3000    32604
6        5000    18921
7       10000     8618
8       25000     2802
9       50000     1000
10     100000      334'''.split('\n')]

soDF = pd.DataFrame(data, columns=('index', 'total_rep', 'users'))

soDF['total_rep'] = pd.to_numeric(soDF['total_rep'])
soDF['users'] = pd.to_numeric(soDF['users'])

soDF['log_total_rep'] = soDF['total_rep'].apply(np.log10)
soDF['log_users'] = soDF['users'].apply(np.log10)
soDF.plot(x='log_total_rep', y='log_users')

rawDescription: using pandas and numpy to parametrize stack overflow's number of users and reputation

description: Using pandas and numpy to parametrize stack overflow's number of users and reputation


code:
sessionObj = requests.session()
sessionOj.get(...) # Do whatever ...

rawDescription: Login and upload file using Python 'requests'


code:
num = 5
den = [1,6,11,6]

#Creating a transfer function G = num/den
G = control.tf(num,den)
w = numpy.logspace(-3,3,5000)
control.nyquist(G,w);

rawDescription: Python Control Package - Increasing resolution of Nyquist plotting


code:
myShape = Part.makeBox(2,2,2)
myShape.translate(Base.Vector(2,0,0))

rawDescription: Python module for parametric CAD

description: Python module for parametric CAD


code:
def get_field_by_name(self, name):
    """
    Returns the (field_object, model, direct, m2m), where field_object is
    the Field instance for the given name, model is the model containing
    this field (None for local fields), direct is True if the field exists
    on this model, and m2m is True for many-to-many relations. When
    'direct' is False, 'field_object' is the corresponding RelatedObject
    for this field (since the field doesn't have an instance associated
    with it).

    Uses a cache internally, so after the first access, this is very fast.
    """

rawDescription: How to introspect django model fields?

description: Introspect django model fields


code:
def call_with_retries(callable, args=(), tries=3):
  for attempt in range(tries):
    try:
      result=callable(*args)
      break
    except:
      traceback.print_exc()
      continue
  else:  # break never reached, so function always failed
    raise  # Reraises the exception we printed above
  return result

rawDescription: How could I pass block to a function in Python which is like the way to pass block in Ruby


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


rawDescription: Is Python Object Instance a unique object in the language?


code:
class CustomWorksheet(gspread.Worksheet):
    def get_links(self, col):
        """Returns a list of all links urls in column `col`.
           Empty cells in this list will be rendered as :const:`None`.
        """
        start_cell = self.get_addr_int(1, col)
        end_cell = self.get_addr_int(self.row_count, col)

        row_cells = self.range('%s:%s' % (start_cell, end_cell))
        return [cell.input_value.split('"')[1] for cell in row_cells if cell.input_value.startswith('=HYPERLINK')]

rawDescription: Retrieve value of links from Google Sheet?


code:
class MyStr(str):
    def __gt__(self, other):
        try:
            return int(self) > int(other)
        except ValueError:
            return False

rawDescription: Can you override a magic method when extending a builtin in python?

description: Override a magic method when extending a builtin in python


code:
'SEP'.join(a)
''.join(a)

rawDescription: Convert a list of elements in a string

description: Convert a list of elements in a string


rawDescription: Numpy masked array modification

description: Numpy masked array modification


rawDescription: Normalizing rows of a matrix python

description: Normalizing rows of a matrix python


rawDescription: How can I do this complex SQL query using Django ORM? (sub-query with a join)

description: Do this complex SQL query using Django ORM? (sub-query with a join)


code:
k,v=map(list, zip(*sorted(di.items(), key=itemgetter(1), reverse=True)))
k
v

rawDescription: python3 unzipping a list of tuples

description: Python3 unzipping a list of tuples


code:
from django import forms

class ChoiceField(forms.ChoiceField):
    def __init__(self, *args, **kwargs):
        self.blank_choice = kwargs.pop('blank_choice', None)
        super(ChoiceField, self).__init__(*args, **kwargs)

    def _get_choices(self):
        return self._choices

    def _set_choices(self, value):
        choices = list(value)
        if self.blank_choice:
            choices = [('', self.blank_choice)] + choices
        self._choices = self.widget.choices = choices

    choices = property(_get_choices, _set_choices)

rawDescription: Showing "Please choose:" in a Django's `Select` widget


code:
Mon - Wed, Fri - Sat
Mon, Wed - Sun
Mon, Wed - Thu, Sat - Sun

rawDescription: Converting for loops to recursion [finding consecutive weekdays]


code:
import music21
def countNotes(s):
    return len(s.recurse().notes)
    # using recurse() instead of .flat to avoid certain caches...

bach = music21.corpus.parse('bach/bwv66.6')
[countNotes(p) for p in bach.parts]

rawDescription: Multiprocess tasks in python that can't be pickled?


code: df

rawDescription: Return DataFrame item using partial string match on rows pandas python


code:
# Headers, centered
print("{: ^15s} {: ^15s} {: ^15s} {: ^15s} {: ^15s}".format(
    "Name", "Age", "Height", "Pay Rate", "Grade")
)

# Dashes (not very readable, but I'm lazy)
print(" ".join([("-" * 15)] * 5))

# Lines
for line in data:
    print("{:15s} {: 15.2f} {: 15.2f} {: 15.2f} {: 15.2f}".format(*line))

rawDescription: Create ASCII table from given list - Python


code:
import random
def mutate(string, mutation, threshold):
    return ''.join([mutation[char] if random.random() < threshold
                                       and char in mutation else char
                                       for char in string])

rawDescription: Using Random Module to Administer DNA Mutations


code:
race.penup() #Inside for loop.
race.right(90)
race.forward(20) #I think it should be 20...
race.right(-90)

rawDescription: python use turtle draw a track n field race track

description: Python use turtle draw a track n field race track


code:
import datetime
t = '08:00-17:00'
times = t.split('-')
start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
if start_time <= datetime.datetime.now().time() < end_time:
        print("Shop open")

rawDescription: Check if current current hour is available in python list


code:
from django.conf.urls import url, include
from yourapp import views

urlpatterns = [
    url(r'articles/^', views.ArticleList.as_view(), name="article-list"),
    url(r'articles/(?P<pk>[0-9]+)/^', views.ArticleDetail.as_view(), name="article-detail"),
]

rawDescription: Django REST Framework: difference between views and viewsets?


rawDescription: compare file line by line python

description: Compare file line by line python


rawDescription: Speeding up column conversions

description: Speeding up column conversions


rawDescription: Pythonic Circular List

description: Pythonic Circular List


code:
#in for loop with enumerate for i
selector.append(' > li:nth-child(%i)' % (i + 1))  # identify child <li> by its order pos

rawDescription: Python Selenium wait for several elements to load


code: tds = (td.text_content() for td in doc.xpath('//td'))

rawDescription: Simple example regarding how to parse data from html output using lxml


code: date = 'The date is {}'.format(get_date())

rawDescription: How to call a python function within quotation marks

description: Call a python function within quotation marks


code: df.pivot('TransID', 'SKUID').fillna(0)

rawDescription: Data transformation for machine learning


code: Series(list(set(s1) & set(s2)))

rawDescription: Finding the intersection between two series in Pandas


code:
class OAuthRemoteApp(object):
    def authorized_handler(self, f):
        def decorated(*args, **kwargs):
            print(self, f, args, kwargs)   #1
            # (<__main__.OAuthRemoteApp object at 0xb74d324c>, <function authorized at 0xb774ba04>, (<__main__.ClientView object at 0xb74d32cc>,), {})
            data = 'resp'
            print((data,) + args)  #2
            # ('resp', <__main__.ClientView object at 0xb74d32cc>)
            return f(*((data,) + args), **kwargs)
        return decorated

vk = OAuthRemoteApp()

class ClientView(object):
    @vk.authorized_handler
    def authorized(self, resp):
        print(self, resp)  #3
        # ('resp', <__main__.ClientView object at 0xb7452eec>)
cv = ClientView()
cv.authorized()

rawDescription: Python - Use decorated function in class


code:
str_command = ...

#Double-check: only allowed methods and foo_obj must have it!
allowed_commands = ['print', 'install', 'remove']
assert str_command in allowed_commands, "Command '%s' is not allowed"%str_command

fn = getattr(foo_obj, str_command, None)
assert callable(fn), "Command '%s' is invalid"%str_command

#Ok, call it!
fn()

rawDescription: How to dynamically select a method call in Python?

description: Dynamically select a method call in Python


code:
def opt_heapsort(s):
    sl = len(s)

    def swap(pi, ci):
        if s[pi] < s[ci]:
            s[pi], s[ci] = s[ci], s[pi]

    def sift(pi, unsorted):
        i_gt = lambda a, b: a if s[a] > s[b] else b
        while pi*2+2 < unsorted:
            gtci = i_gt(pi*2+1, pi*2+2)
            swap(pi, gtci)
            pi = gtci
    # heapify
    for i in range((sl/2)-1, -1, -1):
        sift(i, sl)
    # sort
    for i in range(sl-1, 0, -1):
        swap(i, 0)
        sift(0, i)

rawDescription: Heap Sort: how to sort?

description: Heap Sort: how to sort


code:
import unittest

class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print('MyTestCase.setUpClass')
    def test_one(self):
        print("One")
    def test_two(self):
        print("Two")

class MyTestCase2(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print('MyTestCase2.setUpClass')
    def test_three(self):
        print('Three')

suite = unittest.TestSuite([MyTestCase('test_one'), MyTestCase2('test_three'), MyTestCase('test_two')])

suite.run(unittest.TestResult())

rawDescription: Is it unconventional to override unittest.TestCase's init in Python


code:
result_filled = result2.filled(0)

assert np.all(result_filled == result)

rawDescription: Numpy: multiplying with NaN values without using nan_to_num


code:
seq = []
for i in range(100):
    seq.append(SomeRandomObject())

rawDescription: Make python create a new object

description: Make python create a new object


code:
from django import template
template.add_to_builtins('myapp.templatetags.myapptags')

rawDescription: Abstract Django Application from "Project"


code:
# -*- coding: utf-8 -*-
from flask import Flask
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)
app.config.from_object('config')
from app import views

rawDescription: Flask : How to update and render a variable periodically?


code:
for i in range (1,18):
   try:
       img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits")
       img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits")
       img3=(img2)[2]
       newimg=img1/img3
       pf.writeto("dividedsciPHOTOf105w"+str(i)+".fits",newimg, clobber=True)
   except IOError:
       pass

rawDescription: Ignoring a missing file in a for loop- Python


code:
x1 = 5
x2 = np.random.rand(3,3)
y  = np.array([0.5, 0.5])
(x1 * y).sum() # works fine
(x2[..., np.newaxis] * y).sum() # also works fine

rawDescription: Numpy Dimensions: Multiplications with scalar/matrix


code: zip(*result)

rawDescription: Python list rearranging

description: Python list rearranging


code:
ti = indices[numpy.arange(len(VVm))]
R1 = (VVm[:,None]-VVs[ti,:])**2+(HHm[:,None]-HHs[ti,:])**2
d0 = numpy.nanmin(R1, axis=1) # places where the best index is not a nan
bestepsilons2[~numpy.isnan(d0)] = epsilon[numpy.nanargmin(R1[~numpy.isnan(d0),:], axis=1)]

rawDescription: push for-loop to numpy

description: Push for-loop to numpy


code:
import json

x='''{"Field": [{"Name": "health", "Value": 100}, {"Name": "toxicity", "Value": 78}],
    "Name": "life",
    "Class": "hero.attributes.Life"}'''

attribute=json.loads(x)

# {u'Class': u'hero.attributes.Life',
#  u'Field': [{u'Name': u'health', u'Value': 100},
#             {u'Name': u'toxicity', u'Value': 78}],
#  u'Name': u'life'}

rawDescription: Is this entity definition model too verbose?


code:
# project's settings.py
APP_NAME_MY_SETTING = 'something else'

rawDescription: add variables in settings to be used in views - Django

description: Add variables in settings to be used in views - Django


rawDescription: Regex with end of line in group

description: Regex with end of line in group


rawDescription: duplicating values in a certain way inside a list inside a dictionary

description: Duplicating values in a certain way inside a list inside a dictionary


rawDescription: Webscraping with Xpath in Python

description: Webscraping with Xpath in Python


code:
GQL_PROD_PART_BY_KEYS = ProductParts.gql('WHERE __key__ IN :1')
@property
def defaultPartsData(self):
    return GQL_PROD_PART_BY_KEYS.bind(self.defaultParts)

rawDescription: Loading datasets from datastore and merge into single dictionary. Resource problem


code:
import matplotlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z += 0.1*np.random.random(Z.shape)

plt.figure()
plt.pcolormesh(X, Y, Z)

CS = plt.contour(X, Y, gaussian_filter(Z, 5.), 4, colors='k',interpolation='none')
plt.colorbar()
plt.show()

rawDescription: Plotting contours over pcolormesh data

description: Plotting contours over pcolormesh data


code: option['value']

rawDescription: python BeautifulSoup get select.value not text

description: Python BeautifulSoup get select.value not text


rawDescription: Python sum values by daterange

description: Python sum values by daterange


code:
import math
import collections

rawDescription: Writing list of import modules in a separate .py file


code:
q1 = df[df.quarters == 1]
q2 = df[df.quarters == 2]
q3 = df[df.quarters == 3]
q4 = df[df.quarters == 4]

rawDescription: Divide entire DataFrame based on dates in specific columns into quarterly dataframes


code:
code = compile("def foo(n):return n+10", "<string>", "exec").co_consts[0]
func = Function(code, globals())

rawDescription: Can I create function using 'function' class?

description: Create function using 'function' class


code:
def convert_factor(obj):
    """
    Taken from jseabold's PR: https://github.com/pydata/pandas/pull/9187
    """
    ordered = r["is.ordered"](obj)[0]
    categories = list(obj.levels)
    codes = np.asarray(obj) - 1  # zero-based indexing
    values = pd.Categorical.from_codes(codes, categories=categories,
                                       ordered=ordered)
    return values

rawDescription: Rpy2 and Pandas: join output from predict to pandas dataframe


code:
def actualite(request, id):
    articles = Article.objects.all()

    return render(request, 'blog/templates/home.html', {'articles': articles})

rawDescription: Django and foreign key

description: Django and foreign key


code:
def get_home_page(request):
    sortvalue = "asc" # Calculate what value you want, (asc or desc)
    return render_to_response('my_template.html',
                          { 'sortvalue' : sortvalue },
                          context_instance=RequestContext(request))

rawDescription: How is this code supposed to be indented?


code:
def summation(linf, prox, lsup):
    soma = 0

    while linf <= lsup:
        soma = soma + linf * (linf + 1) / 2
        linf = prox(linf)

    return soma

summation(1, lambda x: x + 1, 5)

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


rawDescription: smart way to read multiple variables from textfile in python

description: Smart way to read multiple variables from textfile in python


code:
class Node(QtGui.QGraphicsObject):
    customSignal = QtCore.pyqtSignal(str)
    ...

    @QtCore.pyqtSlot()
    def notifyaction(self):
        message = 'action1'
        self.customSignal.emit(message)

rawDescription: Emit signals from QgraphicsItem

description: Emit signals from QgraphicsItem


code:
l = [+3, +4, -7, -5]
result = [l[0]]
reduce(lambda x, y: result.append(x + y) or (x + y), l, 10)
result

rawDescription: Are there any analogues in the standard library?


code:
def FilterMirroredDuplicates(dataFrame, col1, col2):
    df = dataFrame[dataFrame[col1] > dataFrame[col2]]
    return df.select(lambda x: ((dataFrame[col2] == df[col1].loc[x]) & (dataFrame[col1] == df[col2].loc[x])).any())
filter = FilteredMirrorDuplicates(df, i1, i2)  #11 x 7 rows

rawDescription: Pandas: filtering for unique strings in 2 columns


code:
def get_dollar_format_text(dol_and_cent):
    '''Returns the dollar and cents part of a money amount as
    a two element list of integers, where the first element is
    dollars and the second is cents.
    '''
    return [int(x) for x in str(dol_and_cent).split('.')]

rawDescription: Beginner Python: Extract List to integer


code: id_df = grouped['ID'].apply(lambda x: pd.Series(x.values)).unstack()

rawDescription: Pandas groupby result into multiple columns


rawDescription: Cannot locate displayed data in source code when Scraping with Scrapy


code:
x_pos = text.xview()[0]
y_pos = text.yview()[0]

rawDescription: text widget returning cursor

description: Text widget returning cursor


code:
# wand/__init__.py
import api
import color
import compat
import display
import drawing
import exceptions
import font
import image
import resource
import sequence
import version

rawDescription: Wand + ImageMagick + Anaconda: "'wand' has no attribute 'image'"


code:
import hashlib

value1 = 'coconut'
value2 = 1.23

m = hashlib.sha1()
m.update(str([value1, value2]))
print(m.hexdigest())
# 1381ae81c8a5b660cca5b8d4607aa378320e25e8

rawDescription: Hash values with different data types together?


code:
class Category(models.Model):
    ...
    def last10items(self):
        return self.item_set.order_by('-created_date')[:10]

rawDescription: Optimized way of fetching parents with only latest child using django ORM


code: self.lblYouRolled["text"] = self.roll

rawDescription: Python Tk: Can't Retrieve Dice Roll Integer for Calculations


rawDescription: Comparing two strings in python?

description: Comparing two strings in python


rawDescription: Drawing polygons in numpy arrays

description: Drawing polygons in numpy arrays


code:
df.loc[testdate,:] = list(map(adddata.get, df.columns))
df.dtypes

rawDescription: replacing a pandas dataframe row overwrites all columns' dtypes

description: Replacing a pandas dataframe row overwrites all columns' dtypes


rawDescription: pandas plot dataframe barplot with colors by category

description: Pandas plot dataframe barplot with colors by category


code:
non_match = [i for i in new_syns if not any(any(w == s.split("|")[0]
                                                for w in i.split("|"))
                                            for s in syns)]

rawDescription: Check for Partial Match in 1 List With Partial Match Another List - Possible With List Comprehension?


code: self.grid = [[None] * (great_x+1)] * (great_y+1)

rawDescription: Python Iterate Through List of Lists of Objects and Call a Method


code: {{ macros.pagination_widget(pagination, '.yearresults', years=json_loads(years)) }}

rawDescription: Call a Python function from a Jinja template


code:
for bs in xrange(0,nboot):
   for mn in xrange(1,horizon+1):
        row = bootsam[mn-1,bs]-1
        if (mn % 12) == 1:
            bondbal = 24*balance
            sp500bal=34*balance
            russbal = 44*balance
            eafebal=55*balance
            cashbal =66*balance

            bondbal=bondbal*(1+float(filedata[row,2]))
            sp500bal=sp500bal*(1+float(filedata[row,3]))
            russbal=russbal*(1+float(filedata[row,4]))
            eafebal=eafebal*(1+float(filedata[row,5]))
            cashbal=cashbal*(1+float(filedata[row,6]))
            balance=bondbal + sp500bal + russbal + eafebal + cashbal
        else:
            bondbal=bondbal*(1+float(filedata[row,2]))
            sp500bal=sp500bal*(1+float(filedata[row,3]))
            russbal=russbal*(1+float(filedata[row,4]))
            eafebal=eafebal*(1+float(filedata[row,5]))
            cashbal=cashbal*(1+float(filedata[row,6]))

rawDescription: Python: how to optimize this code

description: Python: how to optimize this code


code:
numbers = '5 3 12 3 544 5 1 7 1'
alist = numbers.split()
alist

rawDescription: Need help removing duplicates numbers in Python exercise


code:
with open("input.csv", "r") as inp, open("output","w") as out:
    inpList = inp.read().split()
    out.write('\n'.join(el for el in inpList if ';cr;' in el))

rawDescription: Python sorting by mask

description: Python sorting by mask


code:
from django import forms
from .models import Fighter

class FighterSelectForm(forms.Form):
    def __init__(self, *args, **kwargs):
        choices = kwargs.pop("choices", [])
        super(FighterSelectForm, self).__init__(*args, **kwargs)
        self.fields["fighter_choices"] = forms.ChoiceField(
            widget=forms.RadioSelect,
            choices=choices)

rawDescription: What Form should I create to display these models?


rawDescription: pandas count true values in multi-index frame

description: Pandas count true values in multi-index frame


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

spf = wave.open('music.wav','r')

signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int8')
fs = spf.getframerate()

Time=np.linspace(0, len(signal)/fs, num=len(signal))

plt.figure(1)
plt.title('Signal Wave...')
plt.plot(Time,signal)
plt.show()

rawDescription: Python wav plot, the graph is not plotting


code: tagnames_map = {t['id']: t['name'] for t in tagnames}

rawDescription: Faster way to do a correspondence replace operation in python?


code: names = dir(self.__class__)

rawDescription: Python: How can I get a list of function names from within __getattr__ function?


code: request.session.get( 'type', '' ) #this would return 'f' || 's' || ''

rawDescription: How to handle two versions of the same site

description: Handle two versions of the same site


code: location = max(line.find(sub) for sub in ("FC", "FL"))

rawDescription: How to find the index of multiple sub string in a string by python?

description: Find the index of multiple sub string in a string by python


code: {'stock_name': 'Microsoft Corp', 'last_price': 25.690000000000001, 'stock_symbol': 'MSFT:NASDAQ'}

rawDescription: Download prices with python

description: Download prices with python


code:
r.hmset('rt.http://rottentomatoes.com/m/771354525/', {'Director': 'blasco ricardo', 'Platform': 'RT'})
r.hgetall('rt.http://rottentomatoes.com/m/771354525/')
r.hget('rt.http://rottentomatoes.com/m/771354525/', 'Director')

rawDescription: Save redis hash instead of string

description: Save redis hash instead of string


code:
tick = 0
while True:
    for enemy in enemylist:
        if enemy[0] == tick:
            DO_YOUR_CODE
    tick += 1
    #dont forget to add an exit to this loop

rawDescription: Adding parameters from a file into a list and then using the list


code:
def buttons(self):
    self.button1 = Button(self.main, text="Add User", command=x)

rawDescription: Tkinter: How to call a Button from another class method?


code:
z = [[i] for i in set(ss)] #make a list for each element in set
for i in range(len(z)): #use for-loop to print them out
    u = ''.join(z[i])
    u = u[:-9] #delete last 9 characters ([CHANGE] thing)
    print(u)

rawDescription: removing duplicates in python and selenium

description: Removing duplicates in python and selenium


rawDescription: How to do this pandas group by and count functionality?

description: Do this pandas group by and count functionality


code:
interactions = [[0 for x in xrange(3)] for x in xrange(3) ]
interactions[0] = 'TP53', 'BRCA2', 0.5
interactions[1] = 'AGT' , 'PCALM', 0.8
interactions[2] = 'BRCA1', 'BRCA2',0.2
interactions.sort(key=lambda i: i[2])
interactions

rawDescription: How to sort a python list?

description: Sort a python list


code:
from pyspark.sql.functions import udf
from pyspark.sql.types import IntegerType

day = udf(lambda date_time: date_time.day, IntegerType())
df.withColumn("day", day(df.date_time))

rawDescription: PySpark add a column to a DataFrame from a TimeStampType column


code:
lines = []
with open("Input.txt", "r") as f:
    lines = f.readlines()
with open("Input.txt", "w") as f:
    for line in lines:
        line = line.strip()
        f.write(line + "".join(line.split()[:2]) + "\n")

rawDescription: How to concatenate two strings and add the result to the end of a line in python

description: Concatenate two strings and add the result to the end of a line in python


code:
for n, i in enumerate(data1tm):
    c = [abs(i-j) for j in data2indx]
    mins = min(c)
    index = c.index(mins)
    data2sub.loc[n] = data2.iloc[index]

rawDescription: Return "Iterable" Numbers for Indices in Python Pandas


code:
@my_blueprint.route('/')
@autorender
def index():
    return {'name': 'John'} # or whatever your context is

rawDescription: Using flask/blueprint for some static pages


rawDescription: Mathemmatical formula for incremental breakdowns


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

# The x and y data to plot
y = np.array([1,2,17,20,16,3,5,4])
x = np.arange(len(y))

# Threshold above which the markers should be red
threshold = 15

# Create figure
plt.figure()

# Plot the line
plt.plot(x, y, color='blue')

# Add below threshold markers
below_threshold = y < threshold
plt.scatter(x[below_threshold], y[below_threshold], color='green')

# Add above threshold markers
above_threshold = np.logical_not(below_threshold)
plt.scatter(x[above_threshold], y[above_threshold], color='red')

rawDescription: Python: Is it possible to change line color in a plot if exceeds a specific range?


code:
df[['A', 'B']].values.ravel()
...
df[['A', 'B']].applymap(names.get)

rawDescription: Assign unique id to columns pandas data frame


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import matplotlib as mpl

fig = plt.figure()

display_axes = fig.add_axes([0.1,0.1,0.8,0.8], projection='polar')
display_axes._direction = 2*np.pi ## This is a nasty hack - using the hidden field to
                                  ## multiply the values such that 1 become 2*pi
                                  ## this field is supposed to take values 1 or -1 only!!

norm = mpl.colors.Normalize(0.0, 2*np.pi)

# Plot the colorbar onto the polar axis
# note - use orientation horizontal so that the gradient goes around
# the wheel rather than centre out
quant_steps = 2056
cb = mpl.colorbar.ColorbarBase(display_axes, cmap=cm.get_cmap('hsv',quant_steps),
                                   norm=norm,
                                   orientation='horizontal')

# aesthetics - get rid of border and axis labels
cb.outline.set_visible(False)
display_axes.set_axis_off()
plt.show() # Replace with plt.savefig if you want to save a file

rawDescription: Plot a (polar) color wheel based on a colormap using Python/Matplotlib


code: Product.objects.filter(colors=red).filter(colors=blue) # Red and blue being Color instances

rawDescription: Django filter filter with lists

description: Django filter filter with lists


rawDescription: How to convert pandas dataframe so that index is the unique set of values and data is the count of each value?

description: Convert pandas dataframe so that index is the unique set of values and data is the count of each value


code:
valid_List=["10.1.2.3","10.2.3.4","10.2.4.5","10.2.3.7"]
filename="abc.txt"

f = open(filename,"r")
lines = f.readlines()
f.close()

f = open(filename,"w")
for line in lines:
    flag = True
    deleted = ''
    for i in valid_List:
        if line == i+" "+ "ok"+"\n":
            flag = False
            deleted = i
            break
    if flag:
        #print("Writing ip not to be deleted")
        f.write(line)
    else:
        print(deleted," Deleted")
f.close()

rawDescription: Python delete line/lines from file without modifying existing contents


code:
s = ''
for line in anything:
   s += line

rawDescription: Speed vs security vs compatibility over methods to do string concatenation in Python


code:
data = np.fromfile('foo.bin', dtype='<i4')
data

rawDescription: Best way to convert Hex string file to integer

description: Convert Hex string file to integer


code:
t.pencolor('black')
t.fillcolor('blue')

rawDescription: different fill and border using turtle

description: Different fill and border using turtle


rawDescription: How to set the ticks on a logarithmic axis in matplotlib

description: Set the ticks on a logarithmic axis in matplotlib


code:
@property
def count(self):
    return self._count  # or return self.actual.count

@count.setter
def count(self, value):
    self._count = value  # or self.actual.count = value

rawDescription: How can I write a class that behaves exactly like another dynamically determined class? (Python)

description: Write a class that behaves exactly like another dynamically determined class? (Python)


code: content = request.session['content']

rawDescription: django - how to implement a 2-step publish mechanism

description: Django - how to implement a 2-step publish mechanism


rawDescription: Adding the resulting TFIDF calculation to the dataframe of the original documents in Pyspark


code:
import pycountry

lang = pycountry.languages.get(alpha2=two_letter_code)
three_letter_code = lang.terminology

rawDescription: How to convert IETF BCP 47 language identifier to ISO-639-2?

description: Convert IETF BCP 47 language identifier to ISO-639-2


code:
def query(data, wanted):
    result = {}
    for k, v in data.items():
        v2 = { k2:v[k2] for k2 in wanted if k2 in v }
        if v2:
            result[k] = v2
    return result

rawDescription: Filter a dict of dict

description: Filter a dict of dict


rawDescription: Confused by the enumerate() function in tutorials


code:
def bmi_risk(bmi, age):
    ''' function returning bmi's risk on human '''
    if bmi < 22 and age < 45:
        risk = "Low"
    elif bmi < 22 and age >= 45:
        risk = "Medium"
    elif bmi >= 22 and age < 45:
        risk = "Medium"
    elif bmi >= 22 and age >= 45:
        risk = "High"
    else:
        risk = "Unknown"
    return risk

rawDescription: Reducing the amount of return statements


code:
from gi.repository import Gdk
Gdk.threads_init()

rawDescription: 'gi.repository.Gtk' object has no attribute 'gdk'


code:
{'item': {'key': 'value',
          'key2': 'value2',
          'list': ['listValue1', 'listValue2', 'listValue3'],
          'list2': [{'key1': 'list2Key1Value',
                     'key2': 'list2Key2Value',
                     'key3': 'list2Key3Value'}],
          'list3': [{'key1': 'list3Key1Value',
                     'key2': 'list3Key2Value',
                     'key3': 'list3Key3Value'}]},
 'other': {'key': 'otherKeyValue'}}

rawDescription: Convert list to nested lists and dicts

description: Convert list to nested lists and dicts


code:
import mymodule

mymodule.set_trace()

rawDescription: Does importing a module (but not using it) decrease performance in Python?


code:
class CourseForm(Form):
    code = SelectField('Course Code', choices=CHOICES)
    number = IntegerField('Course Number')

rawDescription: Form with multiple identical lines

description: Form with multiple identical lines


code:
Record._get_collection().aggregate([
    # Match only those documents that would meet the condition
    { "$match": {
        "event_history": {
            "$elemMatch": {
                "$elemMatch": {"$in": [0] }
            }
        }
    }},

    # Unwind the event history array, top level
    { "$unwind": "$event_history" },

    # Make a copy of the inner array
    { "$project": {
        "account_id": 1,
        "event_history": 1,
        "status": 1,
        "copy": "$event_history"
    }},

    # Unwind that copy
    { "$unwind": "$copy" },

    # Group back the document keeping the "first" inner element only
    { "$group": {
        "_id": {
            "_id": "$_id",
            "account_id": "$account_id",
            "event_history": "$event_history",
            "status": "$status"
        },
        "copy": { "$first": "$copy" }
    }},

    # Match only where 0 to filter
    { "$match": { "copy": 0 } },

    # Group back to the original document
    { "$group": {
        "_id": "$_id._id",
        "account_id": { "$first": "$_id.account_id" },
        "event_history": { "$push": "$_id.event_history" },
        "status": { "$first": "$status" }
    }}
])

rawDescription: MongoDB / MongoEngine - Query for Item in List


code:
all_mentions = at_mentions.apply(pd.Series)
all_mentions

rawDescription: Split a Pandas 'findall' result list into multiple items, to group by uniques


code:
def convert_to_write(self, value, target=None, fnames=None):
    # remove/delete former records
    if target is None:
        set_ids = []
        result = [(6, 0, set_ids)]
        add_existing = lambda id: set_ids.append(id)
    else:
        tag = 2 if self.type == 'one2many' else 3
        result = [(tag, record.id) for record in target[self.name] - value]
        add_existing = lambda id: result.append((4, id))

    if fnames is None:
        # take all fields in cache, except the inverses of self
        fnames = set(value._fields) - set(MAGIC_COLUMNS)
        for invf in self.inverse_fields:
            fnames.discard(invf.name)

    # add new and existing records
    for record in value:
        if not record.id or record._dirty:
            values = dict((k, v) for k, v in record._cache.iteritems() if k in fnames)
            tempVal = {}
            for n in values:
                f = record._fields[n] #get field def
                if f.type == 'one2many':
                    subrec = record[n]
                    subfields = subrec._fields
                    tempVal[n] = f.convert_to_write(subrec,record)
                else:
                    val = {}
                    val[n] = values.get(n)
                    tempVal[n] = record._convert_to_write(val)[n]

            if tempVal:
                values = tempVal

            #add to result
            if not record.id:
                    result.append((0, 0, values))
            else:
                result.append((1, record.id, values))
        else:
            add_existing(record.id)

    return result

rawDescription: How to browse or search One2many field in Odoo?

description: Browse or search One2many field in Odoo


code:
n = 50
X_, Y_ = np.meshgrid(np.linspace(-1,1,n), np.linspace(-1,1,n))
X_ = (3*X_**3 + X_) / 4
Y_ = (3*Y_**3 + Y_) / 4

x = np.dstack((X,Y)).reshape((100*100, 2))
xi = np.dstack((X_,Y_)).reshape((n*n, 2))
A_ = griddata(x, A.flat, xi, method='cubic')

rawDescription: Nonuniform sampling for 2D image in Python


code:
def check_pause(self):
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p:
                self.pause = not self.pause

rawDescription: Python: interrupt execution with key and run again


rawDescription: List comprehension to return the sum of n/2...?


code:
df = df.set_index(["resp", "vehicle", "color"])

grouped = df.groupby(lambda x: x[0].lower(), axis=1)

new_grouped = []
for key, group in grouped:
    group.columns = ["sl_val"] + ["BL_val{}".format(i) for i in range(1,4)]
    group["sl"] = key
    new_grouped.append(group)

df2 = pd.concat(new_grouped).reset_index()

df2 = df2.sort(["resp", "vehicle", "color"]).set_index("resp")
df2 = df2[["vehicle", "color", "sl"] + [k for k in df2.columns if "_" in k]]

rawDescription: Pandas stack/groupby to make a new dataframe


code:
from pydataset import data

titanic = data('titanic')

rawDescription: Are there any example data sets for Python?


code:
def get_col(col):
    if col:
        return col
    else:
        return 'null'

rawDescription: Read array string of variable length in Python


rawDescription: Python 2.7+: What's the correct way to format a float in non-scientific notation with certain precision?


rawDescription: Accessing descriptor instance

description: Accessing descriptor instance


code:
import re
import sys

pattern = re.compile(r"(is OK)|(file could not be opened)|(is a broken)|(is a block)")

with open(sys.argv[1]) as handle:
    for line in handle:
        if not pattern.search(line):
            sys.stdout.write(line)

rawDescription: Inverse Match Help in Python

description: Inverse Match Help in Python


rawDescription: Pandas drops timestamp columns in resample


code:
# Create an empty FeatureClass from the original.
with arcpy.UpdateCursor(your_feature_class) as rows:
    for row in rows:
        if row.valence <= 2:
            rows.deleteRow(row)

rawDescription: Python: How to remove values from a list that have a valence lower than a certain value


code:
in_radius
radius_utf

rawDescription: Could I use python to retrieve a number of zip code within a radius


code: unpacker = struct.Struct('>xh').unpack

rawDescription: Translating Array Manipulation in C++ to Python


code:
import csv
import sys

myDict = {}
csvreader = csv.reader(sys.stdin, delimiter=',')

rawDescription: Read inputfile as csv in python

description: Read inputfile as csv in python


code:
def exclude_function(filename):
    if filename.startswith('a'):
        return True
    else:
        return False

mytarfile.add(..., exclude=exclude_function)

rawDescription: Python tarfile and excludes

description: Python tarfile and excludes


code:
from threading import local

_thread_locals = local()
def get_current_user():
    return getattr(getattr(_thread_locals, 'user', None),'id',None)

class ThreadLocals(object):
    """Middleware that gets various objects from the
    request object and saves them in thread local storage."""
    def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)

rawDescription: Model limit_choices_to={'user': user}

description: Model limit_choices_to={'user': user}


code:
from tkinter import *

# --- functions ---

def change_On_Off_state(*args):
    CheckVar1.set(*args)
    #CheckVar1.trace_variable("w", On_Off_state)

def change_on_button_press():
    if CheckVar1.get() == 1:
        CheckVar1.set(0)
    else:
        CheckVar1.set(1)

# --- main ----

root = Tk()

# create only once
CheckVar1 = IntVar() # global

# create only once
OnOff = Checkbutton(root, text="On", variable=CheckVar1, onvalue=1, offvalue=0)
OnOff.grid()

# use many times
change_On_Off_state(1)

# use button to on/off checkbutton
btn = Button(root, text="On / Off", command=change_on_button_press)
btn.grid()

# "start the engine"
root.mainloop()

rawDescription: Checkbutton value constant

description: Checkbutton value constant


rawDescription: from elements in a line to key and values

description: From elements in a line to key and values


code:
types = [int, int, int, str]
[type(value) for type, value in zip(types, values)]

rawDescription: How to convert string input into tuple with integers and a string

description: Convert string input into tuple with integers and a string


code:
lookup = {}
for line in file:
    # do steps above so you have myid, token
    lookup[myid] = token

rawDescription: Is there way to find the pharse and capture next token value


code:
self.canvas.focus_set()
self.canvas.bind("<1>", lambda event: self.canvas.focus_set())

rawDescription: Tkinter: How to scroll an entire canvas using arrow keys?


rawDescription: What's a better way to handle this in Python


rawDescription: python xml query get parent

description: Python xml query get parent


code: np.mean(D_values, axis=0)

rawDescription: Average of nth element of each list in a dictionary


code:
def read_directory_changes(handle, recursive):
    rqIndexLck.acquire()
    rq = ReadDirectoryRequest(handle, recursive)
    set4handle = None
    if handle in rqIndex:
        set4handle = rqIndex[handle]
    else:
        set4handle = set()
        rqIndex[handle] = set4handle
    set4handle.add(rq)
    rqIndexLck.release()
    ret = rq.read_changes()
    rqIndexLck.acquire()
    if rq in set4handle:
        set4handle.remove(rq)
    rqIndexLck.release()
    return ret

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


rawDescription: Python sort list by algorithm

description: Python sort list by algorithm


code:
df_merged = pd.merge(df_A,df_B,how='inner',on=['times'],suffixes=['','_B'])
df_merged

rawDescription: Pandas Merging/Join Dataframes

description: Pandas Merging/Join Dataframes


code:
import numpy as np
import xray

# This was logic from the OP
NUM_LATS = 180.0
NUM_LONS = 360.0

ascii_data = np.loadtxt('tmp.txt', delimiter=' ')

fl_res = NUM_LATS / ascii_data.shape[0]

if fl_res != NUM_LONS / ascii_data.shape[1]:
    raise ValueError('Incorrect dimensions in ascii file')

lon = np.arange(0.5, 360.5, fl_res)
lat = np.arange(-90.5, 89.5, fl_res)

# Create an empty Dataset
ds = xray.Dataset()
# Add coordinate variables
ds['lon'] = ('lon', lon)
ds['lat'] = ('lat', lat)
# Add data (coordinates are automatically mapped)
ds['ascii_data'] = (('lat', 'lon'), ascii_data)

# Write to a netcdf
ds.to_netcdf('tmp.nc')

rawDescription: Xray not able to load ascii data into netcdf file


rawDescription: Class (not instance) constructor

description: Class (not instance) constructor


code:
n_values = 2
value_vars = ["a{}_P".format(i+1) for i in range(0, n_values)]
pd.melt(df, id_vars=['weight'], value_vars=value_vars, value_name='P').sort('P')

rawDescription: Merge multiple DataFrame columns into one


code:
r = requests.post(OAuthURL)
r.cookies
r.cookies['csrftoken']
'b2b621c198642e26a19fc9bf1b38d246' in r.content
token_pattern.search(r.content).group(1)

rawDescription: Parse request response for key, value pairs


code:
Z=linkage(X, 'single', 'correlation')
dendrogram(Z, color_threshold=0)

rawDescription: hierarchical clustering on correlations in Python scipy/numpy?

description: Hierarchical clustering on correlations in Python scipy/numpy


code:
def is_float(data):
    try:
        float(data)
        return True
    except ValueError:
        return False

rawDescription: Distinguish between 'character' and 'numeric' data types in Python


code: df['MainProvence'] = df.apply(lambda row: (row['Provence'] if row['LocFilter'] == 1 else row['State']), axis=1)

rawDescription: Find count of unique column elements after using groupby with pandas


code:
import module_name

module_name.variable_to_use = 'some value to be used'

rawDescription: Passing a string to module "once"

description: Passing a string to module "once"


code: deleted_index_array = [i for i, x in enumerate(array) if x == 0]

rawDescription: Remove elements from a int array that have value 0 and save the deleted index


code:
from pprint import pprint
from bs4 import BeautifulSoup

text = """your html goes here"""

def find_li(element):
    return [{li.a['href']: find_li(li)}
            for ul in element('ul', recursive=False)
            for li in ul('li', recursive=False)]

soup = BeautifulSoup(text, 'html.parser')
data = find_li(soup)
pprint(data)

rawDescription: Converting HTML list to nested Python list


code:
308090 ['complex']
310698 ['complex']
311984 ['compartment2']
500038 ['compartment2']
500072 ['complex']
305667 ['compartment 1', 'compartment2']
500012 ['compartment 1', 'compartment2']
500010 ['compartment2']
500002 ['compartment 1', 'compartment2']

rawDescription: print corresponding key of dictionary for each element in a set

description: Print corresponding key of dictionary for each element in a set


code:
chars = []
with open(filename, 'rU') as fd:
    map(chars.extend, fd)

rawDescription: Break string into list of characters in Python