code:
from pyramid.renderers import render

@view_config(..., renderer="new_model.mako")
def new_model(self):
    raw_form_html = render('new_model_form.mako', request, {...})
    form_html = htmlfill(raw_form_html, ...)
    return {
        'form_html': form_html,
    }

rawDescription: Using HTMLFill with Pyramid's @view_config


rawDescription: how to enter in to a folder through python code on linux

description: Enter in to a folder through python code on linux


code:
def author_name(lines):
    '''Finds the authors name within the docstring'''
    for line in lines:
        name = 'Unknown'
        if line.startswith("Author"):
            line = line.strip('\n')
            line = line.strip('\'')
            author_line = line.split(': ')
            if len(author_line[1]) >=4:
                name = author_line[1]
            break  # ends the `for` loop, we found an author.

    return "{0:21}{1}".format("Author", name)

rawDescription: Find author of python file from docstring


code:
product = Product.get_by_id(p_id, use_memcache=True)
...
product.put(use_memcache=True)

rawDescription: ndb Models are not saved in memcache when using MapReduce

description: Ndb Models are not saved in memcache when using MapReduce


code:
def itertime(start, end, int_step):
    current_time = start
    step = datetime.timedelta(0, int_step)
    while current_time < end:
        yield current_time
        current_time += step

rawDescription: Python datetime

description: Python datetime


code: from mypackage.constants import *

rawDescription: Python Superglobal?

description: Python Superglobal


code:
def count_matching(condition, seq):
    """Returns the amount of items in seq that return true from condition"""
    return sum(1 for item in seq if condition(item))

count_matching(meets_condition, my_list)

rawDescription: What is a good way to do countif in Python


code:
df.loc["two"]
type(_)
df.loc[["two"]]
type(_)

rawDescription: how to preserve pandas dataframe identity when extracting a single row

description: Preserve pandas dataframe identity when extracting a single row


code:
import pandas as pd
import numpy as np
np.random.seed(1)

# make an example df
index = pd.date_range(start='2010-01-20 5:00', end='2010-05-20 17:00', freq='2T')
N = len(index)
df = pd.DataFrame({'val': np.random.random(N)}, index=index)
mask = np.random.randint(2, size=N).astype(bool)
df = df.loc[mask]

# expand the time series, filling in missing values with NaN
df = df.asfreq('2T', method=None)

# now we can use the constant-frequency solution
window_size = pd.Timedelta('8D')/pd.Timedelta('2min')
df['std'] = pd.rolling_std(df['val'], window=window_size, min_periods=1)

result = df['std'].resample('D', how='mean')
print(result.head())

rawDescription: Python: look back n days rolling standard deviation


code: (self.list[L][0] == operand.list[R][0]) and (op == mul or op == pow or op == add or op == sub or (op == div and operand.list[R][1] != 0))

rawDescription: How to do this conditional statement?

description: Do this conditional statement


code:
lock = RLock()

def thread_A():
    lock.acquire()
    try:
        if "foo" not in global_dict:
            global_dict["foo"] = 1
    finally:
        lock.release()

def thread_B():
    lock.acquire()
    try:
        global_dict["foo"] = 2
    finally:
        lock.release()

rawDescription: Using a global dictionary with threads in Python


code:
def resolve_virtual_environment(override=None):
    """Fetch the virtual environment path in the
       process' environment or use an override."""
    path = os.getenv('VIRTUAL_ENV')
    if override:
        path = os.path.join(os.getcwd(), override)
    return path

def activate_virtual_environment(environment_root):
    """Configures the virtual environment starting at ``environment_root``."""
    activate_script = os.path.join(
        environment_root, 'Scripts', 'activate_this.py')
    execfile(activate_script, {'__file__': activate_script})

rawDescription: Virtual environments and embedding Python


code:
[['2010',
  'NON-HISPANIC BLACK',
  'MALE',
  'HUMAN IMMUNODEFICIENCY VIRUS DISEASE',
  '297',
  '5'],
 ['2012',
  'NON-HISPANIC BLACK',
  'MALE',
  'INFLUENZA AND PNEUMONIA',
  '2011',
  '3']]

rawDescription: How to exclude some indexes in a python loop?

description: Exclude some indexes in a python loop


code:
def original():pass
classmethod(original).__func__ == original
staticmethod(original).__func__ == original
property(original).fget == original

rawDescription: How to retrieve original @classmethod, @staticmethod or @property

description: Retrieve original @classmethod, @staticmethod or @property


code:
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
from lasagne import layers
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
from lasagne import nonlinearities

class PlotLosses(object):
    def __init__(self, figsize=(8,6)):
        plt.plot([], [])

    def __call__(self, nn, train_history):
        train_loss = np.array([i["train_loss"] for i in nn.train_history_])
        valid_loss = np.array([i["valid_loss"] for i in nn.train_history_])

        plt.gca().cla()
        plt.plot(train_loss, label="train")
        plt.plot(valid_loss, label="test")

        plt.legend()
        plt.draw()

rawDescription: Live plot losses while training neural net in Theano/lasagne


code:
import argparse

class Arg(object):
    def __init__(self, value):
        self.value = value
        if '=' in value:
            self.value = value.split('=', 1)

    def __str__(self):
        return '{}=<{}>'.format(self.value[0], self.value[1]) if isinstance(self.value, list) else self.value

    def __repr__(self):
        if isinstance(self.value, list):
            return repr('{}=<value>'.format(self.value[0]))
        return '{}'.format(repr(self.value))

    def __eq__(self, value):
        return '{}'.format(repr(value)) == repr(self)

parser = argparse.ArgumentParser()
parser.add_argument('--param', default='ch1', choices=('ch1', 'ch2', 'ch3', 'ch4=<value>'), type=Arg)

args = parser.parse_args('--param ch4=123'.split())
print('choice {}, value {}'.format(args.param, repr(args.param.value)))

args = parser.parse_args([])
print('choice {}, value {}'.format(args.param, repr(args.param.value)))

args = parser.parse_args('--param ch3'.split())
print('choice {}, value {}'.format(args.param, repr(args.param.value)))

rawDescription: Argparse argument with an additional value


code:
pattern = re.compile("^\d{1,4}$")
pattern.match("0").group()
pattern.match("42").group()
pattern.match("777").group()
pattern.match("2012").group()
pattern.match("65535").group()

rawDescription: Regex to match a range number of digits from a string representin an integer number?


code:
import re
term = 'patient'
pattern = '^({})(s?)({}?)$'.format(re.escape(term),"?".join("merge"))
print(pattern)
if re.match(pattern, 'patientmer'):
    print('found')

rawDescription: regex: better way to match unknown number of letters in word

description: Regex: better way to match unknown number of letters in word


rawDescription: .csv data into a dictionary in Python: Duplicate values


code:
from itertools import groupby
from operator import itemgetter
[[k] + [';'.join(v) for v in zip(*g)[1:]] for k,g in groupby(a, itemgetter(0))]

rawDescription: Flatten list of lists vertically in Python


code: {{ htm_map|safe }}

rawDescription: Django Javascript Output

description: Django Javascript Output


code:
from itertools import cycle
input1 = 'hello'
input2 = "goodbye"
for x, y in zip(cycle(input1), input2):
    total = ord(x) + ord(y)
    print('{!r} + {!r} = {:3d} + {:3d} = {:3d}'.format(x, y, ord(x), ord(y), total))

rawDescription: Adding 2 ascii converted characters using nested loops in Python 3.2


code:
from itertools import product, starmap
list(starmap(dis.jaccrd, product(list_11, list_21)))

rawDescription: Problems computing the score of a pairwise list in an iterative way?


code:
def run_st(self):
    global i
    i = (i+1)%4
    self.timer.Restart(1000)
    if not hasattr(self,"sT"):
        self.sT = wx.StaticText(self.widgetPanel, -1, '1', size=(20,20))
        self.sT.SetBackgroundColour('grey')
    self.sT.SetPosition(pos_st[i])

rawDescription: wxPython moving widgets

description: WxPython moving widgets


code: lambda done: self.functionB(done, valueA)

rawDescription: How can I pass to a slot more than the arguments the signal sends in pyqt4?

description: Pass to a slot more than the arguments the signal sends in pyqt4


code:
def necessaryImportFor(name):
    packageNames = []

    def nameHandler(name):
        packageNames.append(name)

    from pkgutil import walk_packages
    for package in walk_packages(onerror=nameHandler):
        nameHandler(package[1])
    # Suggestion: Sort package names by count of '.', so shallower packages are searched first.
    for package in packageNames:
        # Suggestion: just skip any package that starts with 'test.'
        try:
            if name in listImportablesForName(package):
                return package
        except ImportError:
            pass
        except PathToSourceFileException:
            pass
    return None

rawDescription: Check Contents of Python Package without Running it?


code:
s = """This is a string with a %(variable)s to fill in.
Here's a %(second)s one
""" % {"variable": "field", "second": "'nother"}

