code:
import pysvn
client = pysvn.Client()
client.import_(path='/tmp/example',
               url=u'svn+ssh://t420/svnroot/trunk/example',
               log_message='Initial checkin')

rawDescription: Using import_() function from pysvn package


code:
main_voltages = [5.5, 15.7, 28.5]
limit_list = [[5,10], [15,20], [25,30]]
result = [b[0] <= a <= b[1] for (a, b) in zip(main_voltages, limit_list)]
result

rawDescription: Perform check on lists

description: Perform check on lists


code:
def partial_match(x,y):
  nb_matches = sum(ea == eb for (ea,eb) in zip(x,y))
  return 0.6 < float(nb_matches) / len(x) < 1

rawDescription: SQLite compare query Python

description: SQLite compare query Python


code:
#!/usr/bin/env python
from flask import Flask, flash, redirect, render_template, \
     request, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template(
        'index.html',
        data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])

@app.route("/test" , methods=['GET', 'POST'])
def test():
    select = request.form.get('comp_select')
    return(str(select)) # just to see what select is

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

rawDescription: Getting value from select tag using flask


code:
data.dtype
temp2 = data.ravel().view('int32, int32')
temp2.sort(order = ['f1', 'f0'])

rawDescription: Python Matrix sorting via one column

description: Python Matrix sorting via one column


code:
arith_expr = operatorPrecedence(num,
    [
    (oneOf('-'), 1, opAssoc.RIGHT),
    (oneOf('* /'), 2, opAssoc.LEFT),
    (oneOf('+ -'), 2, opAssoc.LEFT),
    ])

rawDescription: pyparsing: how to find string of form a + b = c OR c = a + b

description: Pyparsing: how to find string of form a + b = c OR c = a + b


rawDescription: Representing version number as regular expression


code: data = numpy.loadtxt(..., usecols=tuple(xrange(1, numcols, 2)))

rawDescription: Numpy loadtxt load every other column

description: Numpy loadtxt load every other column


rawDescription: Can I add a second name to a variable

description: Add a second name to a variable


code:
df
col = ['a','b','c']
permutation = [0,2,2]
interim = df[col].isin(permutation)

rawDescription: Python: given list of columns and list of values, return subset of dataframe that meets all criteria


code:
dot_result = 0.0
for jj in range(sample_size):
    dot_result += tmp_sample[jj]*weight_array[jj]

rawDescription: Why assign values to C-contiguous array is slow in my case using Cython


code:
v[1, :, :]
v[1, Ellipsis, Ellipsis]
v[1, slice(None), slice(None)]
v[(1, Ellipsis, Ellipsis)]
v[(1, slice(None), slice(None))]

rawDescription: represent numpy ellipsis

description: Represent numpy ellipsis


code: import random

rawDescription: create and insert randomly duplicates

description: Create and insert randomly duplicates


code:
import scipy.sparse as sps
a = sps.rand(1000, 1000, format='csr')
a[::10, ::10]

rawDescription: Slicing a sparse scipy matrix to subsample for every 10th row and column


code:
def exit_and_return_counter(*args):
    sys.stdout.write('%s'%counter)
    exit()

if __name__ == '__main__':
    signal.signal(signal.SIGUSR1, exit_and_return_counter)
    try:
        while 1:
            main_loop()
    except KeyboardInterrupt:
        sys.exit()

rawDescription: Retrieve a value from subprocess after kill()


code: strdata = []

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


code:
import pandas as pd
json_text = """
[
   {"key_1":"foo1","key_2":"bar1","key_3":"foobar1"},
   {"key_1":"foo2","key_2":"bar2","key_3":"foobar2"}
]
"""
df = pd.read_json(json_text)
df.to_excel('output.xls', index=False)

rawDescription: Mapping a json file to excel with python


code:
import numpy as np
import pandas as pd

N = 10
test = pd.DataFrame(np.random.randint(4, size=(N, 3)),
                    columns=['trader', 'stock', 'foo'],
                    index=pd.date_range('2000-1-1', periods=N))
test.index.names = ['date']
test = test.set_index(['trader', 'stock'], append=True)

test = test.unstack().unstack()

test = test.resample("1D")

test = test.fillna(0)

means = pd.rolling_mean(test, 50, 50)
means.columns = [('{}_norm'.format(col[0]),)+col[1:] for col in means.columns]
test = pd.concat([test, means], axis=1)

test = test.stack().stack()
test = test.reorder_levels(['trader', 'stock', 'date'])
test = test.sort_index()
print(test.head())

rawDescription: rolling mean in Pandas with fixed time window (instead of fixed nb. of observations)

description: Rolling mean in Pandas with fixed time window (instead of fixed nb. of observations)


code: np.dot(X,A) + np.dot(W,B)[:,None]

rawDescription: Compute each element of matrix

description: Compute each element of matrix


code:
l
[c.real for c in l]

rawDescription: numpy's complex128 conversion

description: Numpy's complex128 conversion


code:
direction = (-gradient).argmax(axis=0)
result = code.take(direction)

rawDescription: Applying functions to multidimensional numpy arrays without loops


code:
if condition:
    return True if otherCondition else False

rawDescription: Python does not allow multiple return() statements in ternary; possible alternative that is also aesthetically pleasing?


code:
class MyClass(object):

    def __init__(self, initializer):
        """
        initialize internal data structures with 'initializer'
        """
        if isinstance(initializer, dict):
            for k, v in itit_dict.items():
                # do something with k & v
                setattr(self, k, v)
        elif isinstance(initializer, (list, tuple)):
            for item in initializer:
                setattr(self, item, None)

rawDescription: The most pythonic way to implement two constructors


code: df1 = pd.DataFrame([ x for x in df['aaData'] ])

rawDescription: Create DataFrame from Scraped Javascript Table List


rawDescription: Merge multiple dataframes with non-unique indices


code:
from collections import defaultdict

S = [1, 2, 3, 4, 5, 6,   8, 9]

T_1 = [1, 4]
T_2 = [2, 3]
T_3 = [1, 3, 4]

Ts = [S, T_1, T_2, T_3]

parents = defaultdict(int)
for i, T in enumerate(Ts):
    for elem in T:
        parents[elem] += 2 ** i

children = defaultdict(list)
for elem, p in parents.items():
    children[p].append(elem)

print(list(children.values()))

rawDescription: Partitioning a superset and getting the list of original sets for each partition


code:
def pairs(l):
    for i in range(len(l)-1):
        for j in range(i+1, len(l)):
            yield l[i], l[j]

rawDescription: Follow-up on iterating over a graph using XML minidom


rawDescription: Find matching rows in 2 dimensional numpy array


code:
input = "Héllô"
input
normalized = unicodedata.normalize("NFKD", input)
normalized

rawDescription: Regex - match a character and all its diacritic variations (aka accent-insensitive)


code:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(...);
# some stuff..
gluLookAt(...);

rawDescription: How do I use gluLookAt properly?

description: Use gluLookAt properly


code:
pat = re.compile("_(?:%s)_"%"|".join(sorted(split_list,key=len)))
list(itertools.chain(pat.split(line) for line in data))

rawDescription: Splitting a string based on a certain set of words


code:
from collections import Counter
from itertools import chain
L=[['a','b'],['foo','bar'],['spam','eggs'],['b','c'],['spam','bar']]
S=Counter(chain(*L))
S
[[y for y in x if S[y]!=1] for x in L]

rawDescription: Remove all the words from a list of lists which occur in a given set


code:
def substrings(s, min_length=1):
    for start in range(len(s)):
        for length in range(min_length, len(s)-start+1):
            yield s[start:start+length]

rawDescription: Getting a regex trie to run faster?

description: Getting a regex trie to run faster


code:
s = """/a/[/r/Antonym/,/c/af/afghanistan/,/c/af/pakistan/]
/a/[/r/UsedFor/,/c/en/book/,/c/en/learn/]
/a/[/r/Antonym/,/c/ar/???/,/c/ar/???/]
bad line
/a/[/r/IsA/,/c/en/island/,/c/en/land_mass/]"""

for line in s.split("\n"):
    if line.startswith("/a"):
        a = line[4:-1]
        r, c1, c2 = a.split(",")
        if c1.split("/")[2] == "en" and c2.split("/")[2] == "en":
            print(" ".join((r.split("/")[2], c1.split("/")[3], c2.split("/")[3])))

rawDescription: How to extract triples in Python?

description: Extract triples in Python


code: averageNAS = {}

rawDescription: Finding the highest value

description: Finding the highest value


code:
def is_suffix(potential_suffix, text):
    return potential_suffix == text[-len(potential_suffix):]

rawDescription: Why are two empty string slices not acting 'equal'?


code:
def printName():
       print("Enter your name: ")
       n=input()
       return n

n = printName()
# now you can use n

rawDescription: I am getting a NameError: name 'n' is not defined


code:
d = list()
for i in range(0,10):
    d.append(i)

rawDescription: How do I declare list in python using for loop in one line?

description: Declare list in python using for loop in one line


rawDescription: How to convert string series into integer

description: Convert string series into integer


code:
class LatestQuestionAnswer(models.Model):
    question = models.ForeignKey(Question)
    question_answer = models.ForeignKey(QuestionAnswer)
    answer_set = models.ForeignKey(AnswerSet)
    created = created = models.DateTimeField(auto_now_add=True)

rawDescription: Django getting only the most recent object after filtering


code:
writer = csv.DictWriter(f, fieldnames=player.keys())
writer.writeheader()
writer.writerow(player)

rawDescription: how do i print to a a CSV file from different inputs in python

description: Print to a a CSV file from different inputs in python


rawDescription: Creating Dictionaries from XML Data in Python (with xml.etree.ElementTree)


code:
L = [['not', 'D'], ['not', 'C'], 'B', 'A']
L.sort(key=lambda x:(not isinstance(x,str), x if isinstance(x,str) else x[1]))
L
L = [['not', 'Pours'], ['not', 'Outside'], 'Rusty', 'Rains']
L.sort(key=lambda x:(not isinstance(x,str), x if isinstance(x,str) else x[1]))
L

rawDescription: Sort alphabetically a list with strings and lists of strings in Python


rawDescription: Python global in module

description: Python global in module


code:
class BinTree():
    def __init__(self, item = None):
        self.item = item
        self.left = None
        self.right = None

class Tree():
    def __init__(self):
        self.root = None
    def put(self, indata):
        newnode = BinTree(indata)
        if self.root is None:
            self.root = newnode
            return self.root
        current = self.root
        while True:
            if indata > current.item:
                # if bigger, go right
                if current.right is None:
                    # if right slot is empty, make one
                    current.right = newnode
                    return newnode
                else:
                    current = current.right
            elif indata < current.item:
                # if smaller, go left
                if current.left is None:
                    # if left slot is empty, make one
                    current.left = newnode
                    return newnode
                else:
                    # if left slot is full, go deeper
                    current = current.left
            else:
                # if equal
                return False
    def isempty(self):
        return self.root is None

tree = Tree()
tree.isempty()
tree.put(5)
tree.isempty()

rawDescription: Method isEmpty for binary tree

description: Method isEmpty for binary tree


code: regex = re.compile("guys.*$", re.DOTALL)

rawDescription: Fetching a part of a string using regex starting from a given word untill the end of the string(one that includes newlines)


code: lst = [d[k] for k in lst]

rawDescription: Assigning integers to strings

description: Assigning integers to strings


code: Psign = [0]*max ### make a list the same length as P, to store the signs

rawDescription: Euler's pentagonal number function in python


code:
import os
file = "C:\\Documents\\file.txt"
os.startfile(file)

rawDescription: How to open an Excel file with Python to display its content?

