code:
d1 = {"a":[1,2,3]}
d2 = {"b":[4,5,6]}
l1=["d1","d2"]

for d in l1:
    for k,v in globals()[d].items(): #or simply d.items() if the values in l1 are references to the dictionaries
        print("Dictionray {0}, under key {1} contains:".format(d,k))
        for e in v:
            print("\t{0}".format(e))

rawDescription: Access dictionary from a list

description: Access dictionary from a list


code: iter(lambda: list(IT.islice(iterator, 10)), [])

rawDescription: How to get chunks of elements from a queue?

description: Get chunks of elements from a queue


code:
for line in process:
    if "process.control.timeout" in line:
        # You need to include a newline if you're replacing the whole line
        line = "process.control.timeout=900\n"
    outFile.write(line)

rawDescription: Search for a line that contains some text, replace complete line python


code:
a_lineitem_object.buyer = request.user
a_lineitem_object.save()

rawDescription: Use logged in username as field value in django


code:
d1 = self.db.hget(auth, 'user_add')
d2 = self.db.get('foo')

rawDescription: Twisted: Advise on using txredisapi library required


code:
def insert_into_data_struct(state, job, count, struct):
    if state not in struct:
        struct[state] = {job: count}
    elif job not in struct[state]:
        struct[state][job] = count
    else:
        struct[state][job] += count

rawDescription: Checking for Values in a Dictionary

description: Checking for Values in a Dictionary


rawDescription: Why does setattr fail on a bound method

description: Why does setattr fail on a bound method


code:
import re

def findWholeWord(w, string):
    pattern = re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE)
    if pattern.search(string):
        return True
    else:
        return False

rawDescription: Find single or multiple words in string

description: Find single or multiple words in string


code:
def group_paws(data_slices, time):
    # Sort slices by initial contact time
    data_slices.sort(key=lambda s: s[-1].start)

    # Get the centroid for each paw impact...
    paw_coords = []
    for x,y,z in data_slices:
        paw_coords.append([(item.stop + item.start) / 2.0 for item in (x,y)])
    paw_coords = np.array(paw_coords)

    # Make a vector between each sucessive impact...
    dx, dy = np.diff(paw_coords, axis=0).T

    #-- Group paws -------------------------------------------
    paw_code = {0:'LF', 1:'RH', 2:'RF', 3:'LH'}
    paw_number = np.arange(len(paw_coords))

    # Did we miss the hind paw impact after the first
    # front paw impact? If so, first dx will be positive...
    if dx[0] > 0:
        paw_number[1:] += 1

    # Are we starting with the left or right front paw...
    # We assume we're starting with the left, and check dy[0].
    # If dy[0] > 0 (i.e. the next paw impacts to the left), then
    # it's actually the right front paw, instead of the left.
    if dy[0] > 0: # Right front paw impact...
        paw_number += 2

    # Now we can determine the paw with a simple modulo 4..
    paw_codes = paw_number % 4
    paw_labels = [paw_code[code] for code in paw_codes]

    return paw_labels

rawDescription: How to sort my paws?

description: Sort my paws


code:
with Capturing() as output:
    do_something(my_object)

rawDescription: How to capture stdout output from a Python function call?

description: Capture stdout output from a Python function call


rawDescription: Pandas: groupby and return mean value of a non-numeric variable


code: getNumeric('Python 2.7: ')

rawDescription: Getting safe user input in python

description: Getting safe user input in python


code:
from __future__ import print_function
from multiprocessing.dummy import Pool, Lock # use threads
from subprocess import Popen, PIPE

def run(i, lock=Lock()):
    p = Popen(["cmd", str(i)], stdout=PIPE, bufsize=1)
    for line in iter(p.stdout.readline, b''):
        with lock:
            print(p.pid, line.rstrip())
    p.stdout.close()
    return p.wait()

return_codes = Pool(4).map(run, range(10)) # run 10 subprocesses, 4 at a time

rawDescription: Print multithread subprocess

description: Print multithread subprocess


code: iter_mystate = iter(getstate, None)

rawDescription: python: iterator from a function

description: Python: iterator from a function


code:
from datetime import datetime
import io
import threading
import os
import time

import urllib2

from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

wdir = "workdir"

def looper(time_count, loop_name):
    start = time.time()
    end = start + time_count
    font = ImageFont.truetype("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", 10)
    while time.time() <= end:
        now = datetime.now()
        dte = str(now.day) + "-" + str(now.month) + "-" + str(now.year)
        dte1 = str(now.hour) + "-" + str(now.minute) + "-" + str(now.second) + "." + str(now.microsecond)
        cname = "Cam1-"
        dnow = """Date: %s """ % dte
        dnow1 = """Time: %s""" % dte1
        image = urllib2.urlopen('http://(ip address)/snapshot.cgi?user=uname&pwd=password').read()
        # convert directly to an Image instead of saving / reopening
        # thanks to SO: http://stackoverflow.com/a/12020860/377366
        image_as_file = io.BytesIO(image)
        image_as_pil = Image.open(image_as_file)
        draw = ImageDraw.Draw(image_as_pil)
        draw_text = "\n".join((cname, dnow, dnow1))
        draw.text((0, 0), draw_text, fill="white", font=font)
        #draw.text((0, 0), cname, fill="white", font=font)
        #draw.text((0, 10), dnow, fill="white", font=font)
        #draw.text((0, 20), dnow1, fill="white", font=font)
        img_name = "Cam1-" + dte + dte1 + "(" + loop_name + ").jpg"
        img_path = os.path.join(wdir, img_name)
        image_as_pil.save(img_path)

if __name__ == '__main__':
    time_count = 5
    threads = list()
    for i in range(2):
        name = str(i)
        t = threading.Thread(target=looper, args=(time_count, name))
        threads.append(p)
        t.start()
    for t in threads:
        t.join()

rawDescription: How to efficiently read and save video from an IP camera?

description: Efficiently read and save video from an IP camera


rawDescription: Extra newline character for children of Beautiful Soup


rawDescription: Defined dict entries Python

description: Defined dict entries Python


rawDescription: list's index() method for nested structures OR how to match against particular value of composed element stored in list and get it's index

description: List's index() method for nested structures OR how to match against particular value of composed element stored in list and get it's index


rawDescription: Constantly Update Label Widgets From Entry Widgets TKinter


rawDescription: Accessing inner function of a function

description: Accessing inner function of a function


code:
A=[ ]
B = [ ]
C = [ ]
allLists =[A,B,C]
X=range(10,20)
for i,j in enumerate(X):
  allLists[i%len(allLists)].append(j)
A,B,C

rawDescription: Append new list every iteration of the for loop


rawDescription: Check if all values of iterable are zero


code:
import re
"".join([str(m.start()) for m in re.finditer(r'[A-Z]', "aAaEaaUA")])

rawDescription: Persistent index in python string

description: Persistent index in python string


rawDescription: How can I extract all possible induced subgraphs from a given graph with networkx

description: Extract all possible induced subgraphs from a given graph with networkx


code:
your_string = "domain.3.bumblebee"
your_string.split(".")[1]

rawDescription: Capturing input between periods in Python


code:
query = """SELECT %s
           FROM TVShowData
           WHERE julianday(_Starttime) + (_RunningTime / 24.0 / 60.0) > julianday('now', 'localtime')
           %s
           ORDER BY StartTime
           LIMIT 15"""
if category:
    filter = " AND WatchType = ?"
    parameters = (category,)
else:
    filter = ""
    parameters = ()
query = query % (','.join(properties), filter)
cur.execute(query, parameters)

rawDescription: SQlite Select all when filter has a specific value


code:
v[:-1] != v[1:]

array([False, False, False, False,  True, False, False,  True,  True,
    True,  True,  True,  True,  True,  True,  True, False, False], dtype=bool)

rawDescription: Find index where elements change value numpy


code:
try:
    # script goes here

    # when you want to stop,
    raise HaltException("Somebody stop me!")

except HaltException as h:
    print(h)
    # now what?

rawDescription: Stop python script without killing the python process


code: paths = subprocess.check_output(["find", ".", "-name", "foobar.ext"])

rawDescription: Translate standard output memory file to string of English text as if a print command were being used


code:
import sys
sys.path.append('.')
import module

rawDescription: Hadoop Streaming: Mapper 'wrapping' a binary executable


rawDescription: How to select columns from frame in HDFStore

description: Select columns from frame in HDFStore


rawDescription: Remove all characters from a string who's ordinals are out of range


code:
import dis
dis.dis(a)
dis.dis(b)

rawDescription: Why is my "exploded" Python code actually running faster?


code:
def valid_letter_sequence(abc):
    return not (set(abc) - set('AEIOU'))

rawDescription: why is that str.count('') ≠ (from str.count('A') + str.count('B') + ... + str.count('Z'))

description: Why is that str.count('') ≠ (from str.count('A') + str.count('B') + ... + str.count('Z'))


code: {{ games_list|safe }}

rawDescription: Update Jinja2 template variables

description: Update Jinja2 template variables


code:
@skipIfTrue('isOnline')
def test_thing(self):
    print("A test")

rawDescription: How can I decorate a Python unittest method to skip if a property I've previously evaluated isn't True?

description: Decorate a Python unittest method to skip if a property I've previously evaluated isn't True


code:
[list(t) for t in zip(*[iter(num_str.split(","))]*4)]
[list(t) for t in zip(*[iter(num_str.split(","))]*2)]

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


code:
exec_text = 'INSERT INTO t (' + ','.join(col_names) +') values(' + ','.join(['?'] * len(values)) + ')'
conn.exec(exec_text, values)
# as long as len(col_names) == len(values)

rawDescription: Python Sqlite3 insert operation with a list of column names


code:
line = 'a+b+c+d'
line.split('+')
lst = line.split('+')
lst[-1]
lst[0]
lst[1]
lst[2]
lst[3]

rawDescription: In line.split('+')[-1] what does the -1 in the square brackets indicate in Python


code:
class Proxy( server.Server):
    thread = CustomClientThread

rawDescription: Python3 - import and override method

description: Python3 - import and override method


code:
import functools