rawDescription: Are there any equivalent for groovy """ in python?


rawDescription: Python 3: Print multiple lines to one line


code:
def foo(seq):
    from operator import itemgetter
    # | [['UserID', 'Amount', 'Email', {'week1': 1, 'week2': 10, 'week4': 14}], .|
    # V                                                                          V
    seq_dict = (grp[0][:3] + [dict(map(itemgetter(3,4), grp))] for grp in lst)
    # 'week4' | '4' | 4
    max_weeks = int(max(seq[0][-1])[4:])
    # | ['week1', 'week2', 'week3', 'week4'] |
    # V                                      V
    week_range = range(1, max_weeks + 1)
    return [items[:-1] + [items[-1].get("week{}".format(week), 0)
                          for week in week_range]
            for items in seq_dict]

rawDescription: How to combine/merge mostly identical sublists into one, and append the non-identical part to the end of the list?

description: Combine/merge mostly identical sublists into one, and append the non-identical part to the end of the list


rawDescription: Converting a number string into MD5 with python


code:
import numpy as np

def whiten(X,fudge=1E-18):

   # the matrix X should be observations-by-components

   # get the covariance matrix
   Xcov = np.dot(X.T,X)

   # eigenvalue decomposition of the covariance matrix
   d, V = np.linalg.eigh(Xcov)

   # a fudge factor can be used so that eigenvectors associated with
   # small eigenvalues do not get overamplified.
   D = np.diag(1. / np.sqrt(d+fudge))

   # whitening matrix
   W = np.dot(np.dot(V, D), V.T)

   # multiply by the whitening matrix
   X_white = np.dot(X, W)

   return X_white, W

rawDescription: How to whiten matrix in PCA

description: Whiten matrix in PCA


code:
count_dict = {}
for item in my_list:
    count_dict.setdefault(item, 0)
    count_dict[item] += 1

rawDescription: Without using Counter(), how to find most common element in a list?


code:
nums = [1,4,6,10]
[x-y for x,y in zip(nums[1:],nums)]
delta=[x-y for x,y in zip(nums[1:],nums)]
float(sum(delta))/len(delta)

rawDescription: Clunky calculation of differences between an incrementing set of numbers, is there a more beautiful way?


code:
import subprocess
proc = subprocess.Popen(['ssh', 'user@host', 'cat > %s' % filename],
                        stdin=subprocess.PIPE)
proc.communicate(file_contents)
if proc.retcode != 0:
    ...

rawDescription: SSH Connection with Python 3.0

description: SSH Connection with Python 3.0


code:
from itertools import combinations

words = ['DUMMY', 'EARTH']
letters = ['A', 'D', 'E', 'H', 'M', 'M', 'R', 'T', 'U', 'Y']

[w for w in (''.join(c) for c in combinations(words,2))
                               if sorted(w) == letters]
# ['DUMMYEARTH']

rawDescription: Python code that will find 2 words concatenated made out of specific letters. Letters must be used once only


code:
processList = [subprocess.Popen for i in range(1)]
processList

rawDescription: Use poll() on new subprocess.Popen object list


code:
import math
(2 - 2*4/float(24)) / math.sqrt(2 + 1e-20)

rawDescription: What is the total bigram count returned for NLTK BigramCollocationFinder?


code: [diff(x) for x in itertools.combinations(range(4), 3)]

rawDescription: Python list of combinations of positions


rawDescription: How to identify all identical lists from a list of lists?

description: Identify all identical lists from a list of lists


code: id = line.split(' ')[-1]

rawDescription: how to extract information in txt file using python

description: Extract information in txt file using python


code:
xData = np.load('xData.npy')*10**5
yData = np.load('yData.npy')*10**5

rawDescription: Why does scipy.optimize.curve_fit not fit to the data?


rawDescription: Numpy extract arbitrary subarray along one axis


code: i = int.from_bytes(b, byteorder='big', signed=False)

rawDescription: How to XOR literal with a string

description: XOR literal with a string


code:
from datetime import datetime
sdate = datetime(2015, 10, 1)
df
df['Date'] = pd.to_timedelta(df['Date'],unit='d') + sdate
df

rawDescription: Transforming a Date Column with Pandas

description: Transforming a Date Column with Pandas


code:
class Question:
  def __init__(self, question = '', choices = [], correct = None, answer = None):
    self.question = question
    self.choices = choices
    self.correct = correct

  def answer(self, answer):
    self.answer = answer

  def grade(self):
    return self.answer == self.correct

class Test:
  def __init__(self, questions):
    self.questions = questions

  def result(self):
    return sum([question.grade() for question in self.questions])

  def total(self):
    return len(self.questions)

  def percentage(self):
    return 100.0 * float(self.result()) / float(self.total())

rawDescription: Assign variables to random elements from list? Python


rawDescription: How can I delete the dictionary of global variables?

description: Delete the dictionary of global variables


code:
for f in files:
    test = pd.read_csv( f, nrows=1 )
    if len( test.columns ) == 4:
        df = df.append( pd.read_csv( f ) )

rawDescription: Unit Test with Pandas Dataframe to read *.csv files


code:
result = ('CN=SERVER1,OU=General Servers,OU=Servers,OU=Computers,OU=Group,DC=Domain,DC=com', {})
result[0].split(",")[0].split("=")[1]

rawDescription: Python - How do you remove characters recieved as a list from an ldap query?


code:
def func3(xy, s):
    size = xy.shape[0]-2*s
    p1 = xy[0:size]
    p2 = xy[s:size+s]
    p3 = p2
    p4 = xy[2*s:size+2*s]
    return np.einsum('ij,ij->i', p1-p2, p4-p3)

rawDescription: How to vectorize the dot product between segments of a trajectory

description: Vectorize the dot product between segments of a trajectory


code:
values = iter(od.values())
_ = next(values,None)  #scrap the first one
for value in values:
    pass #Do something with the next values.

rawDescription: Python - Looping Over Specific Variables in a Dictionary


code:
parser.add_argument('otherthings', nargs='*')
parser.parse_args(['foo', 'bar', 'baz'])

rawDescription: Getting the remaining arguments in argparse


rawDescription: why this regular expression returns empty

description: Why this regular expression returns empty


code:
import xml.sax.xmlreader
import xml.sax.saxutils

def testJunk(file, e2content):
  attr0 = xml.sax.xmlreader.AttributesImpl({})
  x =  xml.sax.saxutils.XMLGenerator(file)
  x.startDocument()
  x.startElement("document", attr0)

  x.startElement("element1", attr0)
  x.characters("bingo")
  x.endElement("element1")

  x.startElement("element2", attr0)
  x.characters(e2content)
  x.endElement("element2")

  x.endElement("document")
  x.endDocument()

rawDescription: simple output of xml from python

description: Simple output of xml from python


code:
GroupManage.base_fields['group'] = forms.CharField(max_length=81,
error_messages={'does_not_exist':
"This group does not exist!"}, widget=ChoiceWidget(True))

rawDescription: Override a Django form field from a different app


rawDescription: How to gracefully stop python unittest?

description: Gracefully stop python unittest


code:
def Counter(x):
    lst = list(x)
    d = [0] * (max(lst)+1)
    for v in lst: d[v]+=1
    return d

rawDescription: Python list sort by size of group

description: Python list sort by size of group


code:
from datetime import datetime

for line in lines:
    p = line.split()
    xv.append(datetime.strptime(p[0], '%H:%M:%S'))

fig, ax = plt.subplots()
ax.plot_date(xv, yv)

rawDescription: Plot Time values with matplotlib

description: Plot Time values with matplotlib


code:
from urllib import urlencode
from urlparse import urlparse, urlunparse, parse_qs

class DuplicatesPipeline(object):
    def __init__(self):
        self.ids_seen = set()

    def process_item(self, item, spider):
        url = item['url']
        u = urlparse(url)
        query = parse_qs(u.query)
        query.pop('video', None)
        u = u._replace(query=urlencode(query, True))
        unique_id = urlunparse(u)
        if unique_id and unique_id in self.ids_seen:
            raise DropItem("Duplicate Item found (%s)" % unique_id)
        else:
            self.ids_seen.add(unique_id)
        return item

rawDescription: DropItem if parsed url contains key words (pipeline)


code:
def outer(x):
    x = [x]
    def inner_reads():
        # Will return outer's x's first (and only) element.
        return x[0]
    def inner_writes(y):
        # Will look up outer's x, then mutate it.
        x[0] = y
    def inner_error(y):
        # Will now work, because 'x' is not assigned to, just referenced.
        tmp = x[0]
        x[0] = y
        return tmp
    return inner_reads, inner_writes, inner_error

inner_reads, inner_writes, inner_error = outer(5)
inner_reads()
inner_writes(10)
inner_reads()
inner_error(15)
inner_reads()

rawDescription: What limitations have closures in Python compared to language X closures?


code: self.queue.put((src, dst, action, callback, error_callback))

rawDescription: Python Fileconveyor Naming Issues

description: Python Fileconveyor Naming Issues


code:
from abc import *
class C:
    __metaclass__ = ABCMeta
    @abstractmethod
    def abstract_method(self): pass
    @abstractproperty
    def abstract_property(self): return 'foo'

C.__abstractmethods__

rawDescription: Actual difference in implementing/overriding using @abstractproperty and @abstractmethod


code:
class CourseListView(AuthView):
    def get(self, request, format=None):
        """
        Returns a JSON response with a listing of course objects
        """
        courses = Course.objects.order_by('name').all()
        serializer = PaginatedCourseSerializer(courses, request, 25)
        return Response(serializer.data)

rawDescription: Django Rest Framework 3.1 breaks pagination.PaginationSerializer


code:
temp = []
for i in range(len(rows) - 2, -1, -1):
    for j in range(i + 1):
        temp.append((i, j))
for (i, j) in temp:
    rows[i][j] += max([rows[i + 1][j], rows[i + 1][j + 1]])

rawDescription: Strange For Loop

description: Strange For Loop


code:
import random

def rnd_to_sum_with_min(desired_sum=356, numbers=3, minimum=31):
    selection = []
    for i in range(numbers-1):
        upper_limit = desired_sum - sum(selection) - (numbers - i) * minimum
        choice = random.randint(minimum, upper_limit)
        selection.append(choice)
    selection.append(desired_sum - sum(selection))
    return selection

rawDescription: randomly select 3 numbers whose sum is 356 and each of these 3 is more than 30

description: Randomly select 3 numbers whose sum is 356 and each of these 3 is more than 30


code:
company_ids = ['2', '24', '1', '7', '373']
order_expressions = [(Company.id==i).desc() for i in company_ids]
query = Company.query.filter(Company.id.in_(company_ids)).order_by(*order_expressions)
following_companies_list_data = query.paginate(page, per_page=10, error_out=False)

rawDescription: Keep the order of list in sql pagination


code:
# exemple data
A = np.random.rand(2, 3, 4, 5)
axis = 2
n = A.ndim
# building n-dimensional slice
s = [slice(None), ] * n
s[axis] = slice(0, n - 1)
B = A[s]
s[axis] = slice(1, n)
C = A[s]

rawDescription: Slices along arbitrary axis

description: Slices along arbitrary axis


code:
df["enddt"] += timedelta(days=1)
df = pd.melt(df, id_vars=["cid", "jid"], var_name="change", value_name="date")
df["change"] = df["change"].replace({"stdt": 1, "enddt": -1})
df = df.sort(["cid", "date"])

df = df.groupby(["cid", "date"],as_index=False)["change"].sum()
df["count"] = df.groupby("cid")["change"].cumsum()

new_time = pd.date_range(df.date.min(), df.date.max())

df_parts = []
for cid, group in df.groupby("cid"):
    full_count = group[["date", "count"]].set_index("date")
    full_count = full_count.reindex(new_time)
    full_count = full_count.ffill().fillna(0)
    full_count["cid"] = cid
    df_parts.append(full_count)

df_new = pd.concat(df_parts)

rawDescription: Count Number of Rows Between Two Dates BY ID in a Pandas GroupBy Dataframe


rawDescription: How to list all directories that do not contain a file type?

description: List all directories that do not contain a file type


code:
def length(l):
    if hasattr(l, '__len__'):
        return len(l)
    else:
        i = 0
        for _ in l:
            i += 1
        return i

l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
answer = []
for key, iter in itertools.groupby(l):
    answer.append((key, length(iter)))

# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]

rawDescription: Python: determine length of sequence of equal items in list


code: subprocess.check_output("ls -lR")

rawDescription: Files and directories in Python on linux


code: a.mean(axis=(1, 3)).ravel()

rawDescription: Elements Arrangement For Calculating Mean In Python/NumPy


code:
lines = 3
columns = 4
board = [[(0,0)]*lines]*columns
map(id, board)

rawDescription: Change values of a list of list (of tuples) in a for statement


code:
c = np.random.randn(100)
c.sort()
pylab.plot( np.arange(1,len(c)+1)/len(c), c, '-', drawstyle='steps' )

rawDescription: Numpy/matplot: How to plot First X% is in range Y%?


code:
def dosomething():
    try:
        self.canvas.get_tk_widget().destroy()
    except:
        pass
    fig = Figure(figsize=(12, 4))
    axes = fig.add_subplot(111)
    self.canvas = FigureCanvasTkAgg(fig, master=windows)
    self.canvas.get_tk_widget().pack()
    data=np.arange(100)  # not sure what this is for

def dosomethingelse():
    try:
        self.canvas.get_tk_widget().destroy()
    except:
        pass
    fig = Figure(figsize=(12, 4))
    fig.plot(np.arange(100)+10*(np.random.rand(100)-0.5),'-r')
    self.canvas = FigureCanvasTkAgg(fig, master=windows)
    self.canvas.get_tk_widget().pack()

rawDescription: How to replace previous plots in a matplotlib figure with new plots or grid of plots?

description: Replace previous plots in a matplotlib figure with new plots or grid of plots


code:
import pandas as pd

time_vec =     [datetime.datetime(2013,9,26,17,0,0)
               ,datetime.datetime(2013,9,26,17,5,0)
               ,datetime.datetime(2013,9,26,17,8,41)
               ,datetime.datetime(2013,9,26,17,38,43)
               ,datetime.datetime(2013,9,26,17,49,55)
               ,datetime.datetime(2013,9,26,17,49,57)]
df = pd.DataFrame([1,1,1,1,0,1],index = time_vec,columns=['value'])

df['count_change']=0
df.ix[df.value!=df.value.shift(1),'count_change']=1
df.ix[0,'count_change']=0

df.resample('15min',how={'value': 'last', 'count_change': 'sum'},fill_method='ffill',label='right')

rawDescription: Counting change of value in irregular time series data


code:
x = np.array([0, 1], dtype=np.bool_)
x[:,None] - x[None,:]
x[:,None] * x[None,:]

rawDescription: Test if matrix is invertible over finite field


code: from multiprocessing.dummy import Pool # use threads

rawDescription: Python multiprocessing edit-distance calculation


code:
import sys
sys.float_info

rawDescription: What is the smallest number which can be represented in python?


code:
class Note(object):
    def __init__(self, name, size):
        self.name = name
        self.size = size

class Notebook(object):
    def __new__(cls, *notes):
        notebook = object.__new__(cls)
        for note in notes:
            setattr(notebook.__class__, note.name, note.size)
        return notebook

rawDescription: Adding properties dynamically using functions created dynamically


code:
import operator

MAKE_BINARY  = lambda opfn : lambda self,other : BinaryOp(self, asMagicNumber(other), opfn)
MAKE_RBINARY = lambda opfn : lambda self,other : BinaryOp(asMagicNumber(other), self, opfn)

class MagicNumber(object):
    __add__  = MAKE_BINARY(operator.add)
    __sub__  = MAKE_BINARY(operator.sub)
    __mul__  = MAKE_BINARY(operator.mul)
    __div__  = MAKE_BINARY(operator.div)
    __radd__ = MAKE_RBINARY(operator.add)
    __rsub__ = MAKE_RBINARY(operator.sub)
    __rmul__ = MAKE_RBINARY(operator.mul)
    __rdiv__ = MAKE_RBINARY(operator.div)

    def __neg__(self, other):
        return UnaryOp(self, lambda x : -x)

    @property
    def value(self):
        return self.eval()

class Constant(MagicNumber):
    def __init__(self, value):
        self.value_ = value

    def eval(self):
        return self.value_

class Parameter(Constant):
    def __init__(self):
        super(Parameter, self).__init__(0.0)

    def setValue(self, v):
        self.value_ = v

    value = property(fset=setValue, fget=lambda self: self.value_)

class BinaryOp(MagicNumber):
    def __init__(self, op1, op2, operation):
        self.op1 = op1
        self.op2 = op2
        self.opn = operation

    def eval(self):
        return self.opn(self.op1.eval(), self.op2.eval())

class UnaryOp(MagicNumber):
    def __init__(self, op1, operation):
        self.op1 = op1
        self.operation = operation

    def eval(self):
        return self.opn(self.op1.eval())

asMagicNumber = lambda x : x if isinstance(x, MagicNumber) else Constant(x)

rawDescription: Python number-like class that remembers arithmetic operations?


code:
fo = open("foo.txt", "r")
foo = open("out.txt","w")
foo.write(fo.read())
fo.close()
foo.close()

rawDescription: Reading/Writing to a file in Python

description: Reading/Writing to a file in Python


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

class B(object):
  def __init__(self):
    #Will be set by A later
    self.a = None

b = B()
a = A(b)

rawDescription: python classes dependant on eachother, how to init?

description: Python classes dependant on eachother, how to init


rawDescription: how to create an array of specified dimension of specific type initialized with same value in python?

description: Create an array of specified dimension of specific type initialized with same value in python


code:
timeit.timeit('q.rotate(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8])', number=1000000)
timeit.timeit('q.rotate(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8])', number=100000000)

rawDescription: Python array manipulation

description: Python array manipulation


code:
im = cv.LoadImage('owl.jpg')
patch = subimage(im, (110, 125), np.pi / 6.0, 100, 200)
cv.SaveImage('patch.jpg', patch)

rawDescription: How to straighten a rotated rectangle area of an image using opencv in python?

description: Straighten a rotated rectangle area of an image using opencv in python


code:
a = numpy.arange(12).reshape([3, 2, 2])
def fun(a, axis, state):
    return numpy.rollaxis(a, axis)[state]
fun(a, 0, 1)
fun(a, 1, 1)

rawDescription: numpy index on a variable axis

description: Numpy index on a variable axis


code:
u"rabbit" in s
u"wolf" in s

rawDescription: Fastest possible dictionary-like matching


code: target_el = SubElement(sw_node, "Target")

rawDescription: Python and ElementTree: How can I nest elements/subelements in an XML?


code:
files = request.files.getlist('file')
for file in files:
    hande_file(file)

rawDescription: Multiple file upload with flask built in uplaoder


code: acfgjp

rawDescription: python quickest way to merge dictionaries based on key match

description: Python quickest way to merge dictionaries based on key match


code:
for sender in snaps:
    if sender['media_type'] == 3:
        s.add_friend(sender)

rawDescription: Filtering results in python, I need one variable but only if based on another


code: mo(mo(a, a), b).shape

rawDescription: Creating 3rd order tensors with python and numpy


code:
month_iter = iter(month)
try:
  while True:
    week = next(month_iter)
    # here begins your code
    week = [day[0] for day in week]
    # here ends your code
except StopIteration:
  pass

rawDescription: Cannot change content of list within list. Can anybody explain why?


code: np.take(a, idx, axis=1)

rawDescription: Sorting numpy array according to the sum


code:
from __future__ import print_function
from collections import Counter
from collections import defaultdict
import random

mylist = [random.randint(0,1500) for _ in range(10000000)]

def s1(mylist):
    return {k:mylist.count(k) for k in set(mylist)}

def s2(mlist):
    return Counter(mylist)

def s3(mylist):
    mydict=dict()
    for index in mylist:
        mydict[index] = mydict.setdefault(index, 0) + 1
    return mydict

def s4(mylist):
    mydict={}.fromkeys(mylist,0)
    for k in mydict:
        mydict[k]=mylist.count(k)
    return mydict

def s5(mylist):
    mydict={}
    for k in mylist:
        mydict[k]=mydict.get(k,0)+1
    return mydict

def s6(mylist):
    mydict=defaultdict(int)
    for i in mylist:
        mydict[i] += 1
    return mydict

def s7(mylist):
    mydict={}.fromkeys(mylist,0)
    for e in mylist:
        mydict[e]+=1
    return mydict

if __name__ == '__main__':
    import timeit
    n=1
    print(timeit.timeit("s1(mylist)", setup="from __main__ import s1, mylist",number=n))
    print(timeit.timeit("s2(mylist)", setup="from __main__ import s2, mylist, Counter",number=n))
    print(timeit.timeit("s3(mylist)", setup="from __main__ import s3, mylist",number=n))
    print(timeit.timeit("s4(mylist)", setup="from __main__ import s4, mylist",number=n))
    print(timeit.timeit("s5(mylist)", setup="from __main__ import s5, mylist",number=n))
    print(timeit.timeit("s6(mylist)", setup="from __main__ import s6, mylist, defaultdict",number=n))
    print(timeit.timeit("s7(mylist)", setup="from __main__ import s7, mylist",number=n))

rawDescription: efficient way to count the element in a dictionary in Python using a loop

description: Efficient way to count the element in a dictionary in Python using a loop


code:
parser = argparse.ArgumentParser()
parser.add_argument('-m', required=True)   # must always give '-m'

rawDescription: Argument checks best practices

description: Argument checks best practices


code:
import mechanize
br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 5.2; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11')]
br.open("login.aspx")
br.select_form(nr=0)
br.form.set_all_readonly(False) # allow us to modify hidden form elements
br["__EVENTTARGET"] = "TransactBtn"
br["AccountID"] = "id"
br["UserName"] = "user"
br["Password"] = "pass"
response = br.submit()
[line for line in response.readlines() if 'ErrorMsg' in line]

rawDescription: Py Mechanize submit more data using the auth'ed user


code:
a = "123ab5"

b = ''.join(map(lambda x: str(int(x) + 1) if x.isdigit() else x, a))

rawDescription: Python, context sensitive string substitution


code:
from itertools import izip_longest

result = ''.join([l
    for pair in izip_longest(sample[::2].upper(), sample[1::2].lower(), fillvalue='')
    for l in pair])

rawDescription: Having trouble with whitespace and strings in a function


code: multiple_index = [itemgetter(0, 3, 4)(i) for i in L]

rawDescription: Python list comprehension with multiple variables


code: X - Y

rawDescription: Euclidean distances between several images and one base image


code:
from scipy.optimize import brentq

a = np.min(xdata)
b = np.max(xdata)
x0, k = popt
y0 = -0.50

solution = brentq(sigmoid, a, b, args=(x0, k, y0))  # = 7.142

rawDescription: how to find 50% point after curve fitting using numpy

description: Find 50% point after curve fitting using numpy


code:
from bs4 import BeautifulSoup

html = """

  Monday Some info here...
 and then some

  Tuesday Some info here...
 and then some

  Wednesday Some info here...

  ...