description: Open an Excel file with Python to display its content


code:
new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
new_grammar._productions.append(singapore_production)
new_parser = ChartParser(new_grammar)
sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
new_parser.parse(sent)

rawDescription: NLTK: can I add terminal to grammar that is already generated


rawDescription: Django: extend queryset or exclude from exclude method


code: help(png)

rawDescription: PyPNG to draw a simple filled box

description: PyPNG to draw a simple filled box


code:
# set the columns of interest as MultiIndex
df = df.set_index(['messageId', 'streetName', 'linkId'])
print(df)

rawDescription: Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy


code: d = {str(i): value for i, value in enumerate(targets)}

rawDescription: Python: dict comprehension from a list with key and value being strings?


rawDescription: Editing keys of a dictionary in Python

description: Editing keys of a dictionary in Python


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

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


code:
import re
input = open("infile","r")
output = open("outfile","w")

oneLine = re.compile(r"""(
        \d{2}-  # the beginning of the line
        .+?     # the middle of the line
        \.\d{3} # the dot and three digits at the end
)""", re.X)

while buffer:
    buffer = input.read(6000) # adjust this to suit
    #newbuffer = re.split(r'(\d{2}-.+?\.\d{3})',buffer) # I'll use the commented re object above
    newbuffer = oneLine.split(buffer)
    newbuffer = filter(None,newbuffer)
    output.write( "\n".join(newbuffer) )
input.close()
output.close()

rawDescription: Regex for Two Digits and a Hyphen

description: Regex for Two Digits and a Hyphen


code:
d = numpy.empty((len(a), 3), dtype=a.dtype)
d[:, 0], d[:, 1], d[:, 2] = a, b, c
d = d.ravel()

rawDescription: Numpy union arrays in order

description: Numpy union arrays in order


rawDescription: Django Images Display

description: Django Images Display


code:
def way6(theList, theDict):
    return [item for item in theList if item in theDict]

rawDescription: Finding all keys in a dictionary from a given list QUICKLY


code:
line_old = ''
line_new = ''
import fileinput
import sys
import glob

for line in fileinput.input(glob.iglob("/mydir/*.txt"),inplace=True):
    if line.strip() == line_old:
        sys.stdout.write(line_new+"\n")
    else:
        sys.stdout.write(line)

rawDescription: Open every text file in directory then replace particular line in each


rawDescription: How to exclude a particular html tag(without any id) from several tags while using scrapy?

description: Exclude a particular html tag(without any id) from several tags while using scrapy


code:
def flatten(lst):
    if not lst:
        return []
    elif not isinstance(lst, list):
        return [lst]
    else:
        return flatten(lst[0]) + flatten(lst[1:])

rawDescription: recursively (or non-recursively) iterating through python array and get the elements

description: Recursively (or non-recursively) iterating through python array and get the elements


code:
d
d_map = {k: [v] if isinstance(v, int) else v for k,v in zip(d['triggers'], d['actions'])}
d_map

rawDescription: Python -- elegant dict comp where keys/values comes from sync'd lists?


code:
import sympy
x, y, z = sympy.symbols('x:z')
f = sympy.exp(x + y) - sympy.sqrt(z)
f.free_symbols

rawDescription: How can I get a list of the symbols in a sympy expression?

description: Get a list of the symbols in a sympy expression


code:
import itertools

for i, j, k, l, m, n, o, p, q in itertools.product(xrange(1, 5), repeat=9):
    ...

rawDescription: Alternative with less indentation for nested loops in Python


code:
def test_data_gen():
    from random import sample
    for i in range(1,5):
        n = 10**i
        population = set(range(1,100000))
        some_list = sample(list(population),n)
        population.difference_update(some_list)
        some_dict = dict(zip(sample(population,n),
                             sample(range(1,100000),n)))
        yield "Population Size of {}".format(n), (some_list, some_dict), {}

rawDescription: Optimize the performance of dictionary membership for a list of Keys


code:
entry_iter = iter(entries)
entry_iter.next() # Throw away the first version
for i, entry in enumerate(entry_iter):
    diff = entry - entries[i]

rawDescription: python for loop, how to find next value(object)?

description: Python for loop, how to find next value(object)


code: OrderedDict(("field%d"%i,v) for i,v in enumerate(fields) if not math.isnan(v))

rawDescription: Conditionally add multiple items to dictionary in Python


code:
text_link = soup.new_tag("a", href="#")
text_link.string = text

rawDescription: BeautifulSoup: How to replace value in an element with an element tag?


code:
import pandas as pd

df = pd.DataFrame({'foo':['100-200','1000-1100','1100-1200','200-300']})

df[['start', 'end']] = df['foo'].apply(lambda val: pd.Series(map(int, val.split('-'))))
df.sort(['start', 'end'], inplace=True)
print(df)

rawDescription: Numbers with hyphens or strings of numbers with hyphens


code:
class P(object):
    def __init__(self, lon, lat):
        self.lon = lon
        self.lat = lat

    def __sub__(self, other):
        dist = ((other[0] - self[0])**2 + (other[1] - self[1])**2)**0.5
        return dist

    def __getitem__(self, key):
        if key == 0:
            return self.lon
        elif key == 1:
            return self.lat
        else:
            raise IndexError

    def __setitem__(self, key, value):
        if key == 0:
            self.lon = value
        elif key == 1:
            self.lat = value
        else:
            raise IndexError

rawDescription: How can I create my own datatype in python so that I could overwrite arithmetic operators?

description: Create my own datatype in python so that I could overwrite arithmetic operators


rawDescription: Itertools: selecting in pandas based on previous three rows, or previous elements in a list


rawDescription: Redimension numpy array dynamically

description: Redimension numpy array dynamically


code:
with open(fileName,'r') as myfile:
    for line in myfile:
        # the rest of your code here, i.e.:
        stop_words=set(stopwords.words("english"))
        words=word_tokenize(line)

rawDescription: How to read a CSV file line by line and store it to new CSV file on new row every time?

description: Read a CSV file line by line and store it to new CSV file on new row every time


code:
from collections import Counter

def checkYinX(y, x):
    return not (Counter(y) - Counter(x))

rawDescription: How to search through a string to see if i can spell a word

description: Search through a string to see if i can spell a word


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

data = pd.read_csv('data.csv', header=None)
ints = data[data[1]=='INT']
exts = data[data[1]=='EXT']
INT_index = data[data[1]=='INT'].index
EXT_index = data[data[1]=='EXT'].index
time = [t for t in data[4]]
int_dist = [d for d in ints[3]]
ext_dist = [d for d in exts[3]]

fig, ax = plt.subplots()
ax.scatter(int_dist, INT_index, c='orange', s=150)
ax.scatter(ext_dist, EXT_index, c='black', s=150)
ax.set_yticks(np.arange(len(data[4])))
ax.set_yticklabels(time)
plt.legend(['INT', 'EXT'], loc=4)
plt.xlabel('Distance')
plt.ylabel('Time')
plt.show()

rawDescription: Python 3.4 reading from CSV formats

description: Python 3.4 reading from CSV formats


code: {key: value for key, value in d1.items() if value}

rawDescription: Filter values of dictionary

description: Filter values of dictionary


code:
for fin in glob.glob(path):
    with open(fin) as f:
        # you're missing some code here - I've taken the next two lines from your previous stackoverflow posts by guessing
        text = f.read()
        data = tone_analyzer.tone(text)

    tonenames = []; tonescores = [];
    for cat in data['document_tone']['tone_categories']:
        for tone in cat['tones']:
            tonenames.append(tone['tone_name'])
            tonescores.append(tone['score'])
            print(tone['tone_name'],tone['score'])

    outfile = fin.replace('.html', '_tonename.csv')
    with open(outfile, mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1)
        writer.writerows((name, score) for name, score in zip(tonenames, tonescores))

rawDescription: CSV download not showing exact values

description: CSV download not showing exact values


rawDescription: Is there any function that returns the out edges of a node?


code:
if "Addition":
    easygui.msgbox ("Please enter the correct answer to earn a point, there are 10 questions in this quiz")

    Figure1 = random.randrange(0,11)
    Figure2 = random.randrange(0,11)

    PlayerAnswer = easygui.enterbox ("What is " +str(Figure1)+ " + " +str(Figure2)+ "?")

    if int(PlayerAnswer) == Figure1 + Figure2:
        AdditionAnswers += 1
        easygui.msgbox ("Correct! Your score is "+str(AdditionAnswers))
    else:
        AdditionAnswers += 0
        IncorrectAnswers += 1

    easygui.msgbox ("Sorry, incorrect! Your score is still "+str(AdditionAnswers))
    easygui.msgbox ("You scored " +str(AdditionAnswers)+ " out of 10")

rawDescription: Add two random numbers together?

description: Add two random numbers together


code: some_json_data = {"companies": [{"foo": 1}]}

rawDescription: FOR loop in object/array

description: FOR loop in object/array


rawDescription: Matrix Approximation and Predicting Timeseries in Python/R with SVD


code:
def toeach_category(subf):
    def percentage(t):
        return between(1, 3)(
            subf.ix[(t - 60 < subf['Time']) & (subf['Time'] <= t), 'Value'])
    result = subf[['Time']].applymap(percentage)
    return result

rawDescription: Customizing rolling_apply function in Python pandas


rawDescription: Python : How to vectorize my split function with Numpy


code:
with open("foo.txt", "w") as f:
   w = csv.writer(f, delimiter=',')
   w.writerows(data)

rawDescription: Replace column separation of # with comma or tab


rawDescription: Class and Array Problems

description: Class and Array Problems


code:
ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)

rawDescription: Average line for bar chart in matplotlib


code:
myNum = int(input("Enter a number: "))
print(myNum + 1)

rawDescription: How to use inputs in loops

description: Use inputs in loops


code:
@classmethod
def get_cars_from(cls, start=0, end=10):
    return [cls(i) for i in range(start, end)]

rawDescription: Python: how to get create instance of a class within same class?


code:
import sympy as sy
sy.simplify('2*x+x')

rawDescription: Python: Eval with undefined variables (2*x+x = 3*x)


code:
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from eventsApp import Event, EventInvite

@login_required
def viewEvent(request, event_pk):
    event = Event.objects.get(pk=event_pk)
    eventInvite = EventInvite.objects.get(event=event,guest=request.user)
    eventInvite.viewed = True
    eventInvite.save()

    return render_to_response("eventView.html", { 'event' : event })

rawDescription: How to get the count of views of a particular event?

description: Get the count of views of a particular event


code:
new_list = [[]]
for i in test_list:
    if element_regex.match(i):
        new_list.append([])
    new_list[-1].append(i)

rawDescription: Splitting a list by matching a regex to an element


code:
fh, ax = plt.subplots(1,2)
coupled(time, [.3, 1/.7], ax)
coupled(time, [.4, 1/.7], ax)
coupled(time, [1/.7, .3], ax)
coupled(time, [.5, .5], ax)
coupled(time, [.1, .1], ax)
ax[0].legend()
ax[1].legend()
ax[0].set_xlabel('N1')
ax[0].set_ylabel('N2')
ax[1].set_xlabel('time')
ax[1].set_ylabel(r'$N_i$')
ax[0].set_title('implicit')
ax[1].set_title('explicit (i.e. vs independant variable time)')
plt.show()

rawDescription: Solve Lotka-Volterra model using SciPy

description: Solve Lotka-Volterra model using SciPy


code:
class CapitalisedHelpFormatter(argparse.HelpFormatter):
    def add_usage(self, usage, actions, groups, prefix=None):
        if prefix is None:
            prefix = 'Usage: '
        return super(CapitalisedHelpFormatter, self).add_usage(
            usage, actions, groups, prefix)