def max_calls(num, default=None):
    """Decorator which allows its wrapped function to be called at most `num`
    times per Flask request, but which then returns `default`.

    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if flask.request.call_counts[func] == num:
                return default
            flask.request.call_counts[func] += 1
            return func(*args, **kwargs)
        return wrapper
    return decorator

rawDescription: Python decorator to limit number of calls


code: zpairs_dict[('apple', 'apple')]['Z1']

rawDescription: How to Process Row Pairs Preserving an ID Column without Dictionaries using Pandas?


rawDescription: is there a way to loop over two lists simultaneously in django?

description: Is there a way to loop over two lists simultaneously in django


rawDescription: Read in tuple of lists from text file as tuple, not string - Python


code: [i for i in a if len(i) == 1]

rawDescription: Find the indices of subarrays of single element


rawDescription: Get HTML Source of WebElement in Selenium WebDriver using Python


code: newImg.save(path, 'JPEG', dpi=[300,300], quality=90)

rawDescription: How does Python PIL and PILLOW compress pictures?


code:
import urllib.request
import json

with urllib.request.urlopen("http://openexchangerates.org/api/latest.json?app_id=XXX") as url:
    response = url.read()

charset = url.info(). get_content_charset('utf-8')  # UTF-8 is the JSON default
data = json.loads(response.decode(charset))

rawDescription: Get Data from JSON Python?

description: Get Data from JSON Python


code: nonZeroYCount = np.count_nonzero(data[time][1][:, 1])

rawDescription: Counting non zeros in only 1 column of a numpy array


code:
strs = [json.dumps(innerdict) for innerdict in d]
s = "[%s]" % ",\n".join(strs)
open('./testing.json','w').write(s)

rawDescription: Python JSON dump a list of object.

description: Python JSON dump a list of object.


code:
users = {}
for tweet in sys.stdin:
    t, u, w, user = tweet.split('\t')
    if user not in users:
        # May run afoul of open file limits...
        users[user]= open(some_directory+user,"w")
    users[user].write( tweet )
    users[user].flush( tweet )
for u in users:
    users[u].close()

rawDescription: Processing a huge file (9.1GB) and processing it faster -- Python


code: df.sort_values(by=2, ascending=False)

rawDescription: Pandas multiIndex DataFrame sort

description: Pandas multiIndex DataFrame sort


code:
with open("file.py", "a+") as f:
    f.write("\na = 1")

rawDescription: How can I tell python to edit another python file?

description: Tell python to edit another python file


code:
{'axes.edgecolor': 'white',
 'axes.facecolor': '#EAEAF2',
 'axes.labelcolor': '.15',
 'grid.color': 'white',
 'text.color': '.15',
 'xtick.color': '.15',
 'ytick.color': '.15'}

rawDescription: Best way to display Seaborn/Matplotlib plots with a dark iPython Notebook profile

description: Display Seaborn/Matplotlib plots with a dark iPython Notebook profile


code: dict(mylist)

rawDescription: Is it possible to add <key, value> pair at the end of the dictionary in python


rawDescription: Trouble resampling Pandas timeseries data on Python timedelta objects


code:
while True:
    choice = random.choice(list_of_strings)
    if len(choice) > x:
        return choice

rawDescription: Extract random values from list that fulfil criteria? Python


code:
toolmenu.add_command(label="Search Ctrl+f", command=self.cntrlf)
root.bind('<Control-f>', self.searchbox)
def cntrlf(self, event):
    self.searchbox()

rawDescription: Keyboard shortcuts with tkinter in Python 3


code: map(int, your_list)

rawDescription: Remove single quotes from python list item


rawDescription: Passing variable length parameters to a function in python


code:
q = Queue.Queue()
for i in range(10**10):
    try:
        q.put((i, my_generator.next()))
    except StopIteration:
        break

rawDescription: Idiomatic list of all natural numbers

description: Idiomatic list of all natural numbers


code: len([x for x in product(range(100),range(100),range(100),range(100)) if sum(x)==100])

rawDescription: Python: Generate matrix of Nx4 integers who sum is a constant


code:
# A simple function of x, y
def f(x, y):
    return 2*x + 3*y**2

x = x.reshape((m, 1, d))
y = y.reshape((1, n, d))
temp = f(x, y)
Z = temp.sum(2)

rawDescription: Function application and reduction on large arrays


code:
array = ['there is nothing','there is everything,',['there is','where']]
" ".join([" ".join(s) if isinstance(s,list) else s for s in array])

rawDescription: Join on nested lists of strings

description: Join on nested lists of strings


code:
for i, has_more in lookahead(range(3)):
    print(i, has_more)

rawDescription: What is the pythonic way to detect the last element in a python 'for' loop?


code: iqr = np.subtract(*np.percentile(x, [75, 25]))

rawDescription: How do you find the IQR in Numpy?

description: Find the IQR in Numpy


code: a, b, c = [np.zeros((2,), object) for _ in xrange(3)]

rawDescription: assigning an object to multiple variables - python

description: Assigning an object to multiple variables - python


rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


code:
def match_and_replace(word, rule, phonemes):
    # a rule can match multiple times, find all of them
    matches = [(m.start(), m.end()) for m in re.finditer(rule, word)]
    matches.reverse()  # we're going to replace in-place, so start from behind
    chars = list(word)  # convert to list of chars since strings are immutable
    for start, end in matches:
        chars[start:end] = phonemes
    return ''.join(chars)  # convert back to string

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


rawDescription: Using the reduce function on a multidimensional array


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

table={'time':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5],
       'data':[1,1,2,2,2,1,2,3,4,5,1,2,2,2,3],
       'type':['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']}
df=pd.DataFrame(table, columns=['time','data','type'])

groups = df.groupby('type')

fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(group['time'], group['data'], label=name)
ax.legend(loc='best')

plt.show()

rawDescription: Python Pandas Matplotlib Plot Colored by type value defined in single column


code: [mydict[key]**exp[key] for key in mydict]

rawDescription: Fastest Way to Multiply Dictionary Values and Output to 'list type'


code:
import timeit
timeit.timeit("arr+='1234567890'", setup="arr = ''", number=10000)

rawDescription: subclass str, and make new method with same effect as +=

description: Subclass str, and make new method with same effect as +=


code:
import multiprocessing as mp
import time

def worker(x):
    print('work item', x)
    time.sleep(x)
    result = x - 5
    if result == 0:
        print('termination condition')
    print('work item', x, 'done')
    return result

if __name__ == '__main__':
    p = mp.Pool(4)
    for result in p.imap_unordered(worker, range(20), chunksize=1):
        if result == 0:
            print('terminating')
            p.terminate()
            break
    print('done')

rawDescription: How to use multiprocessing for a Python for loop with a break statement?

description: Use multiprocessing for a Python for loop with a break statement


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


code: [function(i) for i in iterable]

rawDescription: Python FTP Upload Multiple Files at Once


code:
class Block:
    def __init__ (self):
        self = pygame.sprite.Sprite() # don't overwrite self here
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.rect = self.image.get_rect()

rawDescription: Am I using the constructor __init__ wrong?


code:
from collections import deque
from copy import copy # just to save time
def caesercipher(string, k):
    upper = deque("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    lower = deque("abcdefghijklmnopqrstuvwxyz")
    resultupper = copy(upper)
    resultupper.rotate(-k)
    resultlower = copy(lower)
    resultlower.rotate(-k)
    dict_for_trans = dict(zip(upper,resultupper))
    dict_for_trans.update(dict(zip(lower,resultlower)))

    transdict = str.maketrans(dict_for_trans)

    return string.translate(transdict)

rawDescription: encrypting message in a text file python

description: Encrypting message in a text file python


code:
def __eq__(self, other):
    return all(hasattr(self, a) == hasattr(other, a) and
               getattr(self, a) == getattr(other, a) for a in self.metainfo)

rawDescription: Python: Can you make this __eq__ easy to understand?


code:
rows.flat[reindex]
cols.flat[reindex]

rawDescription: Sorting cells of big numpy matrices

description: Sorting cells of big numpy matrices


code:
for i in range(len(fruit)):
    fruit[i] = fruit[i][-3:]

rawDescription: How do I check how many entries there are within a nested list and then remove all other values other than the last 3 for each item?

description: Check how many entries there are within a nested list and then remove all other values other than the last 3 for each item


code:
if sales>300:
    t_sales=t_sales+sales
    totalsale_each += sales # the last sale counts for the last person
    infilelist.append(str(totalsale_each))

    sales_person=input("another sales pesron")
    infilelist.append(sales_person)
    totalsale_each = 0 # reset the sales for the next person

rawDescription: How to continue writing the loop to the file and how to reset the initial value to 0 after each condition met?

description: Continue writing the loop to the file and how to reset the initial value to 0 after each condition met


code: SKIP_TASKS = True

rawDescription: How to stop Tasks firing during Django Nose tests?

description: Stop Tasks firing during Django Nose tests


code:
def main():
    fn = "matrix1.txt"
    matrix = readMatrix(fn)
    n = int(input("Enter row number: "))
    rowSum(matrix, n)

def readMatrix(fn):
    matrix = []
    with open(fn) as f: # a with block will auto close your file after the statements within it
        for line in f:
            line = line.strip() # strip off any trailing whitespace(including '\n')
            matrix.append(line.split())
    return matrix

def rowSum(matrix, rowNum):
    result = sum(int(i) for i in matrix[rowNum])
    print("The sum of row {} = {}".format(rowNum, result))

main()

rawDescription: Python reading matrix from file

description: Python reading matrix from file


code:
from google.appengine.ext import db
import cgi

class Entity(db.Expando):
    pass

e = Entity()
e.put()         # id is assigned
k = e.key()     # key is complete
id = k.id()     # system assigned id

html="""

        Key: %s