"""
soup = BeautifulSoup(html)
result = soup.find('strong', text='Tuesday').findNextSibling(text=True)
nextSibling = result.findNextSibling()
while nextSibling and nextSibling.name != 'strong':
    print(result.decode('utf-8'))
    result = nextSibling.findNextSibling(text=True)
    nextSibling = result.findNextSibling()

rawDescription: BeautifulSoup parse unstructured html

description: BeautifulSoup parse unstructured html


code:
"This is a sentence."
"Hello, world."
"Hi there; hi there."

rawDescription: Regular expression of a sentence

description: Regular expression of a sentence


rawDescription: Getting a slice of a numpy ndarray (for arbitary dimensions)


code:
df = pd.DataFrame({'a': range(4), 'b': range(1, 5)}).set_index('a')
df.b[df.index == 3] = 29
df.b[df.index == 30] = 3

rawDescription: pandas: more elegant way to retrieve row and set value if exists?

description: Pandas: more elegant way to retrieve row and set value if exists


rawDescription: how to compute a%b recursively?

description: Compute a%b recursively


rawDescription: re.findall not returning a match

description: Re.findall not returning a match


rawDescription: python struct unpack

description: Python struct unpack


code:
ret = evenrow(TwoDArray)
print('Total Value: %d\nEven or Odd: %s' % (ret, 'Odd' if ret % 2 else 'Even'))

rawDescription: Optimizing code for python, values from a 2d array


code:
with open('names.txt', 'r') as check:
    lsNames = list()
    lsLastnames = list()

    for line in check:
        word = line.rstrip().split()
        for item in word[::-1]: #start looking from last item for quick search
            if '@' in item:
                word.remove(item)
        lsNames.append(word[0])
        if len(word[1:]) > 1: #Last Name with two strings
            lsLastnames.append(' '.join(word[1:]))
        else:
            lsLastnames.append(word[1])

with open('myContactList.csv', 'wt') as f:
        writer = csv.writer(f)
        writer.writerow( ('First Name', 'Last Name') )
        for a, b in zip(lsNames, lsLastnames):
            writer.writerow((a.decode('utf-8'), b.decode('utf-8')))

rawDescription: Making cvs file of facebook friends with python to import in new profile


code: # The directory to use for notebooks.

rawDescription: Save IPython file to a particular directory


code:
stacked['group'] = stacked.group_level.str[:6]
stacked['level'] = stacked.group_level.str[6:]
stacked.head(2)

rawDescription: Attributes/information contained in DataFrame column names


code:
x, y, z, *rest = [item.split(':')[-1].strip() for item in data
                                                 if not item.startswith('#')]

rawDescription: How to assign a string from a list in python

description: Assign a string from a list in python


rawDescription: Python Selenium PhantomJS not clicking on same button that Firefox Webdriver is able to click


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

tz = 'US/Pacific'
N = 10**5
dates = pd.date_range('2000-1-1', periods=N, freq='H', tz=tz)
date_strings_tz = dates.format(formatter=lambda x: x.isoformat())
date_strings = [d.rsplit('-', 1)[0] for d in date_strings_tz]

def orig(date_strings, tz):
    return [np.datetime64(pd.Timestamp(s, tz=tz)) for s in date_strings]

def using_tzset(date_strings, tz):
    os.environ['TZ'] = tz
    time.tzset()
    return np.array(date_strings, dtype='datetime64[ns]')

npdates = dates.asi8.view('datetime64[ns]')
x = np.array(orig(date_strings, tz))
y = using_tzset(date_strings, tz)
df = pd.DataFrame({'dates': npdates, 'str': date_strings_tz, 'orig': x, 'using_tzset': y})

rawDescription: Quickly parse Python datetime in a non-local timezone, adjusting for daylight savings


code:
def qsize(self):
    """Return the approximate size of the queue (not reliable!)."""
    self.mutex.acquire()
    n = self._qsize()
    self.mutex.release()
    return n

rawDescription: Does the multi-threaded support of Queue exhibit overthread even when used for just one thread?


rawDescription: Second to last item in django-simple-history


rawDescription: Find all nodes by attribute in xml using Python


code:
class BrokenRepr(object):
    def __repr__(self):
        return "not likely"

rawDescription: When __repr__() is called?

description: When __repr__() is called


code:
for function in functions:
    function(x)

rawDescription: Efficient way of calling set of functions in Python


code:
def normal_interp(x, y, a, xi, yi):
    rbf = scipy.interpolate.Rbf(x, y, a)
    ai = rbf(xi, yi)
    return ai

def rescaled_interp(x, y, a, xi, yi):
    a_rescaled = (a - a.min()) / a.ptp()
    ai = normal_interp(x, y, a_rescaled, xi, yi)
    ai = a.ptp() * ai + a.min()
    return ai

rawDescription: Matplotlib 2D graph with interpolation

description: Matplotlib 2D graph with interpolation


code: d = {k:v for k,v in locals().items() if v is not None and not k.startswith('__')}

rawDescription: Dictionary from variables that may not be initialized


rawDescription: Row based chart plot (Seaborn or Matplotlib)


code:
import numpy as np
x = np.arange(0,1100,100)
y = np.random.rand(6,11)
i = 2
plt.plot(x, y[i])

rawDescription: plot single row of 2d numpy array against 1d list

description: Plot single row of 2d numpy array against 1d list


rawDescription: python string formatting fixed width

description: Python string formatting fixed width


code:
from html.parser import HTMLParser
h = HTMLParser()
s = 'מפגשי'
print(h.unescape(s))

rawDescription: Convert numeric character reference notation to unicode string


code:
def get_part(lst,sep=';'):
    out = []
    for i in lst:
        if i == sep:
           yield out
           out = []
        else:
           out.append(i)

rawDescription: Conditionally merge lists

description: Conditionally merge lists


code:
plt.bar(df['Month'], df['Score'], align='center')

for i in df.index:
    plt.text(df.loc[i, 'Month'], 12, df.loc[i, '_Max'],
             horizontalalignment='center')

plt.xticks(df['Month'])
plt.xlabel('Month')

plt.ylim([0, 15])
plt.ylabel('Score')

rawDescription: vizualize categorical and numerical values on the same plot

description: Vizualize categorical and numerical values on the same plot


rawDescription: Python creating Covariance matrix from List


kind: youtube#searchListResponse

nextPageToken: CAEQAA

kind: youtube#channel

kind: youtube#searchResult

rawDescription: Search YouTube videos by author

description: Search YouTube videos by author


code:
def end_matches(*phrases):           # phrases becomes a tuple that will take any number
    phrase_endings = set()           # number of positional parameters
    for phrase in phrases:
        end = phrase.split('-')[-1]  # take the last element of the split list
        phrase_endings.add(end)
    return len(phrase_endings) == 1  # the set holds only unique values, so a set of
                                     # length 1 means all values in the set are the same

rawDescription: strings match after a certain character

description: Strings match after a certain character


code:
class MyOutputStream(object):

    def write(self, data):
        pass   # Ignore output

import sys
sys.stdout = MyOutputStream()

print("Test")  # Output is ignored

rawDescription: How do I redirrect the output in web.py

description: Redirrect the output in web.py


code:
def miner_not_full_action(world, action, ticks):
   entity = action.entity
   entity_pt = entities.get_position(entity)
   ore = find_nearest(world, entity_pt, entities.Ore)
   (tiles, found) = MinerNotFullAction.miner_to_ore(world, entity, ore)
   ...

rawDescription: If a function (that's outside of the class) needs to use a method from a class, how do I call the method?


code:
df = pd.DataFrame({"A": ['a', 'b', 'c', 'd'], "B": ['e', 'f', 'g', 'h']})
df
bf = pd.DataFrame({"A": [True, True, False, False], "B": [True, False, True, False]})
bf

rawDescription: How to get the filtered dataframe for calculations while retaining the original one in pandas?

description: Get the filtered dataframe for calculations while retaining the original one in pandas


code:
#!/usr/bin/env python
import os.path
import sys
from time import strftime
import Image

row_size = 4
margin = 3

def generate_montage(filenames, output_fn):
    images = [Image.open(filename) for filename in filenames]

    width = max(image.size[0] + margin for image in images)*row_size
    height = sum(image.size[1] + margin for image in images)
    montage = Image.new(mode='RGBA', size=(width, height), color=(0,0,0,0))

    max_x = 0
    max_y = 0
    offset_x = 0
    offset_y = 0
    for i,image in enumerate(images):
        montage.paste(image, (offset_x, offset_y))

        max_x = max(max_x, offset_x + image.size[0])
        max_y = max(max_y, offset_y + image.size[1])

        if i % row_size == row_size-1:
            offset_y = max_y + margin
            offset_x = 0
        else:
            offset_x += margin + image.size[0]

    montage = montage.crop((0, 0, max_x, max_y))
    montage.save(output_fn)

if __name__ == '__main__':
    basename = strftime("Montage %Y-%m-%d at %H.%M.%S.png")
    exedir = os.path.dirname(os.path.abspath(sys.argv[0]))
    filename = os.path.join(exedir, basename)
    generate_montage(sys.argv[1:], filename)

rawDescription: Creating a montage of pictures in python


code:
if first_check:
    new_name = file_name[first_check.span()[1]:]
else:
    new_name = file_name[second_check.span()[1]:]
shutil.move(os.path.join(dirpath, file_name),
            os.path.join(dirpath, new_name))

rawDescription: Cleaner way to move renamed files when walking over directory


rawDescription: matlab find() for nonzero element in python

description: Matlab find() for nonzero element in python


code:
try:
    # Python 2
    from itertools import izip_longest
    zip_longest = izip_longest
except ImportError:
    # Python 3
    from itertools import zip_longest

from pprint import pprint

def main():
    maker =['Horsey', 'Ford', 'Overland', 'Scripps-Booth', 'FutureX', 'FutureY']
    year = ['1899', '1909', '1911', '1913', '20xx']
    model = ['Horseless', 'Model T', 'OctoAuto', 'Bi-Autogo']

    car_data = dict(zip(maker, zip(year, model)))
    car_data_longest = {mk: (yr, md) for mk, yr, md in zip_longest(maker, year, model)}

    pprint(car_data)
    pprint(car_data_longest)

rawDescription: Merging three lists into into one dictionary


code:
class UpdatePost(UpdateView):
    model = Post # assuming you've made from your_app.models import Post call already
    fields = ['title', 'content', 'pub_date'] # for demonstration purposes
    template_name = 'post_form.html'

    @method_decorator(login_required) #Use login required on your dispatch method
    def dispatch(self, request, *args, **kwargs):
        pulled = Post.objects.get(id=kwargs['id'])
        if pulled.created_by == request.user: #just to verify person making edit is rightly disposed to do so
            return super(UpdatePost, self).dispatch(request, *args, **kwargs)
        raise PermissionDenied

rawDescription: Django URL regex complication

description: Django URL regex complication


code: bigDict = {}

rawDescription: using nested dictionaries in python

description: Using nested dictionaries in python


rawDescription: Python: Remove elements from the list which are prefix of other


code:
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap
from ruamel.yaml.compat import ordereddict

yaml_str = """\
first_name: Art
occupation: Architect  # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""