parser = argparse.ArgumentParser(formatter_class=CapitalisedHelpFormatter)

rawDescription: Customize argparse help message

description: Customize argparse help message


code:
class Fooer(object):

    @staticmethod
    def foo(x):
        ...
        return _foo_helper(x)

    @staticmethod
    def _foo_helper(x):
        ...
        return y

rawDescription: Refactoring: break out class or just function to new file?


rawDescription: Compare rows then take rows out if neccessary


code:
with open('/tmp/test.txt') as f:
   data=f.readlines()

data
a,b,c=data
a
b
c

rawDescription: How does readline and readlines work in Python


rawDescription: Differentiate between single and double precision


code: sorted([bool, int, float, long, list, tuple, dict, str, unicode])

rawDescription: Python Max Function

description: Python Max Function


rawDescription: Searching for a word pattern in a Python dataset


code:
class PatientForm(forms.modelForm):
    first_name=forms.CharField(widget=TextInput())
    last_name=forms.CharField(widget=TextInput())

    def __init__(self,user,*args, **kwargs):
         self.request = kwargs.pop('request')
         return super(PatientForm,self).__init__(*args,**kwargs)

    def clean(self):
         cleaned_data=self.cleaned_data
         try:
             Patient.objects.get(first_name=cleaned_data['first_name'], last_name=cleaned_data['last_name'],doctor=self.request.user)
         except Patient.DoesNotExist:
             pass
         else:
             raise ValidationError('A Patient with this name already exists')

    def save(self,*args, **kwargs):
         kwargs['commit']=False
         obj = super(PatientForm.self).save(*args,**kwargs)
         if self.request:
               obj.doctor = self.request.user
         obj.save()

    class Meta:
        model=Patient
        exclude = ['doctor']

rawDescription: How to store current User in Django model

description: Store current User in Django model


rawDescription: Convert sets to frozensets as values of a dictionary


code:
import numpy as np

items_per_line = 5

np.random.seed(1024)
arr = np.random.random(size=12)

fmt = '{:16.8E}'
line_fmt = items_per_line * fmt

arr_fmt = [line_fmt] * (arr.shape[0] // items_per_line)
remainder = arr.shape[0] % items_per_line
if remainder:
    arr_fmt.append(remainder * fmt)
arr_fmt = '\n'.join(arr_fmt)

print(arr_fmt.format(*arr))

rawDescription: Printing a 1d array in 5E16.8 formatting


code: from App1.utils import ClassIWantFromApp1

rawDescription: Python Path Override

description: Python Path Override


code:
import fontforge
font = fontforge.open('blank.sfd')
glyph = font.createMappedChar('A')
glyph.importOutlines('sourceimg.svg')
font.generate('testfont.ttf')

rawDescription: Inverted glyph: bitmap > SVG via autotrace > glyph via fontforge


code:
df[['ip0', 'ip1', 'ip2', 'ip3']] = \
    pd.read_table(StringIO(df['ip'].to_csv(None,index=None)),sep='.')

rawDescription: Using `split` on columns too slow - how can I get better performance?


rawDescription: print top 3 Pandas DataFrame rows to JSON

description: Print top 3 Pandas DataFrame rows to JSON


code:
if not d.keys() & {'amount', 'name'}:
    raise ValueError

rawDescription: python: what is best way to check multiple keys exists in a dictionary?

description: Python: what is best way to check multiple keys exists in a dictionary


code:
d = {'p1': None, 'p2': val2}
cur.execute("""
    select *
    from t
    where
        (%(p1)s is null or col1 = %(p1)s)
        and
        (%(p2)s is null or col2 = %(p2)s)
    """, d
)

rawDescription: Psycopg2 production appropriate mogrify?

description: Psycopg2 production appropriate mogrify


code:
provided_ips = request.headers.getlist("X-Forwarded-For")
# The first entry in the list should be the client's IP.

rawDescription: Parse X-Forwarded-For to get ip with werkzeug on Heroku


rawDescription: Read data from text format into Python Pandas dataframe


rawDescription: Check for valid file extension

description: Check for valid file extension


code: frozenset([1,2]) == frozenset([2,1])

rawDescription: Assert list of list equality without order in Python


code:
class QueryHelper(object):
    def __init__(self, param, text):
        self._param = param
        self._build_query(text)

    def _build_query(self, text):
        self._query = text + " and ham!"

class RefinedQueryHelper(QueryHelper):
    def _build_query(self, text):
        # what if we want to store the query in __query instead?
        # then we need to modify two classes...
        super(RefinedQueryHelper, self)._build_query()
        self._query = self._query.replace("ham", "spam")

rawDescription: Should internal class methods returnvalues or just modify instance variables in python?


code:
def powers_of_x(x):
    print('Powers function with', x, 'entered:')
    for n in range(-3, 4, 1):
        print('power of', n, '=', x**n)
    print('First one ended (using variables with defined range)')

def powers_of_9():
    print('Powers function for 9 is:')
    powers_of_x(9)
    print('Second one ended (no passed variable here)')

def combined():
    x = int(input('Enter value to start: '))
    print('First, run powers_of_x function for entered value of:', x)
    powers_of_x(x)
    print('Second, run powers_of_9 function for powers of 9:')
    powers_of_9()
    print('All now finished')

rawDescription: Python 3.3: Functions calling other functions


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

def custom_plot(x, y, **kwargs):
    ax = kwargs.pop('ax', plt.gca())
    base_line, = ax.plot(x, y, **kwargs)
    ax.fill_between(x, 0.9*y, 1.1*y, facecolor=base_line.get_color(), alpha=0.5)

x = np.linspace(0, 1, 10)
custom_plot(x, x)
custom_plot(x, 2*x)
custom_plot(x, -x, color='yellow', lw=3)

plt.show()

rawDescription: Get matplotlib color cycle state

description: Get matplotlib color cycle state


code:
def __enter__(self):
    return self

def __exit__(self, *exc_info):
    del exc_info
    self.close()

rawDescription: Can I use pymysql.connect() with "with" statement?

description: Use pymysql.connect() with "with" statement


code:
def processor():
  while app.Pending(): app.Dispatch()

rawDescription: Using external GUI libraries to make user interfaces in Autodesk Maya


code: matchMatrix = [[i.match(j) for j in targetLines] for i in matchLines ]

rawDescription: most concise way to operate over two lists, returning list of lists in python

description: Most concise way to operate over two lists, returning list of lists in python


code: draw.text((xpos,ypos), mytext, font=ImageFont.truetype('myfont.ttf', 11))

rawDescription: How to output unicode characters and lines into an image file? -python

description: Output unicode characters and lines into an image file? -python


code: args = sys.argv if __name__ == '__main__' else [whatever_you_want]

rawDescription: How to prevent an imported module from 'importing' sys.argv[1:]

description: Prevent an imported module from 'importing' sys.argv[1:]


code:
#views.py
form = MyForm(request)

#forms.py
def __init__(self, req, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.request = req

#somewhere in your form's body
max_min(self.request)

rawDescription: Context processor in forms.py

description: Context processor in forms.py


code:
with open("file.txt") as f:
    for k, val in groupby(f, lambda x: x.strip() != ""):
        if k:
            k, v = next(val), val
            d[k].extend(map(str.rstrip, v))

rawDescription: Append items to dictionary Python

description: Append items to dictionary Python


code:
import ConfigParser
Config = ConfigParser.ConfigParser()
Config
Config.read("c:\\tomorrow.ini")
Config.sections()

rawDescription: Python application menu

description: Python application menu


code:
class Event(models.Model):
    ALERT   = "alert"
    WARNING = "warning"
    ERROR   = "error"
    EVENT_TYPES = (
        (ALERT,   "Alert"),
        (WARNING, "Warning"),
        (ERROR,   "Error"),
    )

    # map events to colours
    COLOUR = {
        ALERT:   "FF6A00",
        WARNING: "FFE800",
        ERROR:   "FF0000",
    }

    event_type = models.CharField(max_length=16, choices=EVENT_TYPES, default=ALERT)

    @property
    def colour(self):
        """
        Return the hexadecimal colour of this event
        """
        self.COLOUR[event_type]

# now this would return True
my_error_event.colour == "FF0000"

rawDescription: Where to store color information in a web application?


code:
from bisect import bisect_left, insort

def dedup(seq):
    'Remove duplicates. Preserve order first seen.  Assume orderable, but not hashable elements'
    result = []
    seen = []
    for x in seq:
        i = bisect_left(seen, x)
        if i == len(seen) or seen[i] != x:
            seen.insert(i, x)
            result.append(x)
    return result

rawDescription: Removing duplicate elements from a Python list containing unhashable elements while preserving order?


code: [s.strip() for s in data_string.splitlines()]

rawDescription: String split on new line, tab and some number of spaces


code: df = df.groupby(by=['date','category','country','criteria','size'], as_index=False).sum()

rawDescription: Where did my dimensions go when I did a groupby in pandas?


code:
logging.debug('This message should go to the log file (debug) (function %r)',
              funcion)

rawDescription: How get the called function to loggin with decorators?


code: maximum

rawDescription: Python sum of N consecutive digits of a large number


code:
dictionaries = {}
for i in range(10):
    filename = sample+'_rand{0}.genes.tajD'.format(i)
    dictionaries[i] = {}
    with open(filename, 'r') as data:
        for line in data:
            line = line.strip().split('\t')
            gene, taj = line[0], line[3]
            dictionaries[i][gene] = taj

with open(sample+'_rand0.genes.tajD', 'r') as genes, open(outfilename, 'w') as outfile :
    for line in genes :
        line = line.strip().split('\t')
        mastergene = line[0]
        values = []
        for i in range(10):
            values.append(dictionaries[i][mastergene])
        #alternative to the above for loop: values = [dictionaries[i][mastergene] for i in range 10]
        avg = numpy.mean(values)
        outfile.write(mastergene + '\t' + '\t'.join(values) + '\t' + avg + '\n')

rawDescription: Opening multiple files, creating lists, and dictionaries with for loop and range function in iPython


rawDescription: Appending/Merging in Python

description: Appending/Merging in Python


code:
_str = """fhsdkfhskdslshsdkhlghs
bksjvsfgsdnfsfbjfgzfga
avzaeafeaeaddacbytt!tw"""

rawDescription: cut a string with duplicates

description: Cut a string with duplicates


rawDescription: Accessing values in a list of nested dictionaries


code: x = MyArray(bl)

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


code:
class Rectangle():
    def __init__(self):
        self.x = random.randrange(0, 701)
        self.y = random.randrange(0, 501)
        self.width = random.randrange(20,71)
        self.height = random.randrange(20,71)
        self.change_x = random.randrange(-3,4)
        self.change_y = random.randrange(-3,4)

    def move(self):
        self.x += self.change_x
        self.y += self.change_y

    def draw(self):
        pygame.draw.rect(screen, green, [self.x, self.y, self.width, self.height], 0)

rawDescription: List of 10 rectangles, meant to draw every one, only draws one


code: labels[i].mousePressEvent = functools.partial(self.remove_image, source_label = labels[i]) #just pass to self.remove_image the label id

rawDescription: Remove an Image in QLabel After Button Clicked


code:
import numpy as np
x = np.array([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN])
np.median(x[~np.isnan(x)])

rawDescription: Median of a list with NaN values removed, in python


code:
st = 'Hello my name is John'
st.rsplit(' ', 1)

st.rsplit(' ', 1)[1]

rawDescription: Select last chars of string until whitespace in Python


code: res = np.float32(out)

rawDescription: python - OpenCV mat::convertTo in python

description: Python - OpenCV mat::convertTo in python


rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


rawDescription: pydoc.render_doc() adds characters - how to avoid that?

description: Pydoc.render_doc() adds characters - how to avoid that


code:
class A:
    def __init__(self,value):
        self.value=value
        self.cache = {}
    def function(self,a):
        """function returns a+1 and caches the value for future calls."""

        # Add a default value of empty string to avoid key errors,
        # check if we already have the value cached
        if self.cache.get(a,''):
            return self.cache[a]
        else:
            result = a + 1
            self.cache[a] = result
            return result

rawDescription: How to assign cache to a method in an OOP fashion?

description: Assign cache to a method in an OOP fashion


code:
func.unzip(ifile, instances)
func.changecs()  # This should trigger an Exception since changecs expects a positional argument

rawDescription: How to use a list in other function?

description: Use a list in other function


code:
def monitor(f):
    def f_():
        pool = ThreadPool(processes=2)
        t = pool.apply_async(func=f)
        spinner = itertools.cycle("|/~\\")
        while not t.ready():
            sys.stdout.write("\r%s: running %s %s" % (time.ctime(), f.__name__, next(spinner)))
            sys.stdout.flush()
            time.sleep(.5)
        sys.stdout.write("\n")
    return f_

@monitor
def analysis():
    time.sleep(4)

analysis()

rawDescription: Show function status using Python standard library


rawDescription: Find borders on a list in python

description: Find borders on a list in python


code:
import theano
import theano.tensor as T

x1 = T.fscalar('x1')
x2 = T.fscalar('x2')

k = T.arange(1, 10)

expr = ((2 + 2 * k - T.exp(x1 * k) - T.exp(x2 * k)) ** 2).sum()

func = theano.function([x1, x2], expr)

rawDescription: Defining a function with a loop in Theano


code: sum([i.a for i in B])

rawDescription: Adding up instance variables of a class object


code:
import xml.dom.minidom
d = xml.dom.minidom.parse("test.xml")
print(d.getElementsByTagName("type")[0].firstChild.data)

rawDescription: Accessing child nodein an xml in python

description: Accessing child nodein an xml in python


code:
colors = {}

for color in image.getdata():
    colors[color] = colors.get(color, 0) + 1

rawDescription: Pixel Loading and Evaluating with PIL

description: Pixel Loading and Evaluating with PIL


code:
def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    dict.update(self, newdict)

rawDescription: Overriding methods without falling into infinite recursion


code:
"ß".lower() is "ß"
"ß".upper() is "SS"
"ß".upper().lower() is "ss"
("ß".upper().lower() == "ß".lower()) is False

rawDescription: Python - Ignore letter case

description: Python - Ignore letter case


rawDescription: pandas and category replacement

description: Pandas and category replacement


rawDescription: Plotting 'vectors' with different colors in matplotlib


rawDescription: Using Cython To Link Python To A Shared Library


code:
if new_vals:
        d[key] = list(set(new_vals)-set(orig_vals))

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


rawDescription: Python compare 2 lists filled with 3-tuples


code:
allstrings = [u'This', u'the third largest earthquake in recorded history', u'the third largest earthquake', u'recorded history', u'massive tsunamis , which caused widespread devastation when they hit land , leaving an estimated 230,000 people dead in countries around the Bay of Bengal and the Indian Ocean', u'massive tsunamis', u'widespread devastation', u'they', u'land', u'an estimated 230,000 people dead in countries around the Bay of Bengal and the Indian Ocean', u'an estimated 230,000 people', u'countries around the Bay of Bengal and the Indian Ocean', u'countries', u'the Bay of Bengal and the Indian Ocean', u'the Bay', u'Bengal and the Indian Ocean', u'Bengal', u'the Indian Ocean']
allstr2 = [u' {} '.format(s.strip()) for s in allstrings]
[s.strip() for s in allstr2 if not any(t in s for t in allstr2 if t != s)]

rawDescription: How to select the finest granularity of string items in a list

description: Select the finest granularity of string items in a list


code:
import os
os.system("shutdown -r now")

rawDescription: My Raspbian doesn't reboot via a Python application


code: return np.where(np.logical_or(f < min_freq, f > max_freq), 0, sig)

rawDescription: How to convert complex numbers back into "normal" numbers after performing FFT

description: Convert complex numbers back into "normal" numbers after performing FFT


code:
ServerList = [
 {
'IP_' : '@IPADDR1',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
},
 {
'IP_' : '@IPADDR2',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}
]

rawDescription: Python - Is it possible to have a dictionary in a list?


code:
import networkx as nx
import matplotlib.pyplot as plt

N = 10
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i, j), i * 10 + j) for i, j in G.nodes() )
nx.draw_networkx(G, pos=pos, labels=labels)