""" % (cgi.escape(k))

rawDescription: Displaying Python values in HTML

description: Displaying Python values in HTML


code:
df = pd.DataFrame([['123'],['ab 123'],['xyz']],columns = ['A'])
df
df[df["A"].str.contains("\d+")]
df[df["A"].str.contains("\d+")]['A'].str.extract("(\d+)")
df['A'].str.extract("(\d+)")

rawDescription: How do I return the matched portion of a string in a Pandas Series?

description: Return the matched portion of a string in a Pandas Series


code:
mat, row, col = data.shape
data = data.swapaxes(0, 1).reshape(row, mat*col)

rawDescription: Python eliminate Tuples after zipping list of list of lists


code:
self.statusbar = CustomStatusBar(self)
self.SetStatusBar(self.statusbar)

rawDescription: How can I align the text in a StatusBar to the right in wxPython?

description: Align the text in a StatusBar to the right in wxPython


code: df.set_index(df.year.map(lambda x: datetime.datetime(x, 1, 1)))

rawDescription: Construct DatetimeIndex if you only have year


code:
from functools import wraps
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        print('Calling decorated function')
        return f(*args, **kwds)
    return wrapper
@my_decorator
def example():
    """Docstring"""
    print('Called example function')
example()
example.__name__
example.__doc__

rawDescription: Python inspect.getmembers does not return the actual function when used with decorators


code:
def method(self, key, length):
    return self.__dict__[key][:length]

rawDescription: Constructing a dictionary with multi part keys


rawDescription: python list tree indexing

description: Python list tree indexing


rawDescription: convert a hexadecimal file and extract / display characters that belongs to a language

description: Convert a hexadecimal file and extract / display characters that belongs to a language


rawDescription: How do I convert a DataFrame from long to wide format, aggregating a column's values by counts

description: Convert a DataFrame from long to wide format, aggregating a column's values by counts


code: app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

rawDescription: Rejecting files greater than a certain amount with Flask-Uploads?


code:
import mad

mf = mad.MadFile("foo.mp3")
track_length_in_milliseconds = mf.total_time()

rawDescription: python ringtone maker : how to split files

description: Python ringtone maker : how to split files


code: my_dict.setdefault('foo', {})['bar'] = some_var

rawDescription: Correct way to edit dictionary value python


code:
MyButton = Tkinter.Button(
    self.frame,
    text = "Foobar",
    command = self.foobar,
    relief=Tkinter.SUNKEN
)

rawDescription: How to disable text shaking when I click a button?

description: Disable text shaking when I click a button


code: ["10$^{}$".format(int(math.log10(num))) for num in a]

rawDescription: How to format an array of floats into a string

description: Format an array of floats into a string


code: return int(n) == n

rawDescription: How can I type-check variables in Python?

description: Type-check variables in Python


rawDescription: BeautifulSoup extracting data from multiple tables


code:
entry = '1.1 Ensure that all positions have current'
entry.split(' ',1)

rawDescription: trying to split a string on the space after a floatingpoint number - python positive lookbehind assertion

description: Trying to split a string on the space after a floatingpoint number - python positive lookbehind assertion


code:
for path in generate_paths(3):
   print(path)
print(len(tuple(generate_paths(14))))

rawDescription: Modifying a recursive function that counts no. of paths, to get sequence of all paths


code:
[{'color': 'blue', 'priority': 2, 'shape': 'circle'},
 {'color': 'green', 'priority': 3, 'shape': 'square'},
 {'color': 'green', 'priority': 2, 'shape': 'triangle'}]

rawDescription: Merging a list of dictionaries in python based on one key/value pair?


code: result = map(function(i, j)  for i, j in itertools.product(params_list1, params_list2))

rawDescription: Iterate over parameters without a loop

description: Iterate over parameters without a loop


code: from Products.Archetypes.interfaces.storage import IStorage

rawDescription: Plone/Zope/ZODB: how to override storage method on a File field


code:
def split_lines(text):
    lines = text.split('\n')
    regex = re.compile(r'.{1,80}(?:\s+|$)')
    return '\n'.join(s.rstrip() for line in lines for s in regex.findall(line))

rawDescription: wrapping a text file so that each line contain a maximum of 80 characters

description: Wrapping a text file so that each line contain a maximum of 80 characters


code:
v = ValidationRule.objects.get(id=1)
field = getattr(v, v.other_field)

rawDescription: Django Model set foreign key to a field of another Model


code:
intersection = set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))
[x for x in l1 if tuple(x) in intersection]

rawDescription: Python - Intersection of two lists of lists


code:
def read_pgm(pgmf):
    """Return a raster of integers from a PGM as a list of lists."""
    assert pgmf.readline() == 'P5\n'
    (width, height) = [int(i) for i in pgmf.readline().split()]
    depth = int(pgmf.readline())
    assert depth <= 255

    raster = []
    for y in range(height):
        row = []
        for y in range(width):
            row.append(ord(pgmf.read(1)))
        raster.append(row)
    return raster

rawDescription: Read a pgm file in python

description: Read a pgm file in python


code:
example = ['a', 'b', 'c']
repr(example)[1:-1] # [1:-1] to remove brackets

rawDescription: Need to join the elements of a list but keep the '' around element after joining


rawDescription: Get all the diagonals in a matrix/list of lists in Python


code:
class Vendor(models.Model):
  field_names_go_here = models.TextField(max_length=70)
  short_description = models.CharField("Description", max_length=70)

rawDescription: Django One-To-Many Models

description: Django One-To-Many Models


code:
mapping = dict(zip(alpha, alphaShift))
for char in unencrypted:
    encrypted += mapping.get(char, char)

rawDescription: Better way to test for a value in a list than to stack try's and except's


code:
def myFunction(arg):
     # time consuming stuff...
     return arg, True

nonpooldict = dict(pool.imap_unordered(myFunction, data))
# Will collect results in a dictionary as they are calculated

rawDescription: Watching for multiprocessing to finish

description: Watching for multiprocessing to finish


code: isin

rawDescription: Cythonizing string array comparison function to be applied to pandas DataFrame


code: [value[1:3] for value in d.values()]

rawDescription: Return index of dictionary values, when dict values are a list


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

a = np.array([3, 5, 10, np.inf, 5, 8])
imdata = np.ma.masked_invalid(np.atleast_2d(a))
cmap = plt.cm.hot
cmap.set_bad('b', 1)
fig, ax = plt.subplots()
im = ax.pcolormesh(imdata, cmap=cmap)

plt.colorbar(im)
plt.show()

rawDescription: pcolormesh with masked invalid values

description: Pcolormesh with masked invalid values


code:
import sys, dis

class Moo(object):
    def __getitem__(self, i):
        parent_frame = sys._getframe().f_back
        accessing_opcode = parent_frame.f_code.co_code[parent_frame.f_lasti]
        return "This __getitem__ was invoked by way of a %s instruction" \
                % dis.opname[ord(accessing_opcode)]

rawDescription: Python slice how to distinguish slice arguments and default arguments (e.g., x[i:] vs. x[i:None])?


rawDescription: Why isn't my solution to Project Euler 9 working?


code:
def a(): pass
a
type(a)

rawDescription: Difference between methods and functions


code:
val = 0
for wall in walls:
    val <<= 1 # add one 0 bit at the "end"
    val |= wall # set this bit to 1 if wall is True, otherwise leave it at 0

val = hex(val) # get a hex string in the end
val = format(val, 'x') # or without the leading 0x if it's undesired

rawDescription: Elegant way to convert list to hex string


code: df.buyer_id = df.apply(lambda x: '{}_{:02d}'.format(x.buyer_id, id_map[x.phone_no]), axis=1)

rawDescription: how to rename a column value in pandas dataframe on some condition

description: Rename a column value in pandas dataframe on some condition


code:
mags     = [x for x in a if re.match(r'.*MAG$', x)]
mag_errs = [x for x in a if re.match(r'.*MAG_ERR$', x)]

rawDescription: Finding a pattern in a list of strings

description: Finding a pattern in a list of strings


code:
def consume(iterable):
    for s in iterable:
        np.sum(np.ascontiguousarray(s))

min(Timer(lambda: consume(timeline_sample(arr, 1))).repeat(10, 10))
min(Timer(lambda: consume(timeline_sample_fast(arr, 1))).repeat(10, 10))
min(Timer(lambda: consume(timeline_sample_faster(arr, 1))).repeat(10, 10))
#>>> 0.2632228760048747
#>>> 0.25778737501241267
#>>> 0.07451769898761995

rawDescription: Is there a faster version of numpy.random.shuffle?


code:
t = Transaction(amount=100)
u = User()
u.transaction = t
session.add(u)
session.commit()
u = session.query(User).first()
u.transaction.amount
u.transaction.date

rawDescription: What kind of database schema would I use to store users' transaction histories?


code:
for thread in threads:
    thread.start()
    thread.join()

rawDescription: subprocess.Popen in Threads

description: Subprocess.Popen in Threads


code: t = u"Great buy w. all amenities! Use on all cars. come on in!"

rawDescription: regexp, python: index of last occurrence. Has negative look-behind

description: Regexp, python: index of last occurrence. Has negative look-behind


code:
def cashRegister(cashRegisterFile):
    subTotal = 0
    total = 0
    salesTax = .085
    registerTableHeader = ("{0:<30} {1:>10}{2:>10} {3:>10} {4:>10}\n".format(
            'Description', 'Qty', 'Unit Cost','Item Cost', 'Subtotal'))
    cashRegisterFile.write(registerTableHeader)

    while True:
        quantityOfItem = int(input("Enter quantity of item: "))
        if quantityOfItem <= 0:
            break
        itemDescription = input("Enter Item's description: ")[:30]
        itemCost = float(input("Enter item's cost: "))
        subTotal = quantityOfItem * itemCost
        total += subTotal

        registerTable = ("{0:<30} {1:>10}{2:>10.2f} {3:>10.2f} {4:>10.2f}\n".format(
                itemDescription, quantityOfItem, itemCost, itemCost * quantityOfItem,
                subTotal))
        cashRegisterFile.write(registerTable)

with open('cash.txt', 'w') as cashRegisterFile:
    cashRegister(cashRegisterFile)

rawDescription: while loop into another file

description: While loop into another file


code:
for a, b in l:
    xx += range(a, b+1)

rawDescription: Python expand integers inside a list and sort them


code:
with open('data.pickle') as pickle_file:
    data = pickle.load(pickle_file)  # You get the data back!

rawDescription: Python: How to get a object database

description: Python: How to get a object database


code: return sorted(fights, key=(lambda fight:fight["Date"]))

rawDescription: Sorting a list with a dictionary at items


code:
from PySide.QtCore import Qt
a = Qt.CopyAction | Qt.TargetMoveAction
int(a)
int(a & Qt.ActionMask)

rawDescription: Qt DropActions: What is ActionMask for?

description: Qt DropActions: What is ActionMask for


code:
data = [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1]
from itertools import groupby
[list(group) for item, group in groupby(data)]

rawDescription: Grouping 0s and 1s in python

description: Grouping 0s and 1s in python


code:
class myIterator:
    def __init__(self, n):
        self.last = n
        self.prev = 0
        self.fib = 1

    def __iter__(self):
        return self

    def next(self):
        if self.fib < self.last:
            res = self.fib
            self.fib += self.prev
            self.prev = res
            return res

        raise StopIteration

rawDescription: What is the best way to write a python iterator based on a generator


code:
...
F0 = F(x0, a, b)
F1 = F(x1, a, b)

max_step = 100
for step in range(max_step):
    x_mid = (x0 + x1)/2.0
    F_mid = F(x_mid, a, b)
    mask0 = numpy.sign(F_mid) == numpy.sign(F0)
    mask1 = numpy.sign(F_mid) == numpy.sign(F1)
    x0 = numpy.where( mask0, x_mid, x0 )
    x1 = numpy.where( mask1, x_mid, x1 )
    F0 = numpy.where( mask0, F_mid, F0 )
    F1 = numpy.where( mask1, F_mid, F1 )
...

rawDescription: Finding the roots of a large number of functions with one variable


code:
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=['A'],
          format='table')

rawDescription: read HDF5 file to pandas DataFrame with conditions

description: Read HDF5 file to pandas DataFrame with conditions


code:
page = 2
url = 'http:/ ... st/500/{0}?sortField=oi ... page={0}&clear ...'.format(page)

rawDescription: Accessing JSON feeds

description: Accessing JSON feeds


code:
for to_find, left, right in to_find_and_bounds:
    offset_left = numpy.searchsorted(A[1, left:right], to_find, side="left")
    offset_right = numpy.searchsorted(A[1, left:right], to_find, side="right")
    yield from range(offset_left + left, offset_right + left)

rawDescription: Numpy find indices of matching columns

description: Numpy find indices of matching columns


code: {'Images': 50, 'Total cells': 532, 'Viable cells': 512, 'Nonviable cells': 20}

rawDescription: Parsing a generic data file in python

description: Parsing a generic data file in python


code: {'foo': ['blah', 'garble']}

rawDescription: Python add to a list that is a value of a key


code: [(x,y) for x in range(Z-2,Z+2) for y in range(W-2,W+2) if x != y and x >= 0]

rawDescription: Python - Add boolean condition to generator


code:
def foo(bar, baz=None):
    if baz is None:
        baz = blar()

rawDescription: Dynamic default arguments in python functions


code:
ym=np.matrix(y)
ym.sum(axis=1)

rawDescription: Python/numpy issue with array/vector with empty second dimension


code:
type_code = linea[0:2]
(derivation, name) = (linea[2:4], linea[4:20])

rawDescription: ascii file parsing based on position and length in line using python

description: Ascii file parsing based on position and length in line using python


code:
outervar = None # this is global

def foo():
    global outervar # prevents creation of local variable called outervar
    if(outervar):
       outervar = "you win it" # this assigns to global variable

rawDescription: Python: Persistent variable in a module without a class?


rawDescription: Avoiding bias in randomly generated subtraction problems


code: os.path.join(ls(), 'foo.txt')  # produce the value first

rawDescription: call function through variable or without parentheses in python

description: Call function through variable or without parentheses in python


code: delimiter = chr(0x00A0)

rawDescription: Python 3.3. Concatenating strings from input. How?


rawDescription: Finding ElasticSearch records matching empty and null values


rawDescription: 4 dimensional array of zeros in python

description: 4 dimensional array of zeros in python


rawDescription: How to disable the OptionParser default help view?

description: Disable the OptionParser default help view


rawDescription: Summing timeseries data in a python dict


code: proxy = pd.DatetimeIndex(df.index) + pd.DateOffset(hours=6)

rawDescription: Custom time series resampling in Pandas

description: Custom time series resampling in Pandas


code:
repr(MyClass(foo='bar')) == "<MyClass: {'foo': 'bar'}>"
repr(MyClass()) == '<MyClass: {}>'

rawDescription: Correct way of unit testing __repr__ with dict


code:
t = raw_input("Enter list items: ")
l = [int(x) if x.isdigit() else x for x in t.split()]

rawDescription: How to create a list with strings and integers as its elements?

description: Create a list with strings and integers as its elements


code: data_str = str(buffer(data))

rawDescription: passing Array[Byte] from ironpython to python using pickle

description: Passing Array[Byte] from ironpython to python using pickle


code:
make_plot = ro.r("""
function(dr) {
  names(dr) <- c('letters','bool','n','value')

  x <- ggplot() +
    geom_bar(data=dr, aes(y = value, x = letters, fill = bool),
             stat="identity", position='stack') +
    theme_bw() +
    facet_grid( ~ n)

  print(x)
}""")

make_plot(dr)

rawDescription: Pandas stacked multilevel index plot

description: Pandas stacked multilevel index plot


code:
x = None
y = None
r = lambda : x*y
r()
x = 1
y = 2
r()

rawDescription: Passing arithmatic expressions in python without evaluating them


rawDescription: spark python reduced by key

description: Spark python reduced by key


code:
string_version = ''.join(chr(s) for s in S)
list_verison = list(ord(s) for s in string_version)

rawDescription: Clean conversion from int list to character and then back to int list, in Python


rawDescription: How to write a lot of nested 'for' loops (Recursively)

description: Write a lot of nested 'for' loops (Recursively)


rawDescription: Randomly replace 2 values in python dictionary


rawDescription: Numpy vectorization for nearest neighbor calculation in semi-sparse arrays


code:
def fizz_count(x):
    return sum(1 for item in x if item == "fizz")

rawDescription: for statement does not work as intended

description: For statement does not work as intended


rawDescription: Add an item with common key to a dictionary in python


rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
names = 'van der Hilst, Rob, Chen, Min, Huang, Hui, Niu, Fenglin, Yao, Huajian' + \
        'Malanotte-Rizzoli, Paola, Eltahir, Elfatih, Wei, Jun, Xue, Pengfei' + \
        'Bowring, Samuel, Hoke, Gregory, Schmitz, Mark'
names = names.split(', ')
last_names = names[::2]
first_names = names[1::2]

names = {'%s %s' % (fn, ln) : _id for _id, (fn, ln) in enumerate(zip(first_names, last_names))}

rawDescription: Python: extract unique id from file name


code: n = [item * 2 for item in n]

rawDescription: What's the difference?< for item in list> and <for i in range(len(list))>


code:
resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

rawDescription: Extract single value from JSON response Python


rawDescription: Why java String.length gives different result than python len() for the same string


code:
l=np.ones(30)
length=len(l)
rand=np.arange(int(0.25*length))
np.random.shuffle(rand)
l[rand]=0
l

rawDescription: array construction in python

description: Array construction in python


code:
class Ic(object):
  attributes = ['id', 'first_name', 'last_name', 'name', 'name_url',
              'email', 'password', 'password_salt', 'picture_id']

  def __init__(self): ...

  # and other methods that set all the attributes on self

  def updater(self):
    sqlbase = 'UPDATE members SET %s WHERE whateveryouwanthere'
    setpieces = []
    values = []
    for atr in self.attributes:
      setpieces.append('%s = ?' % atr)
      values.append(getattr(self, atr, None))
    return sqlbase % ', '.join(setpieces), values

rawDescription: Efficient way to build a MySQL update query in Python


code:
class B_spline_sym(Function):
    _imp_ = staticmethod(B_spline)

    def fdiff(self, argindex=1):
        return B_der_spline_sym(self.args[0])

class B_der_spline_sym(Function):
    _imp_ = staticmethod(B_der_spline)

def A(r, B):
    return r**2*B(r)

rawDescription: define numerical evaluation of a derivative of a sympy function

description: Define numerical evaluation of a derivative of a sympy function


code:
orig = { x['key']:x for v in d.values() for x in v }
orig

rawDescription: Python defaultdict get original dictionary


code: re.search(regex, "home/ abcd fghizzz")

rawDescription: Django URL matching any 140 characters

description: Django URL matching any 140 characters


code:
for row_index, row in enumerate(grid):
    for col_index, item in enumerate(row):
        gird[row_index][col_index] = 1     # Whatever needs to be assigned.

rawDescription: How to traverse a 2D List in python

description: Traverse a 2D List in python


rawDescription: Sorting a List by frequency of occurrence in a list


code:
myfilter = kwargs['myfilter']
del kwargs['myfilter']

rawDescription: Django: ModelMultipleChoiceField doesn't select initial choices


rawDescription: Dictionary value sorting

description: Dictionary value sorting


code:
class Lock():
    def __init__(self, locked = True):
        self.attributes = {'locked': locked}

    def toggleLock(self):
        self.attributes.update({'locked': not self.attributes['locked']})

class Door():
    def __init__(self, lock_object):
        self._attributes = {'color':'Blue'}
        self.lock = lock_object

    def get_attribute(self,key):
        if key in self._attributes:
            return self._attributes[key]
        elif key in self.lock.attributes:
            return self.lock.attributes[key]
        raise KeyError(key)

    @property
    def attributes(self):
        """
        Door's attributes
        """
        # return a new dict that contains the keys of itself, and lock (and possibly more objects)
        a = {}
        a.update(self.lock.attributes)
        a.update(self._attributes)
        return a

    def __getattr__(self, key):
        #nice addition, makes you able to do things like `if Door.locked:`
        return self.get_attribute(key)

rawDescription: How do I set a value of a dictionary to a reference to a value of another dictionary?

description: Set a value of a dictionary to a reference to a value of another dictionary


code:
import example
def fun():
    assert('y' not in dir())
    example.X()
    assert('y' in dir()) # creating X injects y into scope

assert('y' not in dir())
fun()
assert('y' not in dir())
example.X()
assert('y' in dir()) # creating X injects y into scope
assert(isinstance(y, example.Y))

rawDescription: Create Python object in local scope from within C++


code:
def slow_wdist(A, B, W):

    k,m = A.shape
    _,n = B.shape
    D = np.zeros((m, n))

    for ii in xrange(m):
        for jj in xrange(n):
            wdiff = (A[:,ii] - B[:,jj]) / W[:,ii]
            D[ii,jj] = np.sqrt((wdiff**2).sum())
    return D

rawDescription: Fast weighted euclidean distance between points in arrays


code: all( abs(x) == abs(y) for x,y in zip(a,reversed(a)) )

rawDescription: Sort list of lists by unique reversed absolute condition


rawDescription: Python. displaying items in a random order


rawDescription: Access certain elements of a list

description: Access certain elements of a list


code:
def animate(self):
    self.draw_one_frame()
    self.after(100, self.animate)

rawDescription: simple animation using tkinter

description: Simple animation using tkinter


rawDescription: Is there a difference between putting .lower() in one place or another?


code: [(f(month), g(month)) for month in months]

rawDescription: Python: How to pass functions to another function as arguments?


code:
find_range(4, 2)
find_range(2, 4)

rawDescription: Range between two unsorted numbers

description: Range between two unsorted numbers


code:
sp = s.split()
[sp[i+1] for i, l in enumerate(sp) if l == 'length']

rawDescription: Find associated value to a keyword in file with python


code:
class Application(Frame):
   def __init__(self, parent):
      [...]

      expander = TreeExpander(node2, {
         "level1": "bbb/ccc"
         })
      item.bind("<<TreeDoubleClick>>", expander)

rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


rawDescription: Django recive array ajax problem

description: Django recive array ajax problem


rawDescription: numpy - issue with creating a 2D matrix

description: Numpy - issue with creating a 2D matrix


code:
listobj.sort()
listobj.reverse()

rawDescription: Python naming convention: indicating if function alters arguments


code:
friends = []
for message in messages:
  dict = {"message" : message.message, "phone" : message.phone }
  friends.append(dict)

rawDescription: Named dictionary in python

description: Named dictionary in python


code:
binary()
binary(5)
binary(4,1)
binary(4,4)

rawDescription: Find unique permutation of a list binary values without generating all possibilities


code:
class MyClass:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return 'MyClass({0.value})'.format(self)
    def key_function(self):
        return -self.value

my_list = [MyClass(2), MyClass(1), MyClass(3)]
my_list
sorted(my_list, key=lambda mc: mc.value)
min(my_list, key=lambda mc: mc.value) # by attribute
sorted(my_list, key=lambda mc: mc.key_function()) # by method call
sorted(my_list, key=MyClass.key_function) # using unbound method

rawDescription: is there a way to give class method as a key parameter (sort/min/..) in python?

description: Is there a way to give class method as a key parameter (sort/min/..) in python


rawDescription: How to iterate an array in Python pointer-likely and efficiently?

description: Iterate an array in Python pointer-likely and efficiently


code:
def pop(self):
    if self.child is not None:
        item = self.child.pop()
        if len(self.child.items) == 0:
            self.child = self.child.child
            if self.child is not None:
                self.child.parent = self
    else:
        item = self.items.pop()
    return item

def popAt(self, stacknumber):
    s = self
    for i in range(stacknumber):
        s = s.child
        if s is None:
            return None
    if len(s.items) == 0:
        return None
    item = s.items.pop()
    if len(s.items) == 0 and s.parent is not None:
        s.parent.child = s.child
        if s.child is not None:
            s.child.parent = s.parent
    return item

rawDescription: How to create new class instances dynamically at runtime in python?

description: Create new class instances dynamically at runtime in python


code:
values=np.array([2,5,9])
x, y = 10, 2
mat1=np.repeat(np.repeat(values[None,:],y,0).reshape(1,3*y),x,0)

rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code:
foo = 'test'
foo.replace('test', 'Hello World')
foo.replace('t', 'X')
foo.replace('bar', 'nothing')

rawDescription: Iterating through file and retaining data in list - Python


code:
import sys
with open(sys.argv[1]) as f:
    new_list = list(f)
os.remove(sys.argv[1])
step3 = sys.argv[2]

rawDescription: Transfering arguments in Automator's workflow . Python Shells


code:
timeit.timeit("""
from __main__ import data
my_dict_list = {}
for item in data:
    my_dict_list[item['id']] = item['name'] + item['address'] + item['age']""",
        number = 100)

rawDescription: Optimizing a for-loop in python

description: Optimizing a for-loop in python


code:
import datetime
def make_datetime(lst):
    date_str = lst[1]
    return datetime.datetime.strptime(date_str, '%d/%m/%Y %H:%M:%s')

rawDescription: How to sort array with unique elements by datetime (Python)

description: Sort array with unique elements by datetime (Python)


rawDescription: Find repeated pattern in text with "Re" Python


code:
import MySQLdb
import time

def is_connection_up(connection):
    if connection.ping() == 0:
        return True
    else:
        return False

host,user,pwd,db = "localhost","user","pwd","db"
connections = [MySQLdb.connect(host=host,user=user,passwd=pwd,db=db) for i in range(10)]

while True:
    time.sleep(10)
    for con in connections:
        if is_connection_up(con) is not True:
            raise Exception("Connection is down, test might have gone wrong")

rawDescription: Keeping a connection open for the purposes of testing


rawDescription: make matplotlib plotting window pop up as the active one

description: Make matplotlib plotting window pop up as the active one


code:
import tkinter as tk
from tkinter import Tk, Button, Checkbutton, Toplevel

class SecondaryWindow:
    def __init__(self, window):
        self.window = window
        self.decimal_comma = tk.IntVar()

        Checkbutton(window, variable = self.decimal_comma).grid(row = 0, column = 0)
        Button(window, text = "Check the checkbox and click me", command = self.ok_pressed).grid(row = 1, column = 0)

    def ok_pressed(self, event = None):
        print(self.decimal_comma.get())
        self.window.destroy()

class MainWindow(Tk):
    def __init__(self):
        super().__init__()
        Button(self, text = "Click me", command = self.popup).pack(side=tk.LEFT)

    def popup(self, event = None):
        loader = SecondaryWindow(Toplevel())
        loader.window.wait_window()
        self.destroy()

def main1():
    MainWindow().mainloop()

def main2():
    top = Tk()

    loader = SecondaryWindow(top)
    loader.window.wait_window()

    top.mainloop()

if __name__ == "__main__":
    main2()
    main1()

rawDescription: TKinter checkbox behaves different in different contexsts


code:
@deco
def do():
    ...

rawDescription: How to apply a python decorator to a function?

description: Apply a python decorator to a function


code:
re.findall(r'£\d{1,3}(?:\,\d{3})+(?:\.\d{2})?',
" The little £250,000 brown fox jumped over the lazy dog")

rawDescription: Python regular expressions (extracting monetary value from a string)


code:
def __init__(self,s):
    self.name = s.get('name', 0)
    self.dance = s.get('dance')
    super(Crazyperson,self).__init__(s)

rawDescription: Overriding decorated subclass methods

description: Overriding decorated subclass methods


code: number = str(d)

rawDescription: how to convert the datatype of a varible while reading in python?

description: Convert the datatype of a varible while reading in python


code:
df.loc[homeless_mask,'homeless'] = df['homeless_change']
df

rawDescription: add columns where condition is met, but preserve previous value in pandas python

description: Add columns where condition is met, but preserve previous value in pandas python


code:
mystuff['apple'] # get apple from dict
mystuff.apple() # get apple from the module
mystuff.tangerine # same thing, it's just a variable

rawDescription: Python module object without a file

description: Python module object without a file


code:
from functools import wraps

def _log_method(val):
    @wraps(val)
    def wrapper(*a, **ka):
        print(val.__name__, 'is called')
        val(*a, **ka)
    return wrapper

class LogMethodCalls(type):
    def __new__(cls, cls_name, bases, attrs):
        for name, attr in attrs.items():
            if callable(attr):
                attrs[name] = _log_method(attr)
        return type.__new__(cls, cls_name, bases, attrs)

class Foo(metaclass=LogMethodCalls):
    def my_method(self):
        pass

Foo().my_method() # my_method is called

rawDescription: Python - Print method name whenever the methods of a class is called


code:
#read data into list of dicts
import csv

int_cities = set(['New York', 'Houston', 'Phoenix', 'San Jose'])
int_cities_data = []
with open('data.csv', 'rb') as csv_file:
    for line in csv.DictReader(csv_file):
        if line['City'] in int_cities:
            int_cities_data.append(line)

rawDescription: More efficent way to loop through list then using a double loop in python


rawDescription: django rest framework nested fields with multiple models

description: Django rest framework nested fields with multiple models


code:
import gzip
import urllib.request
def __retrieve_html(self, address):
    with urllib.request.urlopen(address) as resp:
        html = resp.read()
        Helper.log('HTML length', len(html))
        Helper.log('HTML content', html)
        if resp.info().get('Content-Encoding') == 'gzip':
            html = gzip.decompress(html)
        return html

rawDescription: Python Sometimes Returns Strange Result When Reading HTML from URL


code: key=lambda x: sum(y['play'] for y in x)

rawDescription: Sorting a list of lists of dictionaries in python


code: newstr = format(newinteger, 'b')

rawDescription: Bitwise & outputting numbers other than 1 and 0


rawDescription: Close Twitty Twister Stream

description: Close Twitty Twister Stream


code: people_dict = {p.get_name(): p for p in people_list}

rawDescription: List of classes to dict

description: List of classes to dict


rawDescription: Groupby Clause in Pandas

description: Groupby Clause in Pandas


rawDescription: Performing multiple calculations on a Python Pandas group from CSV data


code:
from django.contrib.auth import authenticate

user = authenticate(username='john', password='password to check')

if user is not None:
    # the password verified for the user
    if user.is_active:
        print("User is valid, active and authenticated")
    else:
        print("The password is valid, but the account has been disabled!")
else:
    # the authentication system was unable to verify the username and password
    print("The username and password were incorrect.")

rawDescription: How to use Bcrypt to encrypt passwords in Django

description: Use Bcrypt to encrypt passwords in Django


rawDescription: multi-parameter 'in' in python

description: Multi-parameter 'in' in python


rawDescription: Flask: How to Authenticate with Flask-Redis and Redis


rawDescription: using functools.lru_cache on functions with constant but non-hashable objects

description: Using functools.lru_cache on functions with constant but non-hashable objects


rawDescription: How can I show figures separately in matplotlib?

description: Show figures separately in matplotlib


code:
[sp for _,sp in sorted(
         (len(splitpath),splitpath) for splitpath in
            (path.split('/') for path in x)
         )
    ]

rawDescription: Directory tree in a QTreeWidget

description: Directory tree in a QTreeWidget


code:
b = lambda *args: a(2, 3, *args)
b(6, 7, 8)

rawDescription: Map list by partial function vs lambda

description: Map list by partial function vs lambda


code:
while whatever: # main loop
    ...
    # event handling
    if pygame.event.get(PLAYSOUNDEVENT): # check event queue contains PLAYSOUNDEVENT
        nyansoundm.play() # play the sound

rawDescription: pygame.time.set_timer confusion?

description: Pygame.time.set_timer confusion


code: all_dicts = (dict1, dict2) + dicts

rawDescription: Python: Concatenate required arguments and optional args in function?


rawDescription: NLTK Convert Tree to Array?

description: NLTK Convert Tree to Array


code:
import yaml # $ pip install pyyaml

data = yaml.safe_load(txt)

rawDescription: Converting string into dictionary - pythonic Way


code: b

rawDescription: Comparing two dictionaries in list in python


code:
from functools import partial

zebra_line = partial("^FO{x},{y}^A0,N,{font}^FH^FD{text}^FS".format, font=35)

rawDescription: default argument in bound function

description: Default argument in bound function


code:
add1 = '802Taiwan,XX Street XX Road,123'
re.findall(r'^\d+(.*,)\d+$', add1)

rawDescription: Python regex get address without zip code


code:
import sys
import unittest
import logging

logger = logging.getLogger()
logger.level = logging.DEBUG
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)

class TestCase(unittest.TestCase):
    def testSimpleMsg(self):
        stream_handler.stream = sys.stdout
        print("AA")
        logging.getLogger().info("BB")

rawDescription: PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output"


code:
def is_fetched(obj, relation_name):
    cache_name = '_{}_cache'.format(relation_name)
    return getattr(obj, cache_name, False)

rawDescription: Is there a way to check whether a related object is already fetched?


code:
import functools

def withlock(func):
    @functools.wrap(func)
    def wrapper(*a, **k):
        with lock:
            return func(*a, **k)
    return wrapper

rawDescription: Do I have to lock all functions that calls to one or more locked function for multi-threading?


code:
@classmethod
def from_crawler(cls, crawler):
    recipients = crawler.settings.getlist('STATUSMAILER_RECIPIENTS')
    if not recipients:
        raise NotConfigured

    mail = MailSender.from_settings(crawler.settings)
    instance = cls(recipients, mail, crawler)

    crawler.signals.connect(instance.item_scraped, signal=signals.item_scraped)
    crawler.signals.connect(instance.spider_error, signal=signals.spider_error)
    crawler.signals.connect(instance.spider_closed, signal=signals.spider_closed)
    crawler.signals.connect(instance.item_dropped, signal=signals.item_dropped)

    return instance

rawDescription: Sending email with attachments after crawling a website


code: result = letters + str(number)

rawDescription: List of 2 letters 2 numbers?

description: List of 2 letters 2 numbers


rawDescription: Save tuple of numpy arrays to disk?

description: Save tuple of numpy arrays to disk


rawDescription: 3 Dimensional Data in Python

description: 3 Dimensional Data in Python


code:
def append(lst, elem):
    return lst + [elem]

append([1, 2, 3], 4)
def extend(lst1, lst2):
  return lst1 + lst2

extend([1, 2], [3, 4])

rawDescription: Functional append/extend

description: Functional append/extend


code:
df
df.groupby('group_id').cumcount() == 0

rawDescription: Python - Pandas: select first observation per group


code:
try:
    self.handle.stdin.write(...)
except:
    self.error = True

rawDescription: run a shell script in a python function and get data from the script

description: Run a shell script in a python function and get data from the script


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

rawDescription: Python - Flask Default Route possible?

description: Python - Flask Default Route possible


code:
def thank_you(request, id):

    docrequest = DocumentRequest.objects.get(pk=id)
    return render_to_response('thankyou.html',
                              {'docrequest' : docrequest },
                              context_instance=RequestContext(request))

rawDescription: Passing form data from my view to thank you page


rawDescription: python: extracting one slice of a multidimensional array given the dimension index

description: Python: extracting one slice of a multidimensional array given the dimension index


rawDescription: Twython: Filtering more than one track.

description: Twython: Filtering more than one track.


code:
from pyramid_formalchemy.resources import Models

class ModelsWithACL(Models):
    """A factory to override the default security setting"""
    __acl__ = [
            (Allow, 'admin', ALL_PERMISSIONS),
            (Allow, Authenticated, 'view'),
            (Allow, 'editor', 'edit'),
            (Allow, 'manager', ('new', 'edit', 'delete')),
        ]

config.formalchemy_admin('admin', package='package', view=..., factory=ModelsWithACL)

rawDescription: Pyramid and FormAlchemy admin interface

description: Pyramid and FormAlchemy admin interface


code:
df = pd.read_csv('http://pastebin.com/raw.php?i=SuyWZLj5', header=None, parse_dates=[[0, 1]])
df.groupby(pd.TimeGrouper('W')).value.apply(lambda x: ((x == x.min()).astype(int).groupby(x.index.dayofweek)).sum()).unstack(1)

rawDescription: Daily frequency count with pandas

description: Daily frequency count with pandas


rawDescription: How to change Pandas dataframe index value?

description: Change Pandas dataframe index value


code:
lis = sorted([lsDataSorted[i:i+8]
              for i in range(0,len(lsDataSorted),8)],
              key=Compare, reverse=True)

rawDescription: Python - Sorting Lists

description: Python - Sorting Lists


code:
import pandas as pd
import io

temp=u"""var1 var2 var3
var4 var5 var6
1    2    3
4    5    6
1    2    3
4    5    6
1    2    3
4    5    6"""

rawDescription: pandas: how to read file with divided rows

description: Pandas: how to read file with divided rows


code:
import itertools

# here is where you might insert the class code from above

def namekey(room):
    return room.name
def pricekey(room):
    return room.price
sorted_rooms = sorted(rooms, namekey)

rawDescription: remove all values from multiple lists at same index position with some logic

description: Remove all values from multiple lists at same index position with some logic


code:
def brute(x):
    # determine max p such that 2^p <= x
    p = 0
    while 2**p <= x:
        p += 1
    return p-1

def easy(x):
    return x.bit_length() - 1

rawDescription: Compute fast log base 2 ceiling in python


code:
import json
output = json.dumps(d_target)

f = open("myfile", 'w')
f.write(output)
f.close()

rawDescription: Write values of Python dictionary back to file


code:
class RoundRobin:
    def __init__(self, iterable):
        self._iterable = set(iterable)
        self._removed = set()

    def __iter__(self):
        for value in chain.from_iterable(self.repeat()):
            yield value

    def remove(self, item):
        self._removed.add(item)
        self._iterable.remove(item)

    def add(self, item):
        self._iterable.add(item)

    def repeat(self):
        while True:
            for item in self._iterable.copy():
                if not item in self._removed:
                    yield item
            self._removed = set()

rawDescription: Round robin on iterable

description: Round robin on iterable


code:
L = ['A','B','C','D','E']
N = ['1','2','3','4','5']
n_strings = ['124','351'] # Don't use list as a variable name

while not all( x.isalpha() for x in n_strings): # keep going until all are alpha chars

    print ("Enter a letter")
    # Is there a number in List
    # If yes then do the following else print List

    # Ask for a letter from the user
    letter = input("Enter letter: ")

    # Confirm whether the letter is correct or not
    if letter in L:
    # Find the position of the letter in the list
        position = (L.index(letter));
    # Make a variable called number with value at the same position in the N list
        number = N[position];
    # Replace the numbers in the List with the letter entered
        n_strings = [item.replace(number, letter) for item in n_strings];
    # Print the list with the numbers replaced
        print (n_strings, "\n");
        print ("Please guess again. \n");
        letter = input("Enter a letter now: ")
    # repeat until the List only contains letters
    else:
        print ("That is not correct");
        print ("Please guess again. \n");
        letter = input("Enter a letter now: ")

rawDescription: Replace an item in a list based on user input


code: serialized_items = serializers.serialize("json", itemlist, fields=['.....', 'aux_info'])

rawDescription: Using __init__ in django to annotate a model with extra information


rawDescription: Adding numpy arrays

description: Adding numpy arrays


code:
mylist = ["8 - 9-", "7 - 6-", "4-"]
mylist = [s.rstrip('-') for s in mylist]
print(mylist)

rawDescription: remove a character from all strings in a list

description: Remove a character from all strings in a list


code:
with open('test.txt', 'r') as f:
    myString = f.read().decode('latin-1')

rawDescription: Getting the correct encoding for strings and csv-files in Python


code: py-execute-directory

rawDescription: How to set the directory of IPython shell in Emacs the same as the python file?

description: Set the directory of IPython shell in Emacs the same as the python file


code:
outStr = ",".join(map(str, thelist))
thefile.write("%s %s" %(name, outStr))

rawDescription: How to write variable and array on the same line for a text file?

description: Write variable and array on the same line for a text file


code:
grouped = df.groupby('sat_id')

for key,item in grouped:
    date_range = []
    ix_range = []
    date_range = item['datetime']
    ix_range = item['ix']

    for date,ix in zip(date_range,ix_range):
        satlist.append(key)
        datelist.append(date)
        ixlist.append(ix)
        alt = ephem_func(date,tle[key],lat,lon)
        altitude.append(alt)

rawDescription: Pandas calculate new column from two other column variables within dataframe


code: df = df.interpolate(method='time')

rawDescription: Python linear interpolation of values in dataframe


code:
myquery = "select * from players where {}".format(
    ' and '.join('{}=?'.format(k) for k in mylist))

rawDescription: Looping Through Python Dictionary

description: Looping Through Python Dictionary


code:
pd.DataFrame ( { idx1: { idx2:sum( DistMatrix[ x ][ y ]
                                  for (x, y) in zip( row1, row2 ) )
                         for (idx2, row2) in sample.iterrows( ) }
                 for (idx1, row1 ) in sample.iterrows( ) } )

rawDescription: Distance calculation between rows in Pandas Dataframe using a distance matrix


code: digit_letter_letter_digit = r'\d\w\w\d'

rawDescription: Reuse part of a Regex pattern

description: Reuse part of a Regex pattern


code:
dic = dict(first_list)
set(second_list).difference(dic)

rawDescription: Referring to the first element of all tuples in a list of tuples


code:
from collections import Counter
TupleOfTuples = ( ('Venue1', 'Name1'), ('Venue1', 'Name2'), ('Venue2', 'Name3'), ('Venue3', 'Name4'), ('Venue3', 'Name5'), ('Venue3', 'Name6') )
Counter(t[0] for t in TupleOfTuples).items()

rawDescription: How can I convert this tuple of tuples into a count of its elements?

description: Convert this tuple of tuples into a count of its elements


code:
import pandas as pd
import numpy as np
import timeit

def reset_df_first(df):
    df2 = df.reset_index()
    result = df2.groupby('c1').apply(lambda x: x.loc[x['c3'].idxmax()])
    result.set_index(['index'], inplace=True)
    return result

def maxrow(x, col):
    result = x.loc[x[col].argmax()].to_frame().T
    return result

def using_to_frame(df):
    result = df.groupby('c1').apply(maxrow, 'c3')
    result.reset_index(level=0, drop=True, inplace=True)
    return result

def using_sort(df):
    return df.sort('c3').groupby('c1', as_index=False).tail(1)

for N in (100, 1000, 2000):
    df = pd.DataFrame({'c1': {0: 'a', 1: 'a', 2: 'a', 3: 'b', 4: 'b', 5: 'b'},
                       'c2': {0: 'a', 1: 'c', 2: 'b', 3: 'b', 4: 'c', 5: 'a'},
                       'c3': {0: 1, 1: 3, 2: 2, 3: 10, 4: 12, 5: 7}})

    df = pd.concat([df]*N)
    df.reset_index(inplace=True, drop=True)

    timing = dict()
    for func in (reset_df_first, using_to_frame, using_sort):
        timing[func] = timeit.timeit('m.{}(m.df)'.format(func.__name__),
                              'import __main__ as m ',
                              number=10)

    print('For N = {}'.format(N))
    for func in sorted(timing, key=timing.get):
        print('{:<20}: {:<0.3g}'.format(func.__name__, timing[func]))
    print

rawDescription: How to get rows in pandas data frame, with maximal values in a column and keep the original index?

description: Get rows in pandas data frame, with maximal values in a column and keep the original index


code:
import ast

def literal_eval_with_callables(node_or_string, safe_callables=None):
    if safe_callables is None:
        safe_callables = {}
    if isinstance(node_or_string, str):
        node_or_string = ast.parse(node_or_string, mode='eval')
    if isinstance(node_or_string, ast.Expression):
        node_or_string = node_or_string.body
    try:
        # Python 3.4 and up
        ast.NameConstant
        const_test = lambda n: isinstance(n, ast.NameConstant)
        const_extract = lambda n: n.value
    except AttributeError:
        # Everything before
        _const_names = {'None': None, 'True': True, 'False': False}
        const_test = lambda n: isinstance(n, ast.Name) and n.id in _const_names
        const_extract = lambda n: _const_names[n.id]
    def _convert(node):
        if isinstance(node, (ast.Str, ast.Bytes)):
            return node.s
        elif isinstance(node, ast.Num):
            return node.n
        elif isinstance(node, ast.Tuple):
            return tuple(map(_convert, node.elts))
        elif isinstance(node, ast.List):
            return list(map(_convert, node.elts))
        elif isinstance(node, ast.Dict):
            return dict((_convert(k), _convert(v)) for k, v
                        in zip(node.keys, node.values))
        elif const_test(node):
            return const_extract(node)
        elif isinstance(node, ast.UnaryOp) and \
             isinstance(node.op, (ast.UAdd, ast.USub)) and \
             isinstance(node.operand, (ast.Num, ast.UnaryOp, ast.BinOp)):
            operand = _convert(node.operand)
            if isinstance(node.op, ast.UAdd):
                return + operand
            else:
                return - operand
        elif isinstance(node, ast.BinOp) and \
             isinstance(node.op, (ast.Add, ast.Sub)) and \
             isinstance(node.right, (ast.Num, ast.UnaryOp, ast.BinOp)) and \
             isinstance(node.right.n, complex) and \
             isinstance(node.left, (ast.Num, ast.UnaryOp, astBinOp)):
            left = _convert(node.left)
            right = _convert(node.right)
            if isinstance(node.op, ast.Add):
                return left + right
            else:
                return left - right
        elif isinstance(node, ast.Call) and \
             isinstance(node.func, ast.Name) and \
             node.func.id in safe_callables:
            return safe_callables[node.func.id](
                *[_convert(n) for n in node.args],
                **{kw.arg: _convert(kw.value) for kw in node.keywords})
        raise ValueError('malformed string')
    return _convert(node_or_string)

rawDescription: Is my eval implementation completely safe?


code:
f = pd.read_table('table.txt', names=['Measurement', 'Date', 'Time','CO2', 'Flow'])
f

rawDescription: Pandas DataFrame Cannot Read Data

description: Pandas DataFrame Cannot Read Data


code:
vals = [1,2,3]
vals[1] = FooWrapper("Bob")
vals
for x in vals: print(x)
this = vals[1]
this(10)
vals

rawDescription: List element Pointer in Python

description: List element Pointer in Python


code:
def missingint(i,j):
    return 3-i-j

rawDescription: Given two of three items, return the missing item


code:
def recursive_bubble_ands_up(expr):
    """ Bubble all 'and's in the expression up one level, no matter how nested.
    """
    # if the expression is just a single thing, like 'a', just return it.
    if is_atomic(expr):
        return expr
    # if it has an 'and' in one of its subexpressions
    #  (but the subexpression isn't just the 'and' operator itself)
    #  rewrite it to bubble the and up
    and_clauses = [('and' in subexpr and not is_atomic(subexpr))
                   for subexpr in expr]
    if any(and_clauses):
        first_and_clause = and_clauses.index(True)
        expr_before_and = expr[:first_and_clause]
        expr_after_and = expr[first_and_clause+1:]
        and_parts = expr[first_and_clause][1:]
        expr = ('and',) + tuple([expr_before_and + (and_part,) + expr_after_and
                                 for and_part in and_parts])
    # apply recursive_bubble_ands_up to all the elements and return result
    return tuple([recursive_bubble_ands_up(subexpr) for subexpr in expr])

def is_atomic(expr):
    """ Return True if expr is an undividable component
    (operator or value, like 'and' or 'a'). """
    # not sure how this should be implemented in the real case,
    #  if you're not really just working on strings
    return isinstance(expr, str)

rawDescription: replacing values in a nested tuple with the whole tuple

description: Replacing values in a nested tuple with the whole tuple


code:
fundict['hello']
hello

rawDescription: Syntax for a dictionary of functions?

description: Syntax for a dictionary of functions


code:
from win32api import GetSystemMetrics

width = GetSystemMetrics(0)
weight = GetSystemMetrics(1)

rawDescription: Python on windows, open plot windows next to each other


code:
while data != '':
    sig = signal.filtfilt(b, a, unpack(s,data))
    output_signal = pack(s,*sig)
    sys.stdout.write(output_signal)      # <===
    data = f.readframes(chunk)

rawDescription: python audio player filtered without jitter

description: Python audio player filtered without jitter


code:
def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

rawDescription: Matplotlib.pyplot : Save the plots into a pdf


code: Sum([ ZeroExt(4, Extract(i,i,st1)) for i in range(bits) ])

rawDescription: Finding BitVec weight efficently (aka access to bits of a bitvector) in z3


code:
a = [1, 2, 3, 3, 2, 4]
seen = set()
[x for x in a if not (x in seen or seen.add(x))]
seen

rawDescription: how to use a sentinel list in a comprehension?

description: Use a sentinel list in a comprehension


code:
c = np.dot(points.T,u)
print(c)

rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
import fileinput
import sys
import re
# use word boundaries so we only match "apples"
r = re.compile(r"\bapples\b")
for line in fileinput.input("test.txt",inplace=True):
    # will write the line as is or replace apples with oranges and write
    sys.stdout.write(r.sub("oranges",line))

rawDescription: Overwritting characters from a file in Python


code: max((k, (i, j)) for i, lst in enumerate(T) for j, (k, _) in enumerate(lst))

rawDescription: How to find the max number in this type of data structure in Python

description: Find the max number in this type of data structure in Python


rawDescription: Function that prints all the strings in A that start with '-1' or with '1'


code:
from scipy.misc import imsave, imread
a

rawDescription: Why do values in my 3D numpy array change when I write it to file?


code: children.config(bg="black", fg="blue")

rawDescription: Is it possible to use .tk_setPalette() on the content of only one Frame?


code:
p = subprocess.Popen(['/etc/openvpn/easy-rsa/build-key'], stdin=subprocess.PIPE)
p.communicate('\n'.join(['', '', '', '', '', 'yes', '']))
#                        ^^
#   use one of these for each item you want to press enter to before the "yes"

rawDescription: Simulate pressing "yes" after few "Enter" within bash command


code:
url_re = re.compile(r"""
       [^\s]             # not whitespace
       [a-zA-Z0-9:/\-]+  # the protocol and domain name
       \.(?!\.)          # A literal '.' not followed by another
       [\w\-\./\?=&%~#]+ # country and path components
       [^\s]             # not whitespace""", re.VERBOSE)

rawDescription: Making links clickable in retrieved tweets


code:
word = 'BANANA'
hidden_word = ["_ "] * len(word)
def click_1 (key):
    if key in word:
        for index, character in enumerate(word):
            if character == key:
                hidden_word[index] = character
        print (hidden_word)
    else:
        print ("Nope")

click_1('N')
click_1('B')
click_1('A')

rawDescription: Trying to find the same item in a list with the context of hangman


rawDescription: Python: Two-way Alphanumeric Encryption

description: Python: Two-way Alphanumeric Encryption


code:
# myModule.py
foo = "bar"

rawDescription: Python: Can i set global variables in a package __init__ module?


rawDescription: Apply a comparison between two numpy.arrays to only one column but retrieve whole rows


code:
from itertools import groupby
from operator import itemgetter
groups = groupby(sorted(data, key = itemgetter('key')), key = itemgetter('key'))
data_dict = {k : list(g) for k, g in groups}

rawDescription: nicer way to merge list of dictionaries by key

description: Nicer way to merge list of dictionaries by key


code:
#...
is_important = True if something else False
extra_context.update({'is_important': is_important})
#...

rawDescription: Making text bold with django

description: Making text bold with django


code:
if __name__ == '__main__':
    login(name, pwd)

rawDescription: should I use multiprocessing in all function call from the start function?

description: Should I use multiprocessing in all function call from the start function


code:
args = (re.escape(userstring), re.escape(userStrHEX), re.escape(userStrASCII))
x = re.compile("(%s|%s|%s)" % args, re.IGNORECASE)

rawDescription: I'm trying to implement a valid Regex pattern


code:
#!/usr/bin/env python

from PIL import Image, ImageChops

F_IN = "/path/to/image_in.jpg"
F_OUT = "/path/to/image_out.jpg"

size = (80,80)

image = Image.open(F_IN)
image.thumbnail(size, Image.ANTIALIAS)
image_size = image.size

thumb = image.crop( (0, 0, size[0], size[1]) )

offset_x = max( (size[0] - image_size[0]) / 2, 0 )
offset_y = max( (size[1] - image_size[1]) / 2, 0 )

thumb = ImageChops.offset(thumb, offset_x, offset_y)
thumb.save(F_OUT)

rawDescription: Resize image maintaining aspect ratio AND making portrait and landscape images exact same size?


code:
def my_filter_func(x):
    return x % 2 == 0

class FilterClass(object):

    def __init__(self):
        self.filter_func = my_filter_func

    def filter_data(self, data):
        return filter(self.filter_func, data)

rawDescription: How to store function in class atribute?

description: Store function in class atribute


code: list1 = list2 = []

rawDescription: Declaring an empty list

description: Declaring an empty list


code: Column(ArraySet(Integer))

rawDescription: SQLAlchemy/PostgreSQL mutable, deduplicated array


code: cmd= 'md5sum ' + path

rawDescription: Check md5sum of all files in a directory in python


rawDescription: Python Convert Int List to Decimal string then back to Int List


code: average = numpy.average(arr, axis=0)

rawDescription: Python: How would I get an average of a set of tuples?


rawDescription: Generate string of numbers python

description: Generate string of numbers python


code:
from tkinter import *
from functools import partial

ENTER = '7'
LEAVE = '8'

# extra argument - rectangle ID
def change_color_on_enter_or_leave(event, r_id):

    canvas = event.widget

    # you don't have to search IDs

    if event.type == ENTER:
        canvas.itemconfig(r_id, fill="orange")
    elif event.type == LEAVE:
        canvas.itemconfig(r_id, fill="red")

root = Tk()
canvas = Canvas(root, background="white")
label = Label(root)

for x in range(0, 200, 50):
    for y in range(0, 200, 50):

        # get rectangle ID
        r_id = canvas.create_rectangle((x, y), (x + 40, y + 40), fill='red', tag='rectangle') # tag "rectangle" use for something different

        # use rectangle ID with function
        canvas.tag_bind(r_id, '<Enter>', lambda event,t=r_id:change_color_on_enter_or_leave(event,t))
        canvas.tag_bind(r_id, '<Leave>', lambda event,t=r_id:change_color_on_enter_or_leave(event,t))

canvas.grid()
label.grid()

root.mainloop()

rawDescription: Tkinter canvas leave event isn't trigged


code:
import numpy as np
# turn data into numpy array for easier manipulation
data2 = np.array(data)
n     = len(data2)

# calculate fractions for each bin in bins
# astype('float') because otherwise you end up doing integer arithmetic
fracs = [ sum(data2>=bin).astype('float')/n for bin in bins ]

rawDescription: plotting bounded CDF of discrete count data in matplotlib python

description: Plotting bounded CDF of discrete count data in matplotlib python


code:
list_count = 0
indices = []
mac_times_array = []
for foundMacAddress in found_mac_list:
    mac_dict = {}
    indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
    grouped_times = []
    for index in indices:
        grouped_times.append(times[index])
    mac_dict[foundMacAddress] = grouped_times
    mac_times_array.append(mac_dict)

pprint.pprint(json.dumps(mac_times_array))

rawDescription: Specifying the keys in a JSON object with Python


code:
def generate_pdf_print(self,db,
                            str_report_name = 'OPENING BALANCE REPORT',
                            str_report_format = 'GENERAL',
                            lst_main_heading = [],
                            lst_header = [],
                            lst_report_header = [],
                            lst_page_header = [],
                            lst_footer = [],
                            lst_report_footer = [],
                            lst_page_footer = [],
                            lst_report_data = [],
                            bln_show_column_heading = True,
                            lst_col_title = [],
                            int_count_blocks_of_data_in_print = 1,
                            str_pdf_theme = 'Default'
                            ):

    lst_main_heading = eval(lst_main_heading)
    lst_header = eval(lst_header)
    lst_report_header = eval(lst_report_header)
    lst_page_header = eval(lst_page_header)
    lst_footer = eval(lst_footer)
    lst_page_footer = eval(lst_page_footer)
    lst_report_footer = eval(lst_report_footer)
    lst_report_data = eval(lst_report_data)
    bln_show_column_heading = True
    lst_col_title = eval(lst_col_title)

rawDescription: pass python list to ladon using suds

description: Pass python list to ladon using suds


code:
list = []
list()
del list
list()

rawDescription: REPL - recover callable after redefining it


code:
test_dict = {}
test_dict['number'] = [12,14,12,13]
test_dict['number2'] = [20,21,22,23]
print([j for i,j in zip(test_dict['number'],test_dict['number2']) if i==12])

rawDescription: Find all indices of a value in a dictionary python


rawDescription: Learning python... stumped. Where is the loop in this function?


rawDescription: re to identify range from string

description: Re to identify range from string


code:
class Well(models.Model):
    id = models.AutoField(db_column='ID', primary_key=True, verbose_name='DNS')
    block = models.ForeignKey(Block, db_column='Block_ID', verbose_name='Block', related_name="well")
    uwi = models.CharField(db_column='UWI', max_length=20, blank=True, verbose_name='UWI')
    welllocation = models.ForeignKey('Welllocation', db_column='WellLocation_ID', verbose_name='Location', related_name="well")
    # Plus a number of other columns

class Welldrillingdetails(models.Model):
    id = models.AutoField(db_column='ID', primary_key=True, verbose_name='DNS')
    well = models.ForeignKey(Well, db_column='Well_ID', verbose_name='Well', related_name='drillingdetails')
    casingdetails = models.ForeignKey(Casingdetails, db_column='CasingDetails_ID', verbose_name='Casing Name', related_name="drillingdetails")
    holesize = models.CharField(db_column='holeSize', max_length=15, blank=True, verbose_name='Hole Size (inch)')
    # Plus a number of other columns

rawDescription: Django using list of primary keys to fetch records


code: df = pd.DataFrame(lines, columns=header)

rawDescription: Import data into DataFrame with additional commas


rawDescription: Console colors (Windows)

description: Console colors (Windows)


code:
# initialize the list to store the dictionaries
# that will create the new DataFrame
new_df_dicts = []

# group on 'group'
for group, indices in dfm.groupby('group').groups.iteritems():
    # get the values in the 'match' column
    vals = dfm.ix[indices]['match'].values
    # choose every possible pair from the array of column values
    for i in range(len(vals)):
        for j in range(i+1, len(vals)):
            # compute the new values
            compare = vals[i] + ', ' + vals[j]
            if vals[i] == vals[j]:
                result = 'same'
            else:
                result = 'not same'
            # append the results to the DataFrame
            new_df_dicts.append({'group': group, 'compare': compare, 'result': result})

# create the new DataFrame
new_df = DataFrame(new_df_dicts)

rawDescription: Python pandas: Efficiently compare rows of a dataframe?


code:
key, = d
value, = d.values()

rawDescription: How to fetch the key/value pair of a dictionary only containing one item?

description: Fetch the key/value pair of a dictionary only containing one item


code:
j = Jungle6()
j()

rawDescription: How do I make an engine to change the current area of a game in Python?

description: Make an engine to change the current area of a game in Python


code:
import logging
import Colorer

logger = logging.getLogger()
logger_handler = logging.StreamHandler()
logger.addHandler(logger_handler)
logger_handler.setFormatter(Colorer.MyFormatter("%(message)s"))
logger.setLevel("DEBUG")

logging.debug("\t\tTHIS IS A REALY long DEBUG Message that works and wraps around great........")
logging.info("   THIS IS A REALY long INFO Message that works and wraps around great........")
logging.warning("THIS IS A REALY long WARNING Message that works and wraps around great........")
logging.error("\tTHIS IS A REALY long ERROR Message that works and wraps around great........")
logging.critical("THIS IS A REALY long CRITICAL Message that works and wraps around great........")

rawDescription: Logging Formatting Right Justify Level Name


rawDescription: String slicing with delimiter changing in length


code:
app = webapp2.WSGIApplication([('/', 'handlers.main.MainPage'),
                               ('/sign', 'handlers.guestbook.Guestbook')],
                              debug=True)

rawDescription: how to organise files with python27 app engine webapp2 framework

description: Organise files with python27 app engine webapp2 framework


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

rawDescription: Creating two completely independent plots in matplotlib and going back and forth between them


code:
from numpy import *

a = array([[1, 2, 3], [0, 3, NaN]])
where_are_NaNs = isnan(a)
a[where_are_NaNs] = 0

rawDescription: convert nan value to zero

description: Convert nan value to zero


code:
import struct
struct.pack('>B', 255)
struct.pack('>H', 255)
struct.pack('>I', 255)

rawDescription: python conversion int into arbitrary number of bytes

description: Python conversion int into arbitrary number of bytes


code:
f = lambda x: Series(np.histogram(x, bins=bins)[0], index=bins[:-1])
df1 = daily.apply(f)
df1

rawDescription: Plot timeseries of histograms in Python

description: Plot timeseries of histograms in Python


code:
from lxml import etree
from pprint import pprint

news_sources = {
    source.attrib['source'] : [feed.text for feed in source.xpath('./f')]
    for source in etree.parse('x.xml').xpath('/sources/sourceList')}

pprint(news_sources)

rawDescription: Generating nested lists from XML doc

description: Generating nested lists from XML doc


code:
class Process(wx.Panel):
    def loadMap(self, event):
        frame = MainFrame()
        frame.sPath = str(mapFile.readline()).strip("\n")
        frame.loadSource()

rawDescription: Changing an element in a different Frame in wxPython


rawDescription: Formulating an efficient DB query with highly challenging requirements (Django app)


code:
import  numpy as np
import ctypes as C

lib = C.cdll.LoadLibrary('pycon.exe')
lib.init( C.windll.kernel32.GetProcAddress( C.windll.msvcrt._handle,'printf'))

d = np.ones((5)).astype('double')
lib.fun(d.ctypes.data_as(C.POINTER(C.c_double)), C.c_size_t(5))

rawDescription: How to initialize CRT when doing LoadLibrary("*.exe")

description: Initialize CRT when doing LoadLibrary("*.exe")


code:
def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    Examples
    --------
    >>> func(1, "a")
    True
    """
    return True

rawDescription: How can I produce a numpy-like documentation?

description: Produce a numpy-like documentation


code: {k: v for k1, k2, v1, v2 in data for k, v in ((k1, v1), (k2, v2))}

rawDescription: Python: dict comprehension with multiple key-value pairs in the same time


code:
3
name

rawDescription: python split and reverse text file

description: Python split and reverse text file


code:
def sim_distance(prefs, person1, person2):
  # Get the list of shared_items
  p1, p2 = prefs[person1], prefs[person2]
  si = set(p1).intersection(set(p2))

  # Add up the squares of all the differences
  matches = (p1[item] - p2[item] for item in si)
  return sum(a * a for a in matches)

rawDescription: Euclidian distance between posts based on tags


code:
def f(a):
    print(a)

rawDescription: Can JSON for Python Encode/decode functions from text files?


rawDescription: Chart of mutable versus immutable types

description: Chart of mutable versus immutable types


code:
merged = df1[['ksat']].merge(df2[['ksat', 'PERCENTILE']], how='outer', sort=True)
merged
merged.bfill()

rawDescription: Python pandas dataframe: Find last occurrence of value less-than-or-equal-to current row


rawDescription: Mapping a list to a Huffman Tree whilst preserving relative order


code: struct.unpack('4s', 'test')[0]

rawDescription: unpack function in python

description: Unpack function in python


code:
import ipaddress
str(ipaddress.ip_address('fcef:b0e7:7d20:0000:0000:0000:3b95:0565'))
ip = ipaddress.ip_address('fcef:b0e7:7d20:0000:0000:0000:3b95:0565')
ip.compressed
ip.exploded

rawDescription: Abbreviating IPv6 addresses

description: Abbreviating IPv6 addresses


code:
from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
conn = engine.connect()
conn.execute(event.insert(),[
    {'source_id': 1, 'info': 'xyz', 'item': 'foo'},
    {'source_id': 1, 'info': 'xyz', 'item': 'bar'},
    ...
])

rawDescription: sqlalchemy 0.6 legacy database access?

description: Sqlalchemy 0.6 legacy database access


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

fig = plt.figure()
ax=fig.add_subplot(1,1,1)
ax.set_aspect(0.3)
x,y=np.random.random((2,100))
plt.scatter(x,y)

rawDescription: How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?


rawDescription: Pandas Rolling_std with Window using all previous row counts


code: a = m[i,:].toarray().flatten()

rawDescription: Dictionaries containing the biggest values


code:
import nltk
pattern = 'NNP,CC,NNP'
pattern = [pat.strip() for pat in pattern.split(',')]
text = '''Tristan/NNP and/CC Isolde/NNP and/CC the/DT fatalistic/NN horns/VBZ
          The/DT passionate/JJ violins/NN And/CC ominous/JJ clarinet/NN ;/:'''
tagged_token = [nltk.tag.str2tuple(word) for word in nltk.word_tokenize(text)]
for ngram in nltk.ingrams(tagged_token,len(pattern)):
    if all(gram[1] == pat for gram,pat in zip(ngram,pattern)):
        print(' '.join(word for word, pos in ngram))

rawDescription: navigating text file searches in python

description: Navigating text file searches in python


code:
class MyFuncs:

    @staticmethod
    def func(a, b):
        return a * b

    # ... define other functions

rawDescription: Can one define functions like in JavaScript?


code:
d = {1: 'foo'}
1 in d
2 in d

rawDescription: Ordering a nested dictionary by the frequency of the nested value


code: binary_inv = cv2.bitwise_not(binary)

rawDescription: Binarize pixels by value

description: Binarize pixels by value


code:
#! /usr/bin/python

n = 313105074639950943116 #just an example

#your algorithm
chars = []
buff = ''
s = str (n)
while s:
    if int (buff + s [0] ) < 256:
        buff += s [0]
        s = s [1:]
    else:
        chars.append (int (buff) )
        buff = ''
if buff: chars.append (int (buff) )

print ('You need to write these numbers converted to chars: {}'.format (chars) )
print ('This are {} bytes of data.'.format (len (chars) ) )
print ('But you cannot decompress it, because you lose leading zeros.')

chars = []
while n:
    chars.append (n & 0xff)
    n = n >> 8

print ('Now if you just write the number to a file without your algorithm:')
print ('You need to write these numbers converted to chars: {}'.format (chars) )
print ('This are {} bytes of data.'.format (len (chars) ) )
print ('And you can actually read it again.')

rawDescription: Compress a very large number (in Python)


code: 'The Matrix stars Keanu Reeves and had a reported budget of $80 million'

rawDescription: Python List in List ("Stuck")

description: Python List in List ("Stuck")


code:
import re

there = re.compile(r'''(?x)      # verbose flag: allows comments & whitespace
                       ^         # anchor to the start
                       ([^:]+)   # group with 1+ non-colons, the key
                       :\s*      # colon, then arbitrary whitespace
                       (.*)      # group everything that follows
                       $         # anchor to the end
                    ''')

rawDescription: Extracting data from a text file to use in a python script?


rawDescription: Plotting pandas groupby

description: Plotting pandas groupby


code:
word = 'QUICK'
sum(letter_score[c] for c in word)

rawDescription: dict comprehensions for mapping scrabble letter distribution

description: Dict comprehensions for mapping scrabble letter distribution


code:
def foo(x):
    sleep(0.1)
    # 50% chance to have a fault
    return x, x if random.rand() > 0.5 else -1

def successful_foo(x):
    '''Version of the foo(x) function that never fails.'''

    result = -1
    while result == -1:
        result = foo(x)
    return result

rawDescription: Dynamically add arguments to a Pool of workers


code:
class mydict(dict):
    def __missing__(self,key):
        return key

a = mydict()
a['asd']

rawDescription: Python Dictionary return requested key if value does not exist


code:
q = (
    session
    .query(A)
    .join(Stuff, A.stuff)  # @note: here you specify the relationship
    .filter(Stuff.id == X)
)

rawDescription: SQLAlchemy: how to select if in one list or another list?


code:
sample_count = 600 # Somehow determine how many samples are in your time window.
samples = Weather.objects.filter().exclude(time__lt=commence).exclude(time__gt=cease)
for s_num in range(0, sample_count, 10):
    s = samples[s_num]
    # Now you have one sample in s.

rawDescription: Scheduling Filter on Database with Time Interval


code: df = df.append(data,ignore_index=True)

rawDescription: Append new data to a dataframe

description: Append new data to a dataframe


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code:
from tkinter import *

class ToolBox(Frame):
    def __init__(self, master=None,
                 width=100, height=300):
        Frame.__init__(self, master,
                       width=width, height=height)
        for i in range(2):
            self.grid_columnconfigure(i, weight=1)
        for j in range(3):
            self.grid_rowconfigure(j, weight=1)

        Button(self, text="B").grid(row=0, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=0, column=1, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=1, column=0,sticky=(N,E,W,S))
        Button(self, text="B").grid(row=1, column=1, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=2, column=0, sticky=(N,E,W,S))
        Button(self, text="B").grid(row=2, column=1, sticky=(N,E,W,S))

root = Tk()
root.geometry("400x400")

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

ToolBox(root).grid(sticky="news")

root.mainloop()

rawDescription: Arranging size of a frame in tkinter

description: Arranging size of a frame in tkinter


code:
store = gtk.ListStore(*coltypes)
for act in itemlist:
    store.append(act)

rawDescription: pySQLite integration to pyGtk treeview

description: PySQLite integration to pyGtk treeview


code:
'{:,}'.format(var)    # format an integer
'{:,.2f}'.format(var) # format a decimal or float

rawDescription: how to add thousands separator to a number that has been converted to a string in python?

description: Add thousands separator to a number that has been converted to a string in python


code: file = fh.read()

rawDescription: removing duplicates from a list of strings

description: Removing duplicates from a list of strings


code:
def DisplayIt(request):
    somestring = ""
    for a in A.objects.filter(b__name__isnull=False):
        somestring += a.b.name

rawDescription: Django 1.4: Get a field in a foreign key object (null=True), get None or field value


code:
numbers_dict = {"One": "First",
    "Two": "Second",
    "Three": "Third",
    "Four": "Fourth",
    "Five": "Fifth",
    "Six": "Sixth",
    "Seven": "Seventh"}

rawDescription: Changing values of a list by getting them from a dictionary (Python)