def com_insert(self, pos, key, value, comment=None):
    od = ordereddict()
    od.update(self)
    for k in od:
        del self[k]
    for index, old_key in enumerate(od):
        if pos == index:
            self[key] = value
        self[old_key] = od[old_key]
    if comment is not None:
        self.yaml_add_eol_comment(comment, key=key)

CommentedMap.insert = com_insert

data = ruamel.yaml.round_trip_load(yaml_str)
data.insert(1, 'last name', 'Vandelay', comment="new key")

print(ruamel.yaml.round_trip_dump(data))

rawDescription: Can I insert a line into ruamel.yaml's CommentedMap?

description: Insert a line into ruamel.yaml's CommentedMap


code: [dict(zip(configSet['fields'], result)) for result in configSet['results']]

rawDescription: Python convert a dict object including list to list including dict


code:
from bdb import Bdb
import sys

class RecursionDetected(Exception):
    pass

class RecursionDetector(Bdb):
    def do_clear(self, arg):
        pass

    def __init__(self, *args):
        Bdb.__init__(self, *args)
        self.stack = set()

    def user_call(self, frame, argument_list):
        code = frame.f_code
        if code in self.stack:
            raise RecursionDetected
        self.stack.add(code)

    def user_return(self, frame, return_value):
        self.stack.remove(frame.f_code)

def test_recursion(func):
    detector = RecursionDetector()
    detector.set_trace()
    try:
        func()
    except RecursionDetected:
        return True
    else:
        return False
    finally:
        sys.settrace(None)

rawDescription: Is there a way to check if function is recursive in python?


code: gi = pygeoip.GeoIP('/path/to/GeoIP.dat', pygeoip.MEMORY_CACHE)

rawDescription: MaxMind IP Lookup Speed with Python API

description: MaxMind IP Lookup Speed with Python API


code:
cars = {}
for num in range(1, 3):
    car = pygame.image.load('Car{}.png'.format(num))
    cars[num] = car

rawDescription: Using a String to Call a Variable in Python 3.3 with Pygame


code:
class GPIO(object):
    @property
    def value(self):
        return open("/sys/class/gpio/gpio141/value").read()

    @value.setter
    def set_value(self,val):
         open("/sys/class/gpio/gpio141/value","w").write(val)

rawDescription: Best way to publicize instance attributes

description: Publicize instance attributes


rawDescription: Deleting consonants from a string in Python


rawDescription: How to convert list of dictionaries into list of lists

description: Convert list of dictionaries into list of lists


code:
def decode(data, size, offset=0):
    value = 0

    for ch in data[offset:size]:
        value <<= 6
        value |= ord(ch) - 0x30

    return value

rawDescription: Converting a String to hex and calculate binary result in python