plt.axis('off')
plt.show()

rawDescription: Remove rotation effect when drawing a square grid of MxM nodes in networkx using grid_2d_graph


code: map((lambda foo: maptest(foo, bars)), foos)

rawDescription: Using python map and other functional tools


code: plt.imshow(B/C, interpolation='none')

rawDescription: Get 2D array after mask condition

description: Get 2D array after mask condition


code:
import pytz
import datetime as dt

utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%d %H:%M:%S %Z%z'

text='''\
10/1/2010   0:0:0
10/1/2010   0:6:0
10/1/2010   23:54:0
10/3/2010   0:0:0
'''

for datestring in text.splitlines():
    date=dt.datetime.strptime(datestring,"%m/%d/%Y %H:%M:%S")
    date_eastern=eastern.localize(date,is_dst=None)
    date_utc=date_eastern.astimezone(utc)
    print(date_utc.strftime(fmt))

rawDescription: How to convert EST/EDT to GMT?

description: Convert EST/EDT to GMT


rawDescription: NumPy sort matrix rows by number of non-zero entries


code:
size_count.plot(kind='scatter', x='community size', y='number of communities',
                s=100, c='level')

rawDescription: How to dynamically update a plot in a loop?

description: Dynamically update a plot in a loop


code:
import sympy as sy

phi_1, phi_2, x, a_1, a_2, L = sy.symbols("phi_1, phi_2, x, a_1, a_2, L")

phi = a_1 + a_2*x
shape_coeffs = sy.solve([sy.Eq(phi_1, phi).subs({x:0}), sy.Eq(phi_2, phi).subs({x:L})], (a_1, a_2))
phi = phi.subs(shape_coeffs)

phi = sy.collect(sy.expand(phi), phi_1)
N = sy.Matrix([phi.coeff(v) for v in (phi_1, phi_2)]).transpose()
print(N)

rawDescription: Factor sympy expression to matrix coefficients?


code:
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()

rawDescription: How do you you run a Twisted application via Python (instead of via Twisted)?

description: You run a Twisted application via Python (instead of via Twisted)


code:
train_station=['Amsterdam-Central','Amsterdam-Amstel','Utrecht']
begin = 0

for x in train_station:
    print("Current station is: "+x)
    print("Stations to go: ")

    begin += 1

    for y in range(begin, 3, 1):
        print(train_station[y])

rawDescription: Tracking counter in nested for loop

description: Tracking counter in nested for loop


code:
self.serial_thread.started.connect(self.serial.start)
self.serial_thread.finished.connect(self.serial.stop)

self.db_thread.started.connect(self.db.start)
self.serial_thread.finished.connect(self.db.stop)

self.serial.data_ready.connect(self.db.handle_new_data)

# Starting the database first, as it we won't lose a single packet of data
self.db_thread.start()
self.serial_thread.start()

rawDescription: QThread use in Python

description: QThread use in Python


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

rawDescription: List of Elements to Boolean Array

description: List of Elements to Boolean Array


rawDescription: Set derivatives of a function to 0 in Python


rawDescription: Per-cell standardization efficiently in NumPy


code: d = {e:i for i, e in enumerate(l)}

rawDescription: Transforming list to dict with list items as keys and list indices as values in python


code:
class Entry(Base):
    __table__ = ...

    _entry = __table__.c.entry

    @hybrid_property
    def entry(self):
        return self._entry

    @entry.setter
    def entry(self, value):
        self._entry = value
        self.cached_entry = markdown(value)

rawDescription: Auto updating properties in sqlalchemy

description: Auto updating properties in sqlalchemy


rawDescription: Check if string has date, any format

description: Check if string has date, any format


code:
z = Zipit('/my/path/to/zip')

f = MultipartParam('file', fileobj=z, filesize=z.size, filename='test.zip',filetype='application/zip')
datagen, headers = multipart_encode([ f, ('akey', 'mykey')])

rawDescription: Generator for multipart form data with python requests


code:
page = page.read()
file = open('url.html', 'w')
file.writelines(page)
file.close()

rawDescription: Extracting text from webpage, processing with Perl/Python, then rebuilding the page with links added


code:
items = []
for link in links:
    item = MyItem()
    item['link'] = link.select('span/a/@href').extract()
    items.append(item)
for item in items:
    yield item

rawDescription: Adding text string to scraped data

description: Adding text string to scraped data


code:
celldisp(h)
celldisp(v)

rawDescription: Algorithm to group sets of points together that follow a direction


code:
from PyQt4 import QtGui, QtCore

class SplashScreen(QtGui.QWidget):
    def __init__(self, pixmap):
        QtGui.QWidget.__init__(self)
        self._pixmap = pixmap
        self._message = QtCore.QString()
        self._color = QtGui.QColor.black
        self._alignment = QtCore.Qt.AlignLeft
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint |
                            QtCore.Qt.WindowStaysOnTopHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setFixedSize(self._pixmap.size())
        self.setMask(self._pixmap.mask())

    def clearMessage(self):
        self._message.clear()
        self.repaint()

    def showMessage(self, message, alignment=QtCore.Qt.AlignLeft,
                                   color=QtGui.QColor.black):
        self._message = QtCore.QString(message)
        self._alignment = alignment
        self._color = color
        self.repaint()

    def paintEvent(self, event):
        textbox = QtCore.QRect(self.rect())
        textbox.setRect(textbox.x() + 5, textbox.y() + 5,
                        textbox.width() - 10, textbox.height() - 10)
        painter = QtGui.QPainter(self)
        painter.drawPixmap(self.rect(), self._pixmap)
        painter.setPen(QtGui.QColor(self._color))
        painter.drawText(textbox, self._alignment, self._message)

    def mousePressEvent(self, event):
        self.hide()

def show_splash(path):
    image = QtGui.QPixmap(path)
    splash = SplashScreen(image)
    font = QtGui.QFont(splash.font())
    font.setPointSize(font.pointSize() + 5)
    splash.setFont(font)
    splash.show()
    QtGui.QApplication.processEvents()
    for count in range(1, 6):
        splash.showMessage(splash.tr('Processing %1...').arg(count),
                           QtCore.Qt.AlignCenter, QtCore.Qt.white)
        QtGui.QApplication.processEvents()
        QtCore.QThread.msleep(1000)
    splash.hide()
    splash.close()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    show_splash(sys.argv[1])
    app.quit()

rawDescription: White border on a transparent QSplashScreen image in PyQt


code: a = np.fromfile(file, dtype=np.uint32, sep=' ')  # alternative: np.genfromtxt

rawDescription: python array of decimals into binary numbers efficienty

description: Python array of decimals into binary numbers efficienty


code:
print('some text {:.3f} some more text',format(MyFloat(.4444)))
print('some text {:.3fz} some more text',format(MyFloat(.4444)))
print('some text {:+.3f} some more text',format(MyFloat(.4444)))
print('some text {:+.3fz} some more text',format(MyFloat(.4444)))
print('some text {:.3f} some more text',format(MyFloat(-.4444)))
print('some text {:.3fz} some more text',format(MyFloat(-.4444)))