code:
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget, proportion=0, style=wx.ALL, border=5)
sizer.AddSpacer(10)
# or sizer.Add((0,0))
sizer.Add(anotherWidget, proportion=0, style=wx.ALL, border=5)

rawDescription: How I can set gap in Vertical BoxSizer?

description: How I can set gap in Vertical BoxSizer


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelmin, argrelmax

#Generate some example signal
res = 1000
x = np.linspace(0,2*np.pi,res)
y = np.sin(x)
plt.plot(x,y)

#Take a number of discrete steps
Nsteps = 10
skip = x.shape[0]/Nsteps
xstep = x[::skip]; ystep = y[::skip]
plt.plot(xstep,ystep,'o')

#Plot the step graph
plt.step(xstep, ystep)

#Get max and min (only 2 in this simple case)
plt.plot(x[argrelmax(y)[0]],y[argrelmax(y)[0]],'ro')
plt.plot(x[argrelmin(y)[0]],y[argrelmin(y)[0]],'ro')
plt.show()

rawDescription: Finding discrete logic levels in a waveform


code: {{ data|format_dict }}

rawDescription: Best way to format a nested Python dictionary to be rendered in a jinja2 templates

description: Format a nested Python dictionary to be rendered in a jinja2 templates


code:
class IteratorEx(object):
    def __init__(self, it):
        self.it = iter(it)
        self.sentinel = object()
        self.nextItem = next(self.it, self.sentinel)
        self.hasNext = self.nextItem is not self.sentinel

    def next(self):
        ret, self.nextItem = self.nextItem, next(self.it, self.sentinel)
        self.hasNext = self.nextItem is not self.sentinel
        return ret

    def __iter__(self):
        while self.hasNext:
            yield self.next()

rawDescription: Last element in a python iterator

description: Last element in a python iterator


code:
from __future__ import print_function
def poll(x):
    regex = re.compile("\+CMTI:.......")
    [(m, print("You have received a new message!"))[0] for l in x for m in [regex.search(l)] if m]

rawDescription: Combining print statements with list comprehension in python


code:
temp_list = []
for line in f:
    if line: # this makes sure to skip blank lines
      bits = line.split('-')
      temp_list.add(bits[0].strip())

counts = Counter(temp_list)

rawDescription: Take certain words and print the frequency of each phrase/word?


code:
attempts = session.query(UserAttempt).\
                  options(joinedload(UserAttempt.challenge)).all()

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


code:
{{ subscription_price_free_user }}
{{ subscription_price_03Month_user }}
{{ subscription_price_06Month_user }}
{{ subscription_price_12Month_user }}
{{ subscription_price_default }}

rawDescription: django context processors - how to return everything from one function?

description: Django context processors - how to return everything from one function


code:
import struct, array
foo = b"\x00\xff"
list(bytearray(foo))
struct.unpack('{}B'.format(len(foo)), foo)
array.array('B', foo)

rawDescription: Python 2 and 3 compatible method to convert bytes to integer


code:
import pytz
import datetime
la = pytz.timezone('America/Los_Angeles')
now = la.localize(datetime.datetime.now())
print(repr(now))

rawDescription: How would I add the timezone to a datetime.datetime object?


code:
class City(object):
    def __init__(self, name):
        self.name = '' # name of the city

class Country(object, cities):
    def __init__(self, name, cities):
        self.name = name # name of the country
        self.cities = cities # it's a list of Cities instances

class Continent(object):
    def __init__(self, name, countries):
        self.name = name # name of the continent
        self.countries = countries # it's a list of Countries instances

class World(object):
    def __init__(self, continents):
        self.continents = continents # it's a list of Continent instances

france = Country('France', [City('Paris'), City('Annecy'), City('St. Tropez')])
italy = Country('Italy', [City('Rome'), City('Milan')])
uk = Country('UK', [City('London'), City('Bath')])

europe = Continent('europe', [france, italy, uk])
...

rawDescription: How to created inherited objects using Python?

description: Created inherited objects using Python


code:
plt.hist(to_hist, cumulative=1, normed=True, bins=years+[max(years)+1])
plt.xticks([i+0.5 for i in years], years)
plt.show()

rawDescription: Chart cumulative percentage by year in matplotlib?


code:
import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

rawDescription: Can't figure out how to bind the enter key to a function in tkinter


code:
import theano.tensor as T

x, y = T.matrices("xy")

expr = x**2 + y
grad = T.grad(expr.sum(), x)
print(grad.eval({x: [[1, 2], [1, 2]], y: [[1, 1], [2, 2]]}))

rawDescription: Theano gradient with function on tensors


code:
hour, minute = divmod(int(entry), 60)
time = "%s:%s" % (hour, minute)

rawDescription: Unnecessary repetition of declaration

description: Unnecessary repetition of declaration


code: newlist = list(mytup[:3]) + [10] + list(mytup[3:])

rawDescription: Where does the list assignment go?

description: Where does the list assignment go


rawDescription: Google App Engine: Implementing a collection of ordered lists


code:
a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
b = set(a)
b

rawDescription: Python: DISTINCT on GQuery result set (GQL, GAE)


code:
[
'Sharpen your pencil (or, alternatively, use your pen)',
'In a large paper sheet, write your name. When the ink thickens slightly, gently open the envelop and insert the letter inside folded into 3. Set aside.',
'Use the pen again to write your name and address into the evelope. Include the destination address.',
'Seal the envelop and stamp it',
'Instruction courtesy of John Doe'
]

rawDescription: XPath through python

description: XPath through python


code:
trades_30min = trades.resample('30min', sum)
trades_30min

rawDescription: Python pandas - bucketting and getting sum


code:
class Event(models.Model):
    ...
    from_date = ...
    to_date = ...

    def postpone(self, from_date, to_date):
        EventLog.objects.create(event=self, from_date=self.from_date, to_date=self.to_date)
        self.from_date = from_date
        self.to_date = to_date
        self.save()

rawDescription: How to get events which can be postponed for a given date from a table with change log and a table for event in Django?

description: Get events which can be postponed for a given date from a table with change log and a table for event in Django


rawDescription: Python nose configuration file only allow WHERE to be speciifed once


code:
import math

inptTol = float(input("Enter the tolerance: "))
term = 1

sign = 1
divNum = 1
npower = 0
sumPi = 0.0
count = 0

while abs(term) > inptTol:

    term = sign/(divNum * (3**npower))

    sumPi += term

    # values for next term
    sign = -sign
    divNum += 2
    npower += 1
    count += 1

sumPi = math.sqrt(12) * sumPi
pythonPi = math.pi
approxError = abs (sumPi - pythonPi)

print("The approximate value of pi is %.14e\n" \
        "       Python's value of pi is %.14e\n"
        "The error in the approximation of pi is %.6e\n"
        "The number of terms used to calculate the value of pi is %g " %
        (sumPi, pythonPi, approxError, count))

rawDescription: Can anyone tell me why is my code showing the wrong value of pi?


code:
out_text = "1:"                       # add back "1:"
out_text += "\n".join(lines_to_save)  # add all 19 lines with newlines between them
out_text += "\n"                      # add a newline at the end

open("outputfile.txt", "w").write(out_text)

rawDescription: parse blocks of text from text file using Python

description: Parse blocks of text from text file using Python


code:
y = np.arange(12).reshape(3,4)
y

rawDescription: Create an array from n copies of subarray in python


code: busdict.setdefault(bus, []).append(i)

rawDescription: What is the best way to append lists inside a dict?


code: [sum(lst[:i+1])+1 for i in range(len(lst))]

rawDescription: Performing mathematical operation on a list (recursive or not?)


code:
traveller_x,traveller_y = 10,10  # Or whatever you want

while not at_gravity_points(traveller_x,traveller_y):
    directions = ["left","right","up","down"]
    if traveller_x == 0:
        directions.remove("left")
    if traveller_x == x:
        directions.remove("right")
    if traveller_y == 0:
        directions.remove("down")
    if traveller_y == y:
        directions.remove("up")

    to_gravity_point_1 = []
    if traveller_x < gravity_point_1_x:
        to_gravity_point_1.append("right")
    elif traveller_x > gravity_point_1_x:
        to_gravity_point_1.append("left")
    if traveller_y < gravity_point_1_y:
        to_gravity_point_1.append("up")
    elif traveller_y > gravity_point_1_y:
        to_gravity_point_1.append("down")

    # ... do the same to construct to_gravity_point_2
    # then use these two lists to construct your weighting scheme
    # then use random.random() to choose a direction from directions
    # according to that weighting.

    if direction == "left":
        traveller_x -= 1
    elif direction == "right":
        traveller_x += 1
    elif direction == "up":
        traveller_y += 1
    elif direction == "down":
        traveller_y -= 1

rawDescription: Weighted Random Graph Traversal in Python


rawDescription: How to parse Apple's IAP receipt mal-formatted JSON?

description: Parse Apple's IAP receipt mal-formatted JSON


code: attr_name = 'gender'

rawDescription: Why should I ever use "getattr()"?

description: Why should I ever use "getattr()"


code:
class A(object):
  def b(self):
     pass
  @classmethod
  def c(cls):
     pass

A.b
A.c
A.c()
A.b()

rawDescription: Python Data Model Document : an unbound user-defined method and a class method object


code:
abbrevDict = {country: abbrev for abbrev, country in firstArray}
thirdArray = [[key, abbrevDict[country]] for key, country in secondArray]

rawDescription: Comparing Two Arrays resulting into Third Array


rawDescription: Python : How to find in set of rows, one element is less than 1 and other is greater than 1?


code:
import os

fileSizeTupleList = []
largestSize = 0

for i in os.listdir(os.curdir):
    if os.path.isfile(i):
        fileSizeTupleList.append((i, os.path.getsize(i)))

for fileName, fileSize in fileSizeTupleList:
    if fileSize > largestSize:
        largestSize = fileSize
        largestFile = fileName

print(largestFile, largestSize)

rawDescription: How to get largest file from this python 3 code?

description: Get largest file from this python 3 code


code:
class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    membership_id = db.Column(db.String)

    __table_args__ = (db.UniqueConstraint('membership_id'),)

rawDescription: Is it possible to declare an optional and unique attribute for a class model in (Flask) SQLAlchemy?


code:
for item in  yaml.load_all(text):
    print(item)
    # define(one=1, three=3, two=2)
    # action(print=no, report=maybe, run=yes)

rawDescription: Python dictionaries into yaml documents using PyYaml


code:
for person in sorted(cat1, key=lambda x: max(cat1.get(x)), reverse=True):
    print(person, max(cat1.get(person)))

rawDescription: How to sort python dictionary/list?

description: Sort python dictionary/list


code: Potato()[slice(123, x)]

rawDescription: Slice endpoints invisibly truncated

description: Slice endpoints invisibly truncated


code: (xform_matrix + point1) * scalar

rawDescription: Matrix addition/multiplication in numpy

description: Matrix addition/multiplication in numpy


code:
import collections
import copy

class SetDict(object):
    def __init__(self, size):
        self.d = collections.defaultdict(set)
        # Do some initialization; if size is large, this is expensive
        for i in range(size):
            self.d[i].add(1)

    def __copy__(self):
        other = SetDict.__new__(SetDict)
        other.d = self.d.copy()
        return other

rawDescription: Limited deep copy of an instance with a container of containers as an attribute


code:
diff = np.diff(data)
lasting_times = t[diff == -1] - t[1:][diff == 1]

rawDescription: Getting delay time from a CSV data

description: Getting delay time from a CSV data