rawDescription: Print floating point values without leading zero


code:
class hidden(object):
    def __init__(self):
        self.value = 4
        from types import MethodType
        def dep_show(self):
            return self.value
        self.__setattr__('dep_show', MethodType(dep_show, self))
        def dep_change(self, n):
            self.value = n
        self.__setattr__('dep_change', MethodType(dep_change, self))
    def show(self):
        return self.value
    def change(self, n):
        self.value = n
    def __dir__(self):
        heritage = dir(super(self.__class__, self)) # inherited attributes
        hide = ['dep_show', 'dep_change']
        show = [k for k in self.__class__.__dict__.keys() + self.__dict__.keys() if not k in heritage + private]
        return sorted(heritage + show)

rawDescription: Hide deprecated methods from tab completion


code:
grand_Matrix[0,...] = first_Matrix
grand_Matrix[1,...] = second_Matrix

rawDescription: Inserting one matrix as an element of another matrix using Numpy


code:
from itertools import chain
result = list(zip(*chain(l1, l2, l3)))

# You can also skip list creation if all you need to do is iterate over result:
# for x in zip(chain(l1, l2, l3)):
#     print(x)

print(result)
print(result == unzipped)

rawDescription: Zip lists of tuples

description: Zip lists of tuples


rawDescription: List Range Refinement

description: List Range Refinement


code:
import pprint

t1atts = ('A', 'B', 'C', 'D')
t2atts = ('B', 'D', 'E')

t1tuples = [
    ['A', 1, 'A', 'a'],
    ['B', 2, 'Y', 'a'],
    ['Y', 4, 'B', 'b'],
    ['A', 1, 'Y', 'a'],
    ['S', 2, 'B', 'b']]

t2tuples = [
    [1, 'a', 'A'],
    [3, 'a', 'B'],
    [1, 'a', 'Y'],
    [2, 'b', 'S'],
    [3, 'b', 'E']]

t1columns = set(t1atts)
t2columns = set(t2atts)
t1map = {k: i for i, k in enumerate(t1atts)}
t2map = {k: i for i, k in enumerate(t2atts)}

join_on = t1columns & t2columns
diff = t2columns - join_on

def match(row1, row2):
   return all(row1[t1map[rn]] == row2[t2map[rn]] for rn in join_on)

results = []
for t1row in t1tuples:
    for t2row in t2tuples:
        if match(t1row, t2row):
            row = t1row[:]
            for rn in diff:
                row.append(t2row[t2map[rn]])
            results.append(row)

pprint.pprint(results)

rawDescription: Natural Join Implementation Python

description: Natural Join Implementation Python


rawDescription: Calling a method of a class within a class (non-inherited separate classes)


code:
tags = [
    { 'tag': 'django', 'size': 10 },
    { 'tag': 'python', 'size': 8 },
    { 'tag': 'Australia', 'size': 1 },
    { 'tag': 'coffee', 'size': 6 },
    { 'tag': 'pycon', 'size': 3 },
    { 'tag': 'html', 'size': 9 },
]

rawDescription: Creating a tag cloud from a list in Django?


code:
def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v is dictionary)
    return "%s['%s_%d']" % (d_name, entry, counter)

reason  = define_var(result_dict,2,3)
print(reason)

rawDescription: How to pass the name of a dictionary

description: Pass the name of a dictionary


rawDescription: Mapping a returned string to a specific function


rawDescription: Sorting a complex datastructure

description: Sorting a complex datastructure


rawDescription: Knapsack prob, but allow over-filling

description: Knapsack prob, but allow over-filling


code:
import shutil
from subprocess import Popen, PIPE, STDOUT

p = Popen("./generate-output", stdout=PIPE, stderr=STDOUT, bufsize=-1)
shutil.copyfileobj(p.stdout, foofile)
p.stdout.close()
rc = p.wait()

rawDescription: how to call stdout.write from subprocess.Popen?

description: Call stdout.write from subprocess.Popen


code:
# the string fragments like "root=Root [" need to be replaced by "root=["
# to achieve this, we match the regex pattern "\w+ ["
# This matches ALL instances in the input string where we have a word bounded by "=" & " [",
# i.e. "Root [", "Key3 [", "Key3_3" are all matched. as will any other example you can think of
# where the `word` is composed of letters numbers or underscore followed
# by a single space character and then "["
# We replace this fragment with "[", (which we will later replace with "{")
# giving us the transformation "root=Root [" => "root=["
import re
o = re.compile(r'\w+ [[]')
y = re.sub(o, '[', x, 0)

rawDescription: Custom format to JSON

description: Custom format to JSON


code:
a = range(3)
b = a                     # same object
b.append(3)
a, b                      # same contents

rawDescription: Python objects confusion: a=b, modify b and a changes!


code:
parser.add_argument(
    "--Scount", nargs=2, type=int,
    help="Used to display GRBs within the specified spectral count range")

rawDescription: Issues with using argparse with listcomprehensions


code:
(movie_actor
    .join(movie_actor) # Join by movie
    .values() # Extract values (actors)
    .filter(lambda x: x[0] != x[1]))

rawDescription: PySpark - create pair RDD with two keys that share the same value


code: spam = Tile(ham)

rawDescription: Type casting with non standard types in python


rawDescription: Call a list variable from a for loop in Python


code: {{ item.description|truncatewords:10 }}

rawDescription: Google appengine string replacement in template file


code:
for emailid in items[::-1]:

    resp, data = m.fetch(emailid, "(RFC822)")

    if ( break_ ):
        break

    for response_part in data:

      if isinstance(response_part, tuple):
          msg = email.message_from_string(response_part[1])
          varSubject = msg['subject']
          varDate = msg['date']

rawDescription: Extract information from Gmail with Python


code:
from social.backends.facebook import FacebookOAuth2

class CustomFacebookOAuth2(FacebookOauth2):
    name = 'facebook-custom'

rawDescription: How can I ask for different permissions from facebook at different times?

description: Ask for different permissions from facebook at different times


code:
config = ConfigParser()
config.read('people.ini')
people = []

for s in config.sections():
    if not s.startswith('person:'):
         continue

    name = s[7:]
    person = dict(config.items(s))
    person['name'] = name

    people.append(person)

rawDescription: Define a list of object values in ConfigParser


rawDescription: Summing up every alternate 4 elements in list


rawDescription: Python regex findall numbers and dots

description: Python regex findall numbers and dots


code:
for file in glob.glob(sys.argv[1]):
     with open(file, 'r') as f:
         do_something_to(f)

rawDescription: Running python from windows command prompt on many files


code:
import urllib
import re

url = 'http://www.rob389.com/dp/tr/11/9789754681383'
txt = urllib.urlopen(url).read()
pat = re.compile(r'tOBJ\.DATA\[0\]\.(\w+)\s*=\s*([^;]*);', flags=re.M|re.DOTALL)
my_dict = dict((k,v.strip('"')) for k,v in pat.findall(txt))

rawDescription: How to parse this web page (and convert into a dictionary) in Python

description: Parse this web page (and convert into a dictionary) in Python


code:
import time,pytz
timezone = pytz.timezone('America/New_York')
local_dt = timezone.localize(dt)

rawDescription: Convert datetime object in a particular timezone to epoch seconds in that timezone


code:
import numpy as np

x = np.arange(6)
x2 = x[2:]

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code: lines = [line.decode(sys.stdin.encoding) for line in sys.stdin]

rawDescription: Python regex with devanAgarI

description: Python regex with devanAgarI


code:
# copied directly from the proposed fix
def monkey_patch_init(self, fig, func, frames=None, init_func=None, fargs=None,
             save_count=None, **kwargs):
    if fargs:
        self._args = fargs
    else:
        self._args = ()
    self._func = func

    # Amount of framedata to keep around for saving movies. This is only
    # used if we don't know how many frames there will be: in the case
    # of no generator or in the case of a callable.
    self.save_count = save_count

    # Set up a function that creates a new iterable when needed. If nothing
    # is passed in for frames, just use itertools.count, which will just
    # keep counting from 0. A callable passed in for frames is assumed to
    # be a generator. An iterable will be used as is, and anything else
    # will be treated as a number of frames.
    if frames is None:
        self._iter_gen = itertools.count
    elif six.callable(frames):
        self._iter_gen = frames
    elif iterable(frames):
        self._iter_gen = lambda: iter(frames)
        if hasattr(frames, '__len__'):
            self.save_count = len(frames)
    else:
        self._iter_gen = lambda: xrange(frames).__iter__()
        self.save_count = frames

    # If we're passed in and using the default, set it to 100.
    if self.save_count is None:
        self.save_count = 100

    self._init_func = init_func

    # Needs to be initialized so the draw functions work without checking
    self._save_seq = []

    TimedAnimation.__init__(self, fig, **kwargs)

    # Need to reset the saved seq, since right now it will contain data
    # for a single frame from init, which is not what we want.
    self._save_seq = []

rawDescription: matplotlib animation FuncAnimation frames argument

description: Matplotlib animation FuncAnimation frames argument


code: any(Hamming_distance(genome[x:x+25], sequence) == 1 for x in xrange(len(genome)))

rawDescription: Search for string allowing for one mismatch in any location of the string


code:
mode = get_mode()
message = get_message()
key = get_key()

print('Your translated text is: ', get_translated_message(mode, message, key))

rawDescription: Caesar Cipher validation

description: Caesar Cipher validation


rawDescription: Python 2.7 formatting data for writing as csv


code: [combo[key] for key in combo.viewkeys() & numb]

rawDescription: Printing the values of a dictionary when its key is equal to the value of a list element


code:
def to_nested_dict(list_dict):
    d = {}                                   # initialize the outer dict
    for k, lst in list_dict.items():
        d[k] = {}                            # initialize inner dicts
        for x, y in lst:
            d[k].setdefault(x, []).append(y) # initialize and populate innermost list
    return d

rawDescription: create dictionary from list same values

description: Create dictionary from list same values


code: df = pd.read_csv('data', sep=r',')

rawDescription: Pandas date range to single dates

description: Pandas date range to single dates


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

data = [np.random.normal(0, std, 1000) for std in range(1, 6)]

box = plt.boxplot(data, notch=True, patch_artist=True)

colors = ['cyan', 'lightblue', 'lightgreen', 'tan', 'pink']
for patch, color in zip(box['boxes'], colors):
    patch.set_facecolor(color)

plt.show()

rawDescription: python matplotlib filled boxplots

description: Python matplotlib filled boxplots


code:
import dateutil.parser
sorted(data, key=lambda x: dateutil.parser.parse(x[6]))

rawDescription: Sorting a list of different values by a specific field


rawDescription: validate rows before computing values using python/pandas DataFrame

description: Validate rows before computing values using python/pandas DataFrame


code:
nums=[int(x) for x in num_str.split(",")]
zip(*[iter(nums)]*2)

description: Python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]


rawDescription: Dynamically escape % sign and brackets { } in a string


code:
catnames = rasterband.GetCategoryNames()
memdriver = ogr.GetDriverByName( 'Memory' )
dst_ds = memdriver.CreateDataSource( "out" )

# create a layer with a DN field that will contain the index of
# each category automatically
dst_layer = dst_ds.CreateLayer("out", srs = None )
fd = ogr.FieldDefn( 'DN', ogr.OFTInteger )
dst_layer.CreateField(fd)

gdal.Polygonize( rasterband, None, dst_layer, 0)

# extract features map
featmap = {}
for feature in dst_layer:
    # use the field defined above, create a mapping between
    # index -> feature name
    featname = feature.GetField("DN")
    if featname not in featmap.keys():
        featmap[featname] = [feature]
    else:
        featmap[featname].append(feature)

rawDescription: Convert grc file to shp file using category names


code:
stripped_value = '''Some sentence. And another.
Multiline text works too! And commas, they are included; but not the semicolon?
'''
import re
re.findall(r'([A-Z].*?)[.!?;]', stripped_value, re.MULTILINE | re.DOTALL | re.UNICODE)

rawDescription: python, regex find a subsentence, exclude bounaries

description: Python, regex find a subsentence, exclude bounaries


code:
class Download(webapp.RequestHandler):
        def get(self, photo_id):
            photo= db.get(db.Key(photo_id))
            if photo:
                self.response.headers['Content-Type'] = "image/jpeg"
                self.response.out.write(photo.imageblob)
            else:
                self.response.out.write("Image not available")

rawDescription: Python app engine: how to save a image?

description: Python app engine: how to save a image


code: query = """insert into XXXXXXXXXXXX("XXXXXXXXXX", "XXXXXXXXX", "XXXXXXXXXXX") values(?,?,?)"""

rawDescription: how to transform pandas dataframe for insertion via executemany() statement?

description: Transform pandas dataframe for insertion via executemany() statement


code: edge_index = np.unravel_index(binnumber, [len(edge)-1 for edge in bin_edges])

rawDescription: How to find bin edges of given bin number returned by scipy.stats.binned_statistic_dd()?

description: Find bin edges of given bin number returned by scipy.stats.binned_statistic_dd()


code:
df[["C", "D"]] = df.applymap(names.get)
df

rawDescription: Assign unique id to columns pandas data frame


rawDescription: Filter out rows/columns with zero values in MultiIndex dataframe


code: [f[1:-1] for f in re.findall('".+?"', input)]

rawDescription: Python split string on quotes

description: Python split string on quotes


code: k = s.index('\r')

rawDescription: How do I get the length of the first line in a multi line string?

description: Get the length of the first line in a multi line string


code: soup.body.findAll(text='Python Jobs')

rawDescription: Using BeautifulSoup to search html for string


code: get_vars('%(code)s - %(description)s - %(age)d - %(weight)f')

rawDescription: Python: extract all placeholders from format string


code:
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode

key64 = 'MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k\
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+znJDEbNHOD\
ZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE='

keyDER = b64decode(key64)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct( (seq[0], seq[1]) )

rawDescription: How to read a RSA public key in PEM + PKCS#1 format

description: Read a RSA public key in PEM + PKCS#1 format


code: msgImage = MIMEImage(fp.read(), filename='filename')

rawDescription: Naming inline images when sending HTML mails with Python's email.mime.multipart


rawDescription: How simple list functions could be implemented in Python


code:
from itertools import islice
server3 = ['g', 'h', 'i', 'j']
list(islice(cycle_through_servers(server1, server2, server3), 0, 20))

rawDescription: cycle through multiple list using itertools.cycle()

description: Cycle through multiple list using itertools.cycle()


code:
def holes_between(intervals):
    prec = intervals[0][1] + 1 # Bootstrap the iteration
    result = []
    for low, high in intervals[1:]:
        if prec <= low - 1:
            result.append((prec, low - 1))
        prec = high + 1
    return result

rawDescription: Can Python yield into a list be made more efficient?


code:
21,
2,
'23.5R25 ETADT',
'description, with a comma'

rawDescription: Anchor to End of Last Match

description: Anchor to End of Last Match


code: zip(lst, lst[1:])

rawDescription: How to group a list into inclusive sequential n-tuples

description: Group a list into inclusive sequential n-tuples


rawDescription: From Matlab to Python - Solve function

description: From Matlab to Python - Solve function


code:
aList = [[olditem, olditem], [newitem, newitem]]
                           # ^ aList[0]

rawDescription: creating a dict iterating through two nested loops and a JSON output

description: Creating a dict iterating through two nested loops and a JSON output


rawDescription: python logistic regression (beginner)

description: Python logistic regression (beginner)


rawDescription: Recursion - how do you extract from specific traversals


code:
def is_unique(iterable):
    seen = set()
    seen_add = seen.add
    for element in iterable:
        if element in seen:
            return False
        seen_add(element)
    return True

rawDescription: Python Check If List Is a Mathematical Set Fast


rawDescription: Protection against downloading too big files


code:
query = 'select blah from table where blah = blahblah and ({})'.format(
    ' or '.join(['text like %s'] * len(text_list)))

rawDescription: Unpack python list to pass to a MySQL WHERE clause?


code:
import difflib

def similar(seq1, seq2):
    return difflib.SequenceMatcher(a=seq1.lower(), b=seq2.lower()).ratio() > 0.9

def unique(mylist, keys):
    temp = mylist[:]
    for d in mylist:
        temp.pop(0)
        [d2.pop(i) for i in keys if d.has_key(i)
         for d2 in temp if d2.has_key(i) and similar(d[i], d2[i])]
    return mylist

rawDescription: How to uniquefy a list of dicts based on percentage similarity of a value in the dicts

description: Uniquefy a list of dicts based on percentage similarity of a value in the dicts


code:
all_b_values = [t.b for t in list_of_named_tuples]
all_a_values = [t.a for t in list_of_named_tuples]

rawDescription: get all with same name and value in tuple using named tuple

description: Get all with same name and value in tuple using named tuple


code:
l=[v for (k,v) in Transitions.iteritems() if k[1] == 3]
sum(l)

rawDescription: Sum values of a dictionary

description: Sum values of a dictionary


code: [values for key, values in rev_multidict.items() if len(values) > 1]

rawDescription: Find dictionary keys with duplicate values


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

fig, ax = plt.subplots()

ax.axis('equal')
ell = Ellipse(xy=[0,0], width=30, height=10, angle=0,
              edgecolor='b', lw=4, fill=False)

ax.add_artist(ell)
ax.set(xlim=[-100, 100], ylim=[-100, 100])

plt.show()

rawDescription: Can't plot ellipse in python without fillcolor


code:
s, t = 'acegikmoqsuwy\nbdfhjlnprtvxz', 'bdfhjlnprtvxzacegikmoqsuwy'
from itertools import zip_longest
print(''.join(a + b for a, b in zip_longest(s, t, fillvalue='')))

rawDescription: How you can unite-merge parts of a sliced string?


code:
from itertools import groupby
st = "abcdefghijklm"
some_list = [1,1,0,0,0,1,1,1,0,0,0,1,0]
it_l = iter(some_list)
[''.join(v) for k, v in groupby(st, key = lambda e:next(it_l)) if k]

rawDescription: Match character from string with binary list


code: '. '.join([s.strip().capitalize() for s in 'this is a sentence. this is another.'.split('.')]).strip()

rawDescription: Title case for a paragraph

description: Title case for a paragraph


code: [L[i] for i in range(0,len(L), 14)]

rawDescription: Array generation from a list in python

description: Array generation from a list in python


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


code:
from collections import defaultdict
l = [{'row':1}, {'row':2}, {'row':1}, {'row':3}, {'row':1}]
ret = defaultdict(list)
for d in l:
    ret[d['row']].append(d)
ret.values() # list(d.values())   in Python 3.x

rawDescription: convert list of dict into list of list of dict

description: Convert list of dict into list of list of dict


code:
indices = {}
for i, e in enumerate(b):
    indices[e] = i                      # if elements in b are unique
    indices.setdefault(e, []).append(i) # otherwise, use lists

rawDescription: large array searching with numpy

description: Large array searching with numpy


code: form = AccountSettingsForm(request.POST, obj=request.user)

rawDescription: WTForms and Django OneToOneFields

description: WTForms and Django OneToOneFields


code: (N, COLOR)

rawDescription: main color detection in Python

description: Main color detection in Python


code:
import time

BOT_NAME = "test"
FEED_URI = '%(name)s--%(time)s.csv'
LOG_FILE = "%s--%s.log" % (BOT_NAME, time.strftime('%Y-%m-%dT%H-%M-%S'))

rawDescription: Scrapy - using URI parameters for logging file


code:
def getAlphaOfPixel(self, t):
    mx,my = pygame.mouse.get_pos()
    x,y = self.getCordInImage(mx,my,t.IMAGE)
    #mask = pygame.mask.from_surface(t.IMAGE.image)
    return t.IMAGE.image.get_at([x,y])[3]

rawDescription: Python pygame Detect if mouse is over non transparent part of surface


code:
for index, row in enumerate(tableau, start=1):
    print('Row {index} : {row}'.format(index=index, row=' '.join(row)))

rawDescription: How to print on the same line in a loop?

description: Print on the same line in a loop


code:
seen = set()
for x, y, label in zip(xs, ys, labels):
    plt.scatter(x, y, c=label_dict.get(label), label=legend_dict.get(label) if label not in seen else None)
    seen.add(label)

rawDescription: Depict legend without repeats

description: Depict legend without repeats


code:
import os
import sys
import SimpleHTTPServer
import BaseHTTPServer

class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if not self.redirect():
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    def do_HEAD(self):
        if not self.redirect():
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self)

    def redirect(self):
        path = self.translate_path(self.path)
        if os.path.isdir(path):
            for base in "index", "default":
                for ext in ".html", ".htm", ".txt":
                    index = base+ext
                    index_path = os.path.join(path, index)
                    if os.path.exists(index_path):
                        new_path = self.path
                        if not new_path.endswith('/'):
                            new_path += '/'
                        new_path += index

                        self.send_response(302)
                        self.send_header("Location", new_path)
                        self.end_headers()
                        return True
        return False