code:
import flask

app = flask.Flask(__name__)

@app.route("/foo")
def foo():
    content = "
this is foo content
"
    return flask.render_template("base.html", content=content)

@app.route("/bar")
def bar():
    content = "
this is bar content
"
    return flask.render_template("child.html", content=content)

if __name__ == "__main__":
    app.run(debug=True)

rawDescription: How can I access a block from flask(not from template)?

description: Access a block from flask(not from template)


rawDescription: How do I create a pandas dataframe in python from a csv with additional delimiters?

description: Create a pandas dataframe in python from a csv with additional delimiters


code: all((arr[:,:,x].T==arr[:,:,x]).all() for x in range(arr.shape[2]))

rawDescription: testing if a numpy array is symmetric?

description: Testing if a numpy array is symmetric


code:
sign = functools.partial(math.copysign, 1) # either of these
sign = lambda x: math.copysign(1, x) # two will work
sign(-4)
sign(3)

rawDescription: Why doesn't Python have a sign function?

description: Why doesn't Python have a sign function


rawDescription: Add specific columns to a single row list (might be a little basic)


code:
a
sum(a, [])

rawDescription: How to merge item in list

description: Merge item in list


code:
from Tkinter import *
from ttk import *

def label(row, column, text):
    L = Label(root, text=text, anchor='w')
    L.grid(row=row,column=column,sticky="nw",pady=2,padx=3)

def button(root, row, column, text, command):
    B = Button(root, text=text, command=command, width=15)
    B.grid(row=row, column=column, sticky="e", pady=4, padx=3)

def entry(row, column, insert="", show=""):
    E = Entry(root, width=32)
    E.insert(0, insert)
    E.config(show=show)
    E.grid(row=row,column=column)
    return E

def show_ldif():

    values_list = []
    givenname = var0.get()
    sn = var1.get()
    country = var2.get()
    location = var3.get()
    skype = var8.get()

    cn = givenname[0].lower() + sn.lower()
    email = cn + "@company.com"

    # ldif is import format for openLDAP
    ldif_list =[]
    ldif_list.append(("dn: cn=%s,cn=people,ou=company,dc=company,dc=com\n") % cn)
    ldif_list.append('c: %s\n'% country)
    ldif_list.append('cn: %s\n'% cn)
    ldif_list.append(('objectclass: inetOrgPerson\n'
                      'objectclass: posixAccount\n'
                      'objectclass: top\n'
                      'objectclass: shadowAccount\n'
                      'objectclass: ldapPublicKey\n'
                      'objectclass: extensibleObject\n'))

    ldif = ''.join(ldif_list)

    top = Toplevel()
    top.title("Result")

    ldif_text = Text(top, height=30, width=50)
    ldif_text.insert(END, ldif)
    ldif_text.grid(row=0,column=0,columnspan = 2)

    button(top, 1, 1, "Copy to Clipboard", yes_no)
    button(top, 1, 0, "Import to LDAP", yes_no)

def yes_no():
    pass

root = Tk()

root.style = Style()
root.style.theme_use("clam")

root.title("LDAP Adder")

label(0, 0, 'First name')
var0 = entry(0, 1)

label(1, 0, 'Second name')
var1 = entry(1, 1)

label(2, 0, 'Country (two letters)')
var2 = entry(2, 1)

label(3, 0, 'City')
var3 = entry(3, 1)

label(8, 0, 'Skype')
var8 = entry(8, 1)

label(13, 0, '')

button(root, 14, 0, 'Show', show_ldif)
button(root, 14, 1, 'Quit', root.quit)

root.mainloop()

rawDescription: Python Tkinter. Cant apply theme for second window of program


rawDescription: How to make POST request in robobrowser-python

description: Make POST request in robobrowser-python


code:
class Field(object):
    def __init__(self, name):
        self.name = name

    def __set__(self, instance, value):
        instance.__dict__.update({self.name: value})

    def __get__(self, instance, owner):
        if instance is None:
            return self
        try:
            return instance.__dict__[self.name]
        except KeyError:
            return None

def make_field(*args):
    def wrapper(cls):
        for arg in args:
            setattr(cls, arg, Field(arg))
        return cls
    return wrapper

@make_field('foo')
class Thing(object):
    pass

rawDescription: Use class variables as instance vars?

description: Use class variables as instance vars


code:
from mpl_toolkits.mplot3d import *
import matplotlib.pyplot as plt
import numpy as np
from random import random, seed
from matplotlib import cm

fig = plt.figure()
ax = fig.gca(projection='3d')               # to work in 3d
plt.hold(True)

x_surf=np.arange(0, 1, 0.01)                # generate a mesh
y_surf=np.arange(0, 1, 0.01)
x_surf, y_surf = np.meshgrid(x_surf, y_surf)
z_surf = np.sqrt(x_surf+y_surf)             # ex. function, which depends on x and y
ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot);    # plot a 3d surface plot

n = 100
seed(0)                                     # seed let us to have a reproducible set of random numbers
x=[random() for i in range(n)]              # generate n random points
y=[random() for i in range(n)]
z=[random() for i in range(n)]
ax.scatter(x, y, z);                        # plot a 3d scatter plot

ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_zlabel('z label')

plt.show()

rawDescription: matplotlib - 3D plots - combining scatter plot with surface plot

description: Matplotlib - 3D plots - combining scatter plot with surface plot


code: a.apply(adjust_row, axis=1)

rawDescription: Convert data frame columns to dictionary


rawDescription: Finding indices of matches of one array in another array


code:
from __future__ import print_function

import csv

with open('comp.csv', 'r') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)
    scores_start_idx = 2

    for row in csv_input:
        organization_name = row[1]
        organization_scores = row[scores_start_idx:]

        for score_idx, score_text in enumerate(organization_scores):
            print(organization_name + ',' + header[score_idx + scores_start_idx], end='')

            for line in score_text.splitlines():
                score = line.split(':')[-1].strip()
                print(',' + score, end='')
            print()

rawDescription: print only characters after the delimiter python

description: Print only characters after the delimiter python


code:
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random

def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = ''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + password + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

def encrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = Random.new().read(bs - len('Salted__'))
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += padding_length * chr(padding_length)
            finished = True
        out_file.write(cipher.encrypt(chunk))

def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)

rawDescription: How to AES encrypt/decrypt files using Python/PyCrypto in an OpenSSL-compatible way?


code:
encoded_string = urllib.urlencode(my_dict)
redirect('/signupform/?%s'%encoded_string) # attach the encoded string in the url

rawDescription: Django - dictionary passed in redirect is not showing in template


code:
list_a = list_b = list(range(2, 6))
[x*y for x in list_a for y in list_b]

rawDescription: Python Multiplication of Two Lists

description: Python Multiplication of Two Lists


rawDescription: matplotlib contour plot in given range

description: Matplotlib contour plot in given range


rawDescription: Trying to Write For-While Loop, not working


code:
for item in normal_array:
    'vn %.15f %.15f %.15f\n' % (item.x, item.y, item.z)

rawDescription: faster way to do .format()

description: Faster way to do .format()


rawDescription: Convert list of numpy.float64 to float in Python quickly


code:
catcode_fixed = catcode_fixed = catcode_fixed.apply(pd.Series).stack()
catcode_fixed.index = catcode_fixed.index.droplevel(-1)

rawDescription: pandas: column formatting issues causing merge problems

description: Pandas: column formatting issues causing merge problems


code:
from subprocess import check_output

out = check_output(["ntpq", "-p"])

rawDescription: Store output of subprocess.Popen call in a string


code:
from lineup import registry
from lineup import _debug

def create_archive(queue_id, queue):
    queue.set_param("zip_link", _create_archive(resource = queue.context_object, user = queue.user))
    return queue

def create_archive_callback(queue_id, queue):
    _send_email_notification(subject = queue.get_param("zip_link"), user = queue.user)
    return queue

registry.register_job('create_archive', create_archive, callback = create_archive_callback)

rawDescription: Progress bar with long web requests

description: Progress bar with long web requests


code: map(range, lst[:-1], lst[1:])

rawDescription: Generate ranges between pairs of consecutive values


code:
# Run my_package.my_procedure() over my_list
cursor.execute("""
    declare
        l_params my_type_tab;
        type varchar_list is table of varchar2(4000) index by binary_integer;
        l_names varchar_list := :p_names;
        l_keys varchar_list := :p_keys;
        l_values varchar_list := :p_values;
    begin
        l_params.extend(l_names.count);
        for i in 1..l_names.count loop
            l_params(i) := my_type(l_names(i), l_keys(i), l_values(i));
        end loop;

        my_package.my_procedure(l_params);
    end;""",
    p_names=[item.name for item in my_list],
    p_values=[item.value for item in my_list],
    p_keys=[item.key for item in my_list],
    )

rawDescription: Passing in Oracle custom user types from Python/Django


code:
import re
s = "0, 0, ['REFERENCED', 'UPTODATE', 'LRU'], 1"
re.search(r'(\[.*\])', s).group(1)

rawDescription: using regex to get a substring from a string

description: Using regex to get a substring from a string


code:
import time
time = time

rawDescription: python import package globally

description: Python import package globally


code:
from sqlalchemy import Table, create_engine, MetaData
engine = create_engine('mssql+pyodbc://<username>:<password>@<host>/<database>')
meta = MetaData()
funds_table = Table('funds', meta, autoload=True, autoload_with=engine)  # indicate table name (here 'funds') with a string passed to Table as the first argument
funds_table  # now stores database schema object

rawDescription: Does the Storm or SQLAlchemy ORM allow creating schema's from an existing database?


rawDescription: scraping different table with same classes with beautifulsoup,python

description: Scraping different table with same classes with beautifulsoup,python


code:
from django.utils.safestring import mark_safe

currencies = ((mark_safe('$'), mark_safe('$')),
              (mark_safe('£'), mark_safe('£')),
              (mark_safe('€'), mark_safe('€')))

rawDescription: Django Form values without HTML escape

description: Django Form values without HTML escape


code:
def gen_X():
    yield 'a'
    yield 'b'
    yield 'c'
    if Y:
        yield 'd'
    if Z:
        yield 'e'

rawDescription: Conditionals when defining a tuple / list


rawDescription: Can a Matlab or IDL user cope with a Python datetime object?


code:
def applyPlotStyle():
    plt.xlabel('Size')
    plt.ylabel('Time(s)');
    plt.title('Matrix multiplication')

    plt.xticks(range(100), rotation=30, size='small')
    plt.grid(True)

def plotSeries():
    applyPlotStyle()
    plt.plot(xl, serial_full, 'r--')
    plt.plot(xl, acc, 'bs')
    plt.plot(xl, cublas, 'g^')

plt.subplot(211)
plotSeries()

plt.subplot(212)
plt.yscale('log')
plotSeries()

rawDescription: matplotlib subplots with same 'settings'

description: Matplotlib subplots with same 'settings'


code:
def getAllIndicesRecursively(s, l):
    r = []
    for i, v in enumerate(l):
        if isinstance(v, list):
            r += [ getAllIndicesRecursively(s, v) ]
        elif v == s: r += [ i ]
    return r

arr = ["foo", ["foo", "foo", [1, "foo"]], "foo"]
getAllIndicesRecursively("foo", arr)

rawDescription: How can I find all indices of a value in a multidimensional array?

description: Find all indices of a value in a multidimensional array


code:
views.py
profile = models.Profile.objects.get(user=request.user)
profileform = forms.ProfileForm(instance=profile)
user_emailform = forms.UserEmailForm(initial={'email': profile.user.email})