def test(HandlerClass = MyHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    test()

rawDescription: SimpleHTTPServer add default.htm default.html to index files


code:
from itertools import chain
from collections import Counter
Counter(chain.from_iterable(words))

rawDescription: How to create a list from splitting a list elements in python?

description: Create a list from splitting a list elements in python


code: (some|word)

rawDescription: replace multiple words - python

description: Replace multiple words - python


code: form = TimeSearchForm(initial={'username': request.META['REMOTE_USER']})

rawDescription: Default value of a form in Django using REMOTE_USER


code:
import collections
c = collections.Counter()
for x in lst:
    c.update(dict(x))
print(c.most_common(2))

rawDescription: What is the fastest way to combine and sort lists of tuples?


code:
a = [1,2,3,4,5] # list
b = set(a) # conversion to set

rawDescription: writing a nested dictionary to csv file

description: Writing a nested dictionary to csv file


rawDescription: establish begin/end dates via groupby

description: Establish begin/end dates via groupby


rawDescription: Python Downloading Data File from Web-Scraped URL


code:
for i, members in enumerate(members_lists):
    for j, member in enumerate(members):
        member["priority"] = members_priorites_lists[i][j]
return render(request, "main.html", {"members": zip(pools_list, members_lists)})

rawDescription: Combining lists values for displaying in django template


code:
def order_and_strip(d):
    sorted_items = sorted(d.items(), key=lambda kv: len(kv[-1]), reverse=True)
    seen = set()
    for key, value in sorted_items:
        yield key, list(set(value) - seen)
        seen.update(value)

rawDescription: Dictionary with sorted unique values

description: Dictionary with sorted unique values


rawDescription: Can I convert any string to float without losing precision in Python?

description: Convert any string to float without losing precision in Python


code:
# Python 2
from abc import ABCMeta, abstractmethod
class Abstract:
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass

rawDescription: Is it possible to make abstract classes in python?


rawDescription: Negating previously matched word group

description: Negating previously matched word group


code: user = int(raw_input('> '))

rawDescription: Python simple number comparison

description: Python simple number comparison


code: defaultdict(lambda: None)

rawDescription: Accessing self from outside of a class

description: Accessing self from outside of a class


code:
future = pd.DataFrame()
for i in range(5):
    for season in ['winter', 'spring', 'summer', 'autumn']:
        future = future.append(df2.loc[random.choice(range(2007, 2015))]
                                  .loc[season])

rawDescription: Selecting time-series data in a specific sequence using pandas


rawDescription: Concatenating list of dictionaries

description: Concatenating list of dictionaries


code:
from functools import wraps

def somedec(somearg, someopt=None):
    def somedec_outer(fn):
        @wraps(fn)
        def somedec_inner(*args, **kwargs):
            # do stuff with somearg, someopt, args and kwargs
            response = fn(*args, **kwargs)
            return response
        return somedec_inner
    return somedec_outer

rawDescription: python wrapper function taking arguments inside decorator

description: Python wrapper function taking arguments inside decorator


code:
import pylab
axes = pylab.axes()
circle1 = pylab.Circle((0,0), radius=20, alpha=.5)
circle2 = pylab.Circle((0.5,0.5), radius=20, alpha=.5)
axes.add_patch(circle1)
axes.add_patch(circle2)
pylab.axis('scaled')
pylab.show()

rawDescription: Plot/scatter position and marker size in the same coordinates


code:
utc = dateutil.tz.tzutc()
print(current_time.astimezone(utc))
# 2013-05-12 13:03:19.368122+00:00

rawDescription: Get new datetime object according to timezone difference


code:
def load_global(self):
    module = self.readline()[:-1]
    name = self.readline()[:-1]
    print("module {} name {}".format(module, name))  # I added this.
    klass = self.find_class(module, name)
    self.append(klass)

rawDescription: Why would it throws "'module' object has no attribute XXX" error when I call on apply_async from multiprocessing.Pool?


code:
import re
dirExclude = set(['amip4K','amip4xCO2','aqua4K','aqua4xCO2'])
exre = re.compile(r'decadal[0-9]{4}')
for (path,dirs,files) in os.walk(inpath,topdown=True):
     dirs = [d for d in dirs if d not in dirExclude and not exre.search(d)]
     # Do something

rawDescription: Create list using regex inputs

description: Create list using regex inputs


code:
{'Johnsons': {'Chicken': 3, 'Steak': 2, 'Veggie': 1},
 'Martins': {'Fish': 2, 'Steak': 1},
 'Smiths': {'Veggie': 4}}

rawDescription: Organizing and printing information by a specific row in a csv file


code:
arr
blockshaped(arr[:,:4], 2,2)
blockshaped(arr[:,:4], 2,2).shape

rawDescription: Sums of subarrays

description: Sums of subarrays


rawDescription: Python - How to sort a dictionary based on its value as well it key


code:
h = .02  # step size in the mesh
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

rawDescription: Multilayer-perceptron, visualizing decision boundaries (2D) in Python


code:
lst_2d = [[0] * 3 for i in xrange(3)]
lst_2d
lst_2d[0][0] = 5
lst_2d

rawDescription: Short (and useful) python snippets

description: Short (and useful) python snippets


code:
rqIndexLck = threading.Lock() # Protects the access to `rqIndex`
rqIndex = {} # Maps handles to request objects sets.

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


rawDescription: Combining nested collection in mongodb with documents written from parallel nodes


code:
import hdf5storage # get code on https://pypi.python.org/pypi/hdf5storage/0.1.3
import numpy as np

matcontent = {}
matcontent[u'some_numbers'] = np.array([10, 50, 20]) # each key must be a unicode string
hdf5storage.write(matcontent, '.', 'test2.mat', matlab_compatible=True)

rawDescription: Create .mat v7.3 files from Python using hdf5storage


code:
import email

msg = email.message_from_string(request.get('mail'))

rawDescription: Process received email with Python or Django?


rawDescription: Python list not printing as desired

description: Python list not printing as desired


code: ['bear', 'fox', 'jackie chan',]

rawDescription: Transform sequence of lines into python list, using Vim?


code:
import requests
import unittest
import responses

class Foo(object):
    def __init__(self, uri):
        self.uri = uri

    def __iter__(self):
        payload = {"op": "OPEN"}
        response = requests.get("http://" + self.uri, params=payload,
                                stream=True)
        return response.iter_lines()

class TestFoo(unittest.TestCase):
    @responses.activate
    def test_iter_lines(self):
        responses.add(responses.GET, "http://local.host/", body='abc\n123')
        r = iter(Foo("local.host"))
        self.assertEqual(r.next(), "abc")
        self.assertEqual(r.next(), "123")

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

rawDescription: Python mocking requests.get content and iter_lines()


code:
def face_normal(face):
    vtxface = cmds.polyListComponentConversion(face, tvf = True)
    xes = cmds.polyNormalPerVertex(vtxface, q=True, x =True)
    yes = cmds.polyNormalPerVertex(vtxface, q=True, y =True)
    zes = cmds.polyNormalPerVertex(vtxface, q=True, z =True)
    divisor = 1.0 / len(xes)
    return sum(xes)* divisor, sum(yes)  * divisor, sum(zes) * divisor

rawDescription: How to get face normals average in Maya?

description: Get face normals average in Maya


code:
from Tkinter import *
import ystockquote
import urllib.request
from urllib.request import urlopen
from bs4 import BeautifulSoup

"""

I am adding comments so that if
you need help from stackoverflow
on this again they will know whats
what because it took me a looooong time

"""

class Shares(Frame):
# Main page to display gain/loss on different shares
    def __init__(self, master):
        Frame.__init__(self, master)

        Frame.__init__(self, master)
        self.frame = Frame(master, bg = "#ededed")
        self.frame.grid(row = 9, column = 0)
        self.canvas = Canvas(self.frame, bg = "#ffffff")
        self.data_frame = Frame(self.canvas, bg = "#ffffff")
        self.vscrollbar = Scrollbar(self.frame, orient = "vertical", command = self.canvas.yview)
        self.canvas.configure(yscrollcommand = self.vscrollbar.set)
        self.vscrollbar.grid(row = 9, column = 11, sticky = NS)
        self.canvas.config(width = 1210, height = 200)
        self.canvas.grid(row = 9, column = 0, columnspan = 11, sticky = E)
        self.canvas.create_window((0, 0), window = self.data_frame, anchor = "nw", tags = "self.frame")
        self.data_frame.bind("<Configure>", self.onFrameConfig)

        self.data_frame.grid_columnconfigure(0, minsize = 352)
        self.data_frame.grid_columnconfigure(1,  minsize = 96)
        self.data_frame.grid_columnconfigure(2,  minsize = 96)
        self.data_frame.grid_columnconfigure(3,  minsize = 96)
        self.data_frame.grid_columnconfigure(4,  minsize = 96)
        self.data_frame.grid_columnconfigure(5,  minsize = 96)
        self.data_frame.grid_columnconfigure(6,  minsize = 96)
        self.data_frame.grid_columnconfigure(7,  minsize = 96)
        self.data_frame.grid_columnconfigure(8,  minsize = 96)
        self.data_frame.grid_columnconfigure(9,  minsize = 96)

        master.bind("<Return>", self.company_details)

        Label(self.frame, bg = "#ededed", font = "Helvetica 20", text = "Enter ASX Code").grid(row = 0, column = 0, sticky = W, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", font = "Helvetica 20", text = "Current Price").grid(row = 2, column = 0, sticky = W, padx = 5, pady = 5)

        self.entryVar = StringVar()
        Entry(self.frame, width = 12, font = "Helvetica 20", textvariable = self.entryVar).grid(row = 0, column = 1, padx = 5, pady = 5)

        self.companyVar = StringVar()
        Label(self.frame, font = "Helvetica 20", textvariable = self.companyVar).grid(row = 1, column = 0, columnspan = 2, sticky = W, padx = 5, pady = 5)

        self.priceVar = DoubleVar()
        Label(self.frame, font = "Helvetica 20", textvariable = self.priceVar).grid(row = 2, column = 1, sticky = W, padx = 5, pady = 5)
        self.priceVar.set("")

        Label(self.frame, bg = "#ededed", font = "Helvetica 20", text = "Current Action").grid(row = 3, column = 0, sticky = W, padx = 5, pady = 5)

        Label(self.frame, bg = "#ededed", font = "Helvetica 20", text = "Current Holdings").grid(row = 7, column = 0, pady = 5)

        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Name").grid(row = 8, column = 0, columnspan = 2, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Code").grid(row = 8, column = 2, padx = 5, pady = 5, sticky = E)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Buy Date").grid(row = 8, column = 3, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Quantity").grid(row = 8, column = 4, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Paid").grid(row = 8, column = 5, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Brokerage").grid(row = 8, column = 6, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Total").grid(row = 8, column = 7, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Current").grid(row = 8, column = 8, padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Total").grid(row = 8, column = 9,padx = 5, pady = 5)
        Label(self.frame, bg = "#ededed", width = 10, font = "Helvetica 14 bold", text = "Loss/Gain").grid(row = 8, column = 10, padx = 5, pady = 5)

        Label(self.frame, bg = "#ededed", text = "Amount").grid(row = 16, column = 10, padx = 5, pady = 5, sticky = E)
        Label(self.frame, bg = "#ededed", text = "Amount").grid(row = 16, column = 9, padx = 5, pady = 5, sticky = E)
        Label(self.frame, bg = "#ededed", text = "Amount").grid(row = 16, column = 8, padx = 5, pady = 5, sticky = E)

        Button(self.frame, width = 11, text = "New Record", command = self.new_record).grid(row = 16, column = 0, padx = 5, pady = 5, sticky = E)
        #Button(self.frame, width = 11, text = "Modify Record", command = self.new_record).grid(row = 16, column = 1, padx = 5, pady = 5)
        Button(self.frame, width = 11, text = "Delete Record", command = self.delete_record).grid(row = 16, column = 2, padx = 5, pady = 5, sticky = E)

        self.rows = 0

        self.code_list = {}
# Function to validate Australian company codes
    def validate_code(self):
        soup = BeautifulSoup(urllib.request.urlopen("https://au.finance.yahoo.com/q?s=" + (self.code_entry.get() + ".AX")).read(), "html.parser")
        element = soup.find("div", ("class", "title"))
        name = element.find("h2")
        self.name_entry.set(name.text[:-9])
# Adding a new company
    def new_record(self):
        top = self.top = Toplevel()

        top.bind("<Return>", self.add)

        Label(top, text = "Code: ").grid(row = 0, column = 0, sticky = E, padx = 5, pady = 5)
        Label(top, text = "Name: ").grid(row = 2, column = 0, sticky = E, padx = 5, pady = 5)
        Label(top, text = "Buy Date: ").grid(row = 3, column = 0, sticky = E, padx = 5, pady = 5)
        Label(top, text = "Quantity: ").grid(row = 4, column = 0, sticky = E, padx = 5, pady = 5)
        Label(top, text = "Paid: ").grid(row = 5, column = 0, sticky = E, padx = 5, pady = 5)
        Label(top, text = "Brokerage: ").grid(row = 6, column = 0, sticky = E, padx = 5, pady = 5)

        self.name_main = StringVar()

        self.name_entry = StringVar()
        Entry(top, textvariable = self.name_entry).grid(row = 2, column = 1, padx = 5, pady = 5)
        self.name_entry.set("")

        self.code_main = StringVar()

        self.code_entry = StringVar()
        Entry(top, textvariable = self.code_entry, validatecommand = self.validate_code).grid(row = 0, column = 1, padx = 5, pady = 5)
        self.code_entry.set("")

        self.date_main = StringVar()

        self.date_entry = StringVar()
        Entry(top, textvariable = self.date_entry).grid(row = 3, column = 1, padx = 5, pady = 5)
        self.date_entry.set("")

        self.quantity_main = IntVar()

        self.quantity_entry = IntVar()
        Entry(top, textvariable = self.quantity_entry).grid(row = 4, column = 1, padx = 5, pady = 5)
        self.quantity_entry.set("")

        self.paid_main = DoubleVar()

        self.paid_entry = DoubleVar()
        Entry(top, textvariable = self.paid_entry).grid(row = 5, column = 1, padx = 5, pady = 5)
        self.paid_entry.set("")
        self.frames=[]
        self.column=0

        self.brokerage_main = DoubleVar()

        self.brokerage_entry = DoubleVar()
        Entry(top, textvariable = self.brokerage_entry).grid(row = 6, column = 1, padx = 5, pady = 5)
        self.brokerage_entry.set(29.95)
        #
        self.total_main = DoubleVar()

        self.current_main = DoubleVar()

        self.total_two_main = DoubleVar()

        self.loss_gain_main = DoubleVar()

        self.frames.append(Frame(self.data_frame))
        self.frames[-1].grid()
        Label(self.frames[-1], textvariable=self.name_main).grid(row=self.rows, column=1)
        Label(self.frames[-1], textvariable=self.code_main).grid(row=self.rows, column=2)
        Label(self.frames[-1], textvariable=self.date_main).grid(row=self.rows, column=3)
        Label(self.frames[-1], textvariable=self.quantity_main).grid(row=self.rows, column=4)
        Label(self.frames[-1], textvariable=self.paid_main).grid(row=self.rows, column=1)
        Label(self.frames[-1], textvariable=self.brokerage_main).grid(row=self.rows, column=6)
        Label(self.frames[-1], textvariable=self.total_main).grid(row=self.rows, column=7)
        Label(self.frames[-1], textvariable=self.current_main).grid(row=self.rows, column=8)
        Label(self.frames[-1], textvariable=self.total_two_main).grid(row=self.rows, column=9)
        Label(self.frames[-1], textvariable=self.loss_gain_main).grid(row=self.rows, column=10)
        self.rows+=1

        Button(top, text = "Validate code", command = self.validate_code).grid(row = 1, column = 1, padx = 5, pady = 5)

        Button(top, text = "Add", command = self.add).grid(row = 7, column = 1, sticky = W, padx = 5, pady = 5)

        Button(top, text = "Cancel", command = self.cancel).grid(row = 7, column = 1, sticky = E, padx = 5, pady = 5)

    def add(self, event = None):
        self.rows += 1
        self.code_list[self.code_entry.get()]=self.frames[-1]
        code = str.upper(self.code_entry.get())
        self.code_main.set(code)
        self.name_main.set(self.name_entry.get())
        self.date_main.set(self.date_entry.get())
        self.quantity_main.set(self.quantity_entry.get())
        paid = self.paid_entry.get()
        self.paid_main.set("$%.2f" % paid)
        brokerage = self.brokerage_entry.get()
        self.brokerage_main.set("$%.2f" % brokerage)
        total = self.quantity_entry.get() * self.paid_entry.get() + self.brokerage_entry.get()
        self.total_main.set("$%.2f" % total)
        self.current_main.set("$" + str(ystockquote.get_price(self.code_entry.get() + ".AX")))
        curent_main = float(ystockquote.get_price(self.code_entry.get() + ".AX"))
        total_two = self.current_main * self.quantity_entry.get()
        self.total_two_main.set("$%.2f" % total_two)
        rounded = ((total_two / total * 100) - 100)
        self.loss_gain_main.set("%.2f" % rounded + "%")
        self.top.destroy()

    def cancel(self, event = None):
        self.top.destroy()

    def delete_record(self):
        top = self.top = Toplevel()

        top.bind("<Return>", self.delete)

        Label(top, text = "Please enter code of record to be deleted: ").grid(row = 0, column = 0, sticky = E, padx = 5, pady = 5)

        self.code_entry_delete = StringVar()
        Entry(top, textvariable = self.code_entry_delete).grid(row = 0, column = 1, padx = 5, pady = 5)
        self.code_entry_delete.set("")

        Button(top, text = "Delete Record", command = self.delete).grid(row = 1, column = 1, padx = 5, pady = 5)
        Button(top, text = "Cancel", command = self.cancel).grid(row = 1, column = 0, padx = 5, pady = 5)

    def delete(self, event = None):
        if self.code_entry_delete.get() in self.code_list:
            self.code_list[self.code_entry_delete.get()].destroy()

    def company_details(self, event):
        self.priceVar.set("$" + (ystockquote.get_price(self.entryVar.get() + ".AX")))

        soup = BeautifulSoup(urllib.request.urlopen("https://au.finance.yahoo.com/q?s=" + (self.entryVar.get() + ".AX")).read(), "html.parser")
        element = soup.find("div", ("class", "title"))
        name = element.find("h2")
        self.companyVar.set(name.text[:-9])

    def onFrameConfig(self, event):
        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

if __name__ == "__main__":
    master = Tk()
    master.title("Share Program")
    app = Shares(master)
    master.geometry("1235x528+20+40")
    master.mainloop()

rawDescription: How to delete a specific row of label widgets in tkinter app

description: Delete a specific row of label widgets in tkinter app


code: entities['hashtags']

rawDescription: Python Json loads() returning string instead of dictionary?


code:
for item in foo_now():
    with open("my_out.json","ab") as f:
        json.dump(item,f)

rawDescription: Stream to JSON file using yield

description: Stream to JSON file using yield


code: vertices = numpy.empty(1000, dtype=vertex_dtype)

rawDescription: A way to pass milions of items in python to C program many times in rapid succesion


code:
three_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=3)
tweets = list(connection.my_database.my_collection.find({
    'created_at': { '$gte': three_days_ago }
}).sort([('created_at', pymongo.DESCENDING)]))