rawDescription: How can I prefill value in a custom form field in a ModelForm

description: Prefill value in a custom form field in a ModelForm


code:
import autoreloader,thread
thread.start_new_thread(autoreloader.reloader_thread, ())
...
app = webapp2.WSGIApplication(...)
def main():
    from paste import httpserver
    httpserver.serve(app, ...)

rawDescription: webapp2: automatically reload code changes

description: Webapp2: automatically reload code changes


code: [v[0].values()[0].n() for v in Vlist]

rawDescription: sagemath: Convert Fractions in Dictionaries in a list to Decimals for matplotlib

description: Sagemath: Convert Fractions in Dictionaries in a list to Decimals for matplotlib


code: s = set(key for counter in counters.values() for key in counter)

rawDescription: Python map() dictionary values

description: Python map() dictionary values


code:
infileData = infile.read()
line = infileData
#for line in infile:
list = line.split(',')
list = line.strip("\n")

rawDescription: python using data from a list, where by you call the data from its index number

description: Python using data from a list, where by you call the data from its index number


code:
import psutil

for proc in psutil.process_iter():
    try:
        flist = proc.get_open_files()
        if flist:
            print(proc.pid,proc.name)
            for nt in flist:
                print("\t",nt.path)

    # This catches a race condition where a process ends
    # before we can examine its files
    except psutil.NoSuchProcess as err:
        print("****",err)

rawDescription: Check if a file is not open( not used by other process) in Python


code:
node_sizes = [150*len(g.edges(n)) for n in g.nodes()]
networkx.draw_spring(g, node_size=node_sizes)

rawDescription: Model an undirected graph in Python

description: Model an undirected graph in Python


code:
import collections
a = collections.Counter([1,1,2,2])
a
a[1]
a[2]

rawDescription: How can I check how many times 0 1 2 3 4 5 6 7 8 9 appears in the input and put it in a list in Python?

description: Check how many times 0 1 2 3 4 5 6 7 8 9 appears in the input and put it in a list in Python


code:
class A(object):
  pass

class B(object):
  pass

class C(A, B):
  pass

C.__bases__

rawDescription: get python class parent(s)

description: Get python class parent(s)


code:
import threading
import queue

def console(q):
    while 1:
        cmd = input('> ')
        q.put(cmd)
        if cmd == 'quit':
            break

def action_foo():
    print('--> action foo')

def action_bar():
    print('--> action bar')

def invalid_input():
    print('---> Unknown command')

def main():
    cmd_actions = {'foo': action_foo, 'bar': action_bar}
    cmd_queue = queue.Queue()

    dj = threading.Thread(target=console, args=(cmd_queue,))
    dj.start()

    while 1:
        cmd = cmd_queue.get()
        if cmd == 'quit':
            break
        action = cmd_actions.get(cmd, invalid_input)
        action()

main()

rawDescription: Constantly looking for user input in Python


code:
def set_active_border(self, window):
    border_color = self.colormap.alloc_named_color(\
        "#ff00ff").pixel
    window.configure(border_width = 2)
    window.change_attributes(None,border_pixel=border_color)
    self.dpy.sync()

rawDescription: Drawing window border in Python xlib

description: Drawing window border in Python xlib


code: place_holder = [ sweedish[item] for item in new if item in sweedish ]

rawDescription: How to convert this function/for loop into a list comprehensionor higher order function using python?

description: Convert this function/for loop into a list comprehensionor higher order function using python


code:
def log_time(logpath="log.txt", interval=5):

    def log_time_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            RESULT = [None]
            def temp():
                RESULT[0] = func(*args, **kwargs)
            t = threading.Thread(target=temp)
            log_entries = 0
            with codecs.open(logpath, "wb", "utf-8") as logfile:
               start_time = time.time()
               t.start()
               while t.is_alive():
                   elapsed_time = (time.time() - start_time)
                   if elapsed_time > interval * log_entries:
                       m, s = divmod(elapsed_time, 60)
                       h, m = divmod(m, 60)
                       logfile.write("Elapsed time: %2dh %2dm %2ds\n" %(h, m, s))
                       log_entries += 1
            return RESULT[0]
        return wrapper
    return log_time_decorator

rawDescription: Logging execution time with decorators

description: Logging execution time with decorators


code:
Y
X
reload
X

rawDescription: import behaviour with already loaded modules

description: Import behaviour with already loaded modules


code:
import commands
# Caps Lock is off.
commands.getoutput("xset q | grep LED")[65]
# Setting Caps Lock on now.
commands.getoutput("xset q | grep LED")[65]

rawDescription: Detect Caps Lock in Python curses

description: Detect Caps Lock in Python curses


code:
stop_words = set(stop_words)
def tokenizer(text):
   return [stemmer.stem(tok) for tok in nltk.word_tokenize(text.lower())
           if tok.isalpha() and tok not in stop_words]

rawDescription: Efficient method to exclude items in one list from another list in Python


code:
first_list = [[{u'name': u'Peter'},{u'name': u'Kevin'},{u'name': u'Earl'}]]

names = []
#You loop over the whole list
for element in first_list:

    # For each element, you loop over the elements inside it
    for object in element:

        # Now, object is each one of the dictionaries
        names.append(object["name"])

rawDescription: How to literate my list

description: Literate my list


code: df.groupby("Country", as_index=False).agg({"Prize_Money": ["sum", "count"]})

rawDescription: pandas display results grouped by column

description: Pandas display results grouped by column


code:
import copy
a = copy.deepcopy(y)
a
a[0] is y[0]
a[0][0] = 'copy!'
y

rawDescription: Why does a 'for' loop in python change unreferenced lists?


code:
new_traff = GroupTraffic.objects.filter(time__gte=date,which_group__private=0).distinct('visitor','which_group').values_list('id',flat=True)

trendingGrp_ids = GroupTraffic.objects.filter(id__in=new_traff).values('which_group').annotate(total=Count('which_group')).order_by('-total')

trendingGrps = [Group.objects.filter(id=grp['which_group']).extra(select={"views":grp['total']})[0] for grp in trendingGrp_ids]

trndids = [grp['which_group'] for grp in trendingGrp_ids]

nonTrendingGrps = Group.objects.filter(private=0).exclude(id__in=trndids).extra(select={"views":0})

allGrps = trendingGrps.append(nonTrendingGrps)

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


code:
from ast import literal_eval
import os.path

output = []
for entry in Master:
    base, lst = entry.split(None, 1)
    for name in literal_eval(lst):
        output.append(os.path.join(base, name))

rawDescription: How to make a list from several nested lists

description: Make a list from several nested lists


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


code:
with open(filename) as f:
    input= f.read()
input= str.replace('""','"')
input= str.replace('"{','{')
input= str.replace('}"','}')
with open(filename, "w") as f:
    f.write(input)

rawDescription: Regex to remove doubled double quotes from CSV


code:
def count(obj):
    total = 0
    for o in obj[1:]:
        # Add the node itself.
        total += 1

        if isinstance(o, list):
            total += count(o)
    return total

rawDescription: How to split two nested lists and combine the parts to create two new nested lists

description: Split two nested lists and combine the parts to create two new nested lists


code:
#!/usr/bin/env python
import shlex
import subprocess
import threading

def kill_all(processes):
    for p in processes:
        try:
            if p.poll() is None:
                p.kill()  # note: it may leave orphans
                p.wait()
        except:  # pylint: disable=W0702
            pass  # ignore whatever it is (including SIGINT)

def wait(process, exit_event):
    try:
        process.wait()
    finally:
        exit_event.set()  # signal the process has exited

def main():
    # start processes
    cmd = "/bin/bash -c 'echo start {0}; sleep {0}; echo done {0}'".format
    processes = []
    for i in range(1, 3):
        try:
            processes.append(subprocess.Popen(shlex.split(cmd(i))))
        except EnvironmentError:
            kill_all(processes)  # failed to start some process; kill'em all
            return 1  # error

    # wait until at least one process finishes
    exit_event = threading.Event()
    for p in processes:
        threading.Thread(target=wait, args=(p, exit_event)).start()

    exit_event.wait()
    kill_all(processes)

if __name__ == "__main__":
    import sys
    sys.exit(main())

rawDescription: Python Thread problems

description: Python Thread problems


code: format_to_year_to_value_dict.setdefault(format_str, {})[year] = value

rawDescription: How to initialize nested dictionaries in Python

description: Initialize nested dictionaries in Python


code:
import ruamel.yaml as yaml

yaml_str = """\
receipt:     Oz-Ware Purchase Invoice
date:        2007-08-06
customer:
    given:   Dorothy

items:
    - part_no:   A4786
      descrip:   Water Bucket (Filled)

    - part_no:   E1628
      descrip:   High Heeled "Ruby" Slippers
      size:      8

bill-to:  &id001
    street: |
            123 Tornado Alley
            Suite 16
    city:   East Centerville
    state:  KS

ship-to:  *id001

specialDelivery:  >
    Follow the Yellow Brick
    Road to the Emerald City.
"""

data1 = yaml.load(yaml_str, Loader=yaml.Loader)
dump_str = yaml.dump(data1, Dumper=yaml.Dumper)
data2 = yaml.load(dump_str, Loader=yaml.Loader)

rawDescription: C# parse and change strings in yaml

description: C# parse and change strings in yaml


code:
def app(environ, start_response):
    calendar = get_processed_file()

    start_response('200 OK', [
        ('Content-Type', 'text/icalendar; charset=utf-8'),
        ('Content-Disposition', 'inline; filename=calendar.ics'),
    ])
    yield calendar

rawDescription: Processing a remote iCal with Python

description: Processing a remote iCal with Python


code:
from operator import itemgetter
largest_key = max(my_dict, key=itemgetter(1))

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


code: rock = Weapon("rock", ["scissors", "lizard"])

rawDescription: Python. How to make a class so that I can create a set of related objects(like"Rock, Paper, Scissors") with it?


code:
class Foo(object):
    def __init__(self):
        self.x = []

rawDescription: Something seems to be stuck in memory

description: Something seems to be stuck in memory


code: soup = BeautifulSoup(site, "html.parser")

rawDescription: Python Beautifulsoup get_text() not getting all text


code:
from itertools import product

my_dict = {'a':[1,2], 'b':[3], 'c':{'d':[4,5], 'e':[6,7]}}

def process(d):
    to_product = []  # [[('a', 1), ('a', 2)], [('b', 3),], ...]
    for k, v in d.items():
        if isinstance(v, list):
            to_product.append([(k, i) for i in v])
        elif isinstance(v, dict):
            to_product.append([(k, i) for i in process(v)])
        else:
            to_product.append([(k, v)])
    return [dict(l) for l in product(*to_product)]

for i in process(my_dict):
    print(i)

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


code:
sorted_lb_coords = sorted(LBCoord)
sorted_core_coords = sorted(CoreCoord)
lb_index = core_index = 0
match_pairs = []

while lb_index < len(sorted_lb_coords) and core_index < len(sorted_core_coords):
    current_lb = sorted_lb_coords[lb_index]
    current_core = sorted_core_coords[core_index]

    # Remember I am only considering x
    if abs(current_lb - current_core) < limit:
        match_pairs.append((current_lb, current_core))

    # This part may also be more complex if you want all available matches.
    # You could run through all the current_core entries till one was out
    # of range and then reset the current_core index and increment the
    # current_lb index.
    if current_lb < current_core:
        current_lb = current_lb + 1
    else:
        current_core = current_core + 1

rawDescription: Python, iterating between 2 lists of lists, seeing if values in one list are similar to values in the other and extracting them


rawDescription: Accessing total_seconds() in pandas data column


code:
import time, subprocess
task = subprocess.Popen(["command"])
time.sleep(10)
task.kill()

rawDescription: How to terminate process in python in certain situation

description: Terminate process in python in certain situation


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

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


rawDescription: Return tuple with smallest y value from list of tuples


code:
if prodAvailable < 0:
    data = {'id':id}

rawDescription: how to return the looped values in a method in python/django that no using array

description: Return the looped values in a method in python/django that no using array


code:
from matplotlib import rcParams
import matplotlib.ticker

if 'axes.formatter.useoffset' in rcParams:
    # None triggers use of the rcParams value
    useoffsetdefault = None
else:
    # None would raise an exception
    useoffsetdefault = True

class FixedScalarFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, format, orderOfMagnitude=0, useOffset=useoffsetdefault, useMathText=None, useLocale=None):
        super(FixedScalarFormatter,self).__init__(useOffset=useOffset,useMathText=useMathText,useLocale=useLocale)
        self.base_format = format
        self.orderOfMagnitude = orderOfMagnitude

    def _set_orderOfMagnitude(self, range):
        """ Set orderOfMagnitude to best describe the specified data range.

        Does nothing except from preventing the parent class to do something.
        """
        pass

    def _set_format(self, vmin, vmax):
        """ Calculates the most appropriate format string for the range (vmin, vmax).

        We're actually just using a fixed format string.
        """
        self.format = self.base_format
        if self._usetex:
            self.format = '$%s$' % self.format
        elif self._useMathText:
            self.format = '$\mathdefault{%s}$' % self.format

rawDescription: Python matplotlib scientific axis formating


code:
def hostname_resolves(hostname):
    try:
        socket.gethostbyname(hostname)
        return 1
    except socket.error:
        return 0

rawDescription: python: check if a hostname is resolved

description: Python: check if a hostname is resolved


code:
from operator import is_not
from functools import partial
L = [0, 23, 234, 89, None, 0, 35, 9]
filter(partial(is_not, None), L)

rawDescription: remove None value from a list without removing the 0 value

description: Remove None value from a list without removing the 0 value


rawDescription: Determining how many times a substring occurs in a string in Python


code:
with open("file.txt") as file:
    for i, line in enumerate(file, 1):
        ...
        if not i % 2:
            consume(file, 2)  # Skip 2 lines ahead.

rawDescription: Read from file: read two lines, skip two lines


rawDescription: Python identify file with largest number as part of filename


code: list(combinations_with_replacement([1, 2, 3, 4, 5],2))

rawDescription: Iterate over same list twice and avoid duplicates in python


code:
import itertools
import string

for guess in itertools.product(string.lowercase, repeat=6):
    if checkguess(''.join(guess)):
        print("Password is: {0}".format(''.join(guess)))

rawDescription: Brute Forcing Application with itertools


rawDescription: Python PySide and Progress Bar Threading


code:
import sublime, sublime_plugin
import subprocess

class ExecuteExternalProgramCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        exec_file = "C:\Path\To\My\Program\spc.py"
        command  = ["cmd.exe", "/c", "python", exec_file, self.view.file_name()]
        subprocess.Popen(command)

rawDescription: Run external python script from Sublime Text passing active file as argument


code: myfunc()

rawDescription: How to understand python decorator arguments pass

description: Understand python decorator arguments pass


rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code:
myLink = 'http://127.0.0.1:8983:/solr/collection1/update/extract/?literal.id=any_document_id_you_like&commit=true'
myfile = 'myfile=@path_to_the_file_you_want_to_index'

rawDescription: Is it possible to make such a request with extra options in Python?


code:
# calculations.py, the bat substitute.

def calculate_from_input(file_name):
    input_ = open(file_name, 'rb') # The mode you read the fike depends on your purposes.
    # .... Do your calculations
    return result   # Return a list of velocities, for example.

rawDescription: How to run a bat file from Python 3.3.2

description: Run a bat file from Python 3.3.2


code: np.concatenate([y[1][None,...] for y in x], axis=0)

rawDescription: Recursively defining an N-dimensional numpy array


code:
_f_array = numpy.array([
        [1, 4, 3],
        [2, 8, 6],
        [0, 7, 5],
    ])
def f(a, b):
    return _f_array[a, b]
def f_row(a):
    return _f_array[a, :]
def f_col(b):
    return _f_array[:, b]

rawDescription: Best data structure for 3D data?

description: Best data structure for 3D data


code: desired_list = [map(str, e) for e in list1]

rawDescription: Most efficient way to change all items in a sublist to a string?


code:
np.all([np.allclose(np.polynomial.polynomial.polyval(xx, fit[:, j]),
                    interpol[j]) for j in range(25)])

rawDescription: NumPy PolyFit and PolyVal in Multiple Dimensions?


code:
digits = (1, 2, 3, 4)
nums = newNums = list(digits)
newNums = [n * 10 + m for n in newNums for m in digits]
nums.extend(newNums)
nums
newNums = [n * 10 + m for n in newNums for m in digits]
nums.extend(newNums)
nums

rawDescription: Creating correct for-loop/iteration for a unique list


code:
mylist = []
mylist.append(dict)

rawDescription: pulling multiple records from mongo using flask and python

description: Pulling multiple records from mongo using flask and python


rawDescription: How can I encode and decode percent-encoded (URL encoded) strings in Python?

description: Encode and decode percent-encoded (URL encoded) strings in Python


code:
tracer = logging.getLogger('elasticsearch.trace')
tracer.setLevel(logging.INFO)
tracer.addHandler(logging.FileHandler('/tmp/es_trace.log'))

rawDescription: No handlers could be found for logger "elasticsearch.trace"


code:
p = sub.Popen(['ffprobe', fname], stderr=sub.PIPE)
stdin, stderr = p.communicate()

rawDescription: Subprocess.communicate prints newline to standard output


code:
from itertools import count
import random
def my_split(lst, chunks):
    def chunk_creator():
        total = 0
        while total <= len(lst):
            x = random.choice(chunks)
            yield L[total: x + total]
            total += x
        yield total - x

    def chunk_finder():
        for _ in count():
            chunk = list(chunk_creator())
            total = chunk.pop(-1)
            if total == len(L):
                return chunk[:-1]
    if max(chunks) <= len(L):
        return chunk_finder()
    else:
        return None

rawDescription: Python: dividing a list into chunks with varying size


code:
for i in hwy:
    i[3].sort() # changes the element(list) in place

for i in hwy:
    i[3] = sorted(i[3]) # this will change the element in hwy also

rawDescription: How to sort string in ascending order based upon the integers that are part of this string

description: Sort string in ascending order based upon the integers that are part of this string


code: result = namedtuple('result', ['rollno', 'name'] + sub)

rawDescription: Pass list of elements to named tuple

description: Pass list of elements to named tuple


code:
source = "Sentence1  .. . word1    word2.    . .  word other_word  . .   ."
''.join(c for c in read(source))

rawDescription: how do you determine the end of a sentence in a python serial parser?

description: Determine the end of a sentence in a python serial parser


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

rawDescription: Python - removing characters from a list


code: f=open ('txt','r').readlines()

rawDescription: line or string?

description: Line or string


code:
arguments = [1, 2, 3, 4]
functions = [a, b, c, d]

results = [func(arg) for func, arg in zip(functions, arguments)]

rawDescription: Call different function for each list item


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

# Initialize second column of output array
out_count = np.zeros_like(out_id)

# Find indices where the first columns of a,b are placed in out_id
_,a_idx = np.where(a[:,None,0]==out_id)
_,b_idx = np.where(b[:,None,0]==out_id)

# Place second column of a into out_id & add in second column of b
out_count[a_idx] = a[:,1]
np.add.at(out_count, b_idx,b[:,1])

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

rawDescription: Updating a NumPy array with another

description: Updating a NumPy array with another


code: max([len(i) for i in arr])

rawDescription: Find the lengths of list within numpy ndarray


rawDescription: How to filter JSON data using Python?

description: Filter JSON data using Python


code:
class Person(sa.Base):
    person_id = sa.Column(sa.Integer, primary_key=True)
    start = sa.Column(sa.DateTime, primary_key=True)
    end = sa.Column(sa.DateTime, primary_key=True)
    name = sa.Column(sa.String)

class Assignment(sa.Base):
    person_id = sa.Column(sa.Integer, primary_key=True)
    start = sa.Column(sa.DateTime, primary_key=True)
    end = sa.Column(sa.DateTime, primary_key=True)
    ...

rawDescription: Can SQL Alchemy and Pyramid handle a date effective scenario


code:
import tkinter
import tempfile
import base64
import zlib

ICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'
    'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))

_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
    icon_file.write(ICON)

tk = tkinter.Tk()
tk.iconbitmap(default=ICON_PATH)
label = tkinter.Label(tk, text="Window with transparent icon.")
label.pack()

tk.mainloop()

rawDescription: Make the logo transparent in Python tkinter 3.4


code:
fig = pyplot.figure(2)

cmap2 = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
                                           ['blue','black','red'],
                                           256)

img2 = pyplot.imshow(zvals,interpolation='nearest',
                    cmap = cmap2,
                    origin='lower')

pyplot.colorbar(img2,cmap=cmap2)

fig.savefig("image2.png")

rawDescription: 2D grid data visualization in Python

description: 2D grid data visualization in Python


code:
# Open a file
fo = open("filename.txt", "w")
fo.write(a);
fo.write(b);
fo.write(c);

# Close opend file
fo.close()

rawDescription: How do i store data collected by "input" onto a text file in python

description: Store data collected by "input" onto a text file in python


code:
import os
def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

rawDescription: Implement touch using Python?

description: Implement touch using Python


code:
class Player(object):
  def __init__(self):
    self.image = get_image('image1.png')

rawDescription: Pre-loading images pygame

description: Pre-loading images pygame


code:
def translate_tuple(a):
  return a in [1, 3]

import dis
dis.dis(translate_tuple)

rawDescription: Bytecode optimization

description: Bytecode optimization


code:
def to_dict(self):
    return dict((p, unicode(getattr(self, p))) for p in self.properties()
                if getattr(self, p) is not None)

rawDescription: Converting GAE model into JSON

description: Converting GAE model into JSON


code:
soup
links_dict

rawDescription: How to find links and modify an Html using BeautifulSoup in Python

description: Find links and modify an Html using BeautifulSoup in Python


code:
l.extend(t)
l.extend(t2)

rawDescription: Add all elements of an iterable to list

description: Add all elements of an iterable to list


code:
for o in objects:
    o.save()

rawDescription: Encapulated object creation in python

description: Encapulated object creation in python


code:
pat = re.compile(r'>>>[A-Z]+<<<')

with open('yourfile') as fh:
    for line in fh:
        result += line
        if pat.search(line):
            break

rawDescription: Regular Expression String Mangling Efficiency in Python - Explanation for Slowness?


code:
class TestSuiteGUI(QtGui.QMainWindow):
    def __init__(self, parent=None):
        ...
        # keep a reference to the threads
        self._threads = []
        for num, com_port_chunk in zip(range(1,25), self.com_ports_list):
            tester_thread = Tester(com_port_chunk, num)
            # get a reference to the associated textbox somehow...
            textbox = get_the_textbox()
            tester_thread.updateText.connect(textbox.setText)
            tester_thread.start()
            self._threads.append(tester_thread)

rawDescription: Send signals from multiple worker threads to the GUI thread