rawDescription: How do I compare dates from Twitter data stored in MongoDB via PyMongo?

description: Compare dates from Twitter data stored in MongoDB via PyMongo


code:
from celery import current_app
all_task_names = current_app.tasks.keys()
all_tasks = current_app.tasks.values()
foo_task = current_app.tasks['tasks.foo']

all_task_classes = [type(task) for task in current_app.tasks.itervalues()]

rawDescription: How to get all tasks and periodic tasks in Celery

description: Get all tasks and periodic tasks in Celery


code:
('apple', 'orange', 'cucumber', 'onion', 'soda', 12)
('banana', 'orange', 'tomato', 'onion', 'soda', 12)
('banana', 'orange', 'cucumber', 'onion', 'juice', 12)
('banana', 'orange', 'cucumber', 'onion', 'soda', 13)

rawDescription: python - check if permutation exists/combination is unique

description: Python - check if permutation exists/combination is unique


code:
import re

def make_dict(s):
    # break into list of keys and values
    chunks = re.split("\s*(\w+\:)\s*", s)
    res = {}
    # work backwards in value,key pairs
    args = [reversed(chunks)] * 2
    for value,key in zip(*args):
        key = key.rstrip(':')
        if value:
            # add to current result-dict
            res[key] = value
        else:
            # start a higher-level result-dict
            res = {key: res}
    return res

rawDescription: Dictionary like operations on string in python3


code:
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('dyn_display', kwargs={'category': 'first'}))

rawDescription: pass kwargs for the view in reverse; django 1.5

description: Pass kwargs for the view in reverse; django 1.5


code:
import decimal
my_float = decimal.Decimal("0.2342134235")
my_float

rawDescription: Python extending decimals

description: Python extending decimals


code: nltk.tokenize.RegexpTokenizer("[\\w']+|[^\\w\\s]+").tokenize("Let's check this out.")

rawDescription: Preserving contractions with textblob ngrams


code:
def p_dynamics(p):
    'DYNAMICS BLOCK END_DYNAMICS'

rawDescription: Identifying keyword pairs in lex

description: Identifying keyword pairs in lex


code: {'Column B': ['Item B1', 'Item B2', 'Item B3'], 'Column C': ['Item C1', 'Item C2', 'Item C3'], 'Column A': ['Item A1', 'Item A2', 'Item A3']}

rawDescription: How can I create a nested list from an existing one where the first x items are the outer items?

description: Create a nested list from an existing one where the first x items are the outer items


code:
#!/usr/bin/env python
nonascii = bytearray(range(0x80, 0x100))
with open('d.txt','rb') as infile, open('d_parsed.txt','wb') as outfile:
    for line in infile: # b'\n'-separated lines (Linux, OSX, Windows)
        outfile.write(line.translate(None, nonascii))

rawDescription: Python read from file and remove non-ascii characters


rawDescription: Reverting from multiindex to single index dataframe in pandas


code:
from itertools import groupby, chain

def consec(l):
    for ind,  (k, v) in enumerate(groupby(l)):
        lst = list(v)
        if len(lst) > 1 or lst[0] or ind == 0:
            yield lst
    if len(lst) == 1 and not lst[0]:
        yield lst

rawDescription: How to remove blank element in between non-blank elements in list?

description: Remove blank element in between non-blank elements in list


code:
class GlobalReference(object):
    def __init__(self, name):
        self.name = name
    def get(self):
        return globals()[self.name]
    def set(self, value):
        globals()[self.name] = value

ref_dict = {'field1': GlobalReference('a'), 'field2': GlobalReference('b')}
def update(field, value):
    ref_dict[field].set(value)

rawDescription: python reference to a float, int, etc

description: Python reference to a float, int, etc


code:
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    about = models.TextField(default='')

rawDescription: Getting logged in User's Profile in Django without repeating request.user a lot?


rawDescription: For-loop to fill in node positions in an array for a cube


code:
file1.py
import file2

username = "steven"

file2.action(username)

rawDescription: Calling variables from other files in Python


code:
import threading
import time

X = 2

def function():
    print("Thread {} starting.".format(threading.current_thread()))
    threading.Timer(X, function).start()
    time.sleep(2*X)
    print("Thread {} done.".format(threading.current_thread()))

function()

rawDescription: Python threading timer

description: Python threading timer


rawDescription: Python: get items from list between 2 known items


rawDescription: JSONEncoder subclass to return actual JSON representation, not serializable object


code:
def tuple_index(nested_list, index_tuple):
    for i in index_tuple:
        nested_list = nested_list[i]
    return nested_list

rawDescription: Navigate manually with a cursor through nested lists by only providing "left()" and "right()" as commands?


code: A = B = np.zeros((len(X), len(X)))

rawDescription: Looped vs Bulk arithmetic

description: Looped vs Bulk arithmetic


code:
import re
p = re.compile(r"(\b[-']\b)|[\W_]")
test_str = "No -  d'Ante compactified on a calabi-yau threefold @ ,."
result = p.sub(lambda m: (m.group(1) if m.group(1) else " "), test_str)
print(result)

rawDescription: Removing punctuation except intra-word dashes Python


code:
import string
import collections

def vigsquare(printable=False):
    '''
    Returns a string like a vigenere square,
    printable joins each row with a newline so it's literally square
    printable=False (defaul) joins without newlines for easier
    searching by row and column index
    '''
    alpha = string.ascii_uppercase
    rotater = collections.deque(alpha)
    vigsquare_list = []
    for i in xrange(26):
        vigsquare_list.append(''.join(rotater))
        rotater.rotate(-1)
    if printable:
        return '\n'.join(vigsquare_list)
    else:
        return ''.join(vigsquare_list)

rawDescription: For Kasiski Test,How to implement 26x26 table in Python


code: ['Joe', 'Dave', 'Professional, Ph.D.', 'Someone else']

rawDescription: python regex to split on certain patterns with skip patterns

description: Python regex to split on certain patterns with skip patterns