code:
from django.db import models
from polymorphic import PolymorphicModel

class AbtractRuleObject(models.Model):
    class Meta:
        abstract = True

    def filter_queryset(self, queryset):
        """Will handle actual filtering of the event queryset"""
        raise NotImplementedError

    def match_instance(self, instance):
        raise NotImplementedError

class RuleSet(AbtractRuleObject):
    """Will manage the painful part o handling the OR / AND logic inside the database"""
    NATURE_CHOICES = (
        ('or', 'OR'),
        ('and', 'AND'),
    )
    nature = models.CharField(max_length=5, choices=NATURE_CHOICES, default='and')

    # since a set can belong to another set, etc.
    parent_set = models.ForeignKey('self', null=True, blank=True, related_name='children')

    def filter_queryset(self, queryset):
        """This is rather naive and could be optimized"""
        if not self.parent_set:
            # this is a root rule set so we just filter according to registered rules
            for rule in self.rules:
                if self.nature == 'and':
                    queryset = rule.filter_queryset(queryset)
                elif self.nature == 'or':
                    queryset = queryset | rule.filter_queryset(queryset)
        else:
            # it has children rules set
            for rule_set in self.children:
                if self.nature == 'and':
                    queryset = rule_set.filter_queryset(queryset)
                elif self.nature == 'or':
                    queryset = queryset | rule_set.filter_queryset(queryset)
        return queryset

    def match_instance(self, instance):
        if not self.parent_set:
            if self.nature == 'and':
                return all([rule_set.match_instance(instance) for rule_set in self.children])
            if self.nature == 'any':
                return any([rule_set.match_instance(instance) for rule_set in self.children])
        else:
            if self.nature == 'and':
                return all([rule_set.match_instance(instance) for rule_set in self.children])
            if self.nature == 'any':
                return any([rule_set.match_instance(instance) for rule_set in self.children])

class Rule(AbtractRuleObject, PolymorphicModel):
    """Base class for all rules"""
    attribute = models.CharField(help_text="Attribute of the model on which the rule will apply")
    rule_set = models.ForeignKey(RuleSet, related_name='rules')

class DateRangeRule(Rule):
    start = models.DateField(null=True, blank=True)
    end = models.DateField(null=True, blank=True)

    def filter_queryset(self, queryset):
        filters = {}
        if self.start:
            filters['{0}__gte'.format(self.attribute)] = self.start
        if self.end:
            filters['{0}__lte'.format(self.attribute)] = self.end
        return queryset.filter(**filters)

    def match_instance(self, instance):
        start_ok = True
        end_ok = True
        if self.start:
            start_ok = getattr(instance, self.attribute) >= self.start
        if self.end:
            end_ok = getattr(instance, self.attribute) <= self.end

        return start_ok and end_ok

class MatchStringRule(Rule):
    match = models.CharField()
    def filter_queryset(self, queryset):
        filters = {'{0}'.format(self.attribute): self.match}
        return queryset.filter(**filters)

    def match_instance(self, instance):
        return getattr(instance, self.attribute) == self.match

class StartsWithRule(Rule):
    start = models.CharField()

    def filter_queryset(self, queryset):
        filters = {'{0}__startswith'.format(self.attribute): self.start}
        return queryset.filter(**filters)

    def match_instance(self, instance):
        return getattr(instance, self.attribute).startswith(self.start)

rawDescription: Storing logic inside database

description: Storing logic inside database


code:
words = [u'dose rate', u'object', u'dose', u'rate', u'computation']
[w1 for w1 in words if not any(w1 in w2 for w2 in words if w2 != w1)]

rawDescription: How to remove inception words in list?

description: Remove inception words in list


code:
def rare_wrapper(x):
    size = x['size']
    y = x.values[:-1]
    return rare(y, size)

rawDescription: Pandas apply with argument that varies by row


code: map(lambda g: map(file_out.write, g), groups.itervalues())

rawDescription: Python: using a List Comprehensions instead of loop in order to improve the performance


rawDescription: combinations of elements of different tuples in the list

description: Combinations of elements of different tuples in the list


code:
def _login_check(f):
    @wraps(f)
    def wrapper(self):
        if self.log_in():
            f(self)
        else:
            raise MyError('Not Logged In')
    return wrapper

rawDescription: Python class function not returning variable


code:
def count(mylist):
    newlist = []
    newlist.append(mylist[0])
    stor = False
    for i in mylist:
        stor = False
        for j in newlist:
            if j == i:
                stor = True # stor == True test for equality
        if not stor:
            newlist.append(i)
    return len(newlist) # you do not want the list itself but its length

rawDescription: Count different numbers in list python

description: Count different numbers in list python


rawDescription: Python scrape style display:none

description: Python scrape style display:none


code:
def f(x,y):
    return np.sin((x + y))
x = y = np.arange(-5, 5, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([f(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

gx,gy = np.gradient(Z,0.05,0.05)

rawDescription: Gradient calculation with python

description: Gradient calculation with python


code:
import random
import igraph

N = 10
g = igraph.Graph.Full(N)
i, j = random.sample(range(g.vcount()), 2)
g.delete_edges([(i,j)])
print(g.ecount(), N*(N-1)/2)

rawDescription: Deleting an edge between two vertices [igraph python]


rawDescription: Pattern for multiplicity in python

description: Pattern for multiplicity in python


code:
for i in range(len(a)):      # this gets the basic idea across
    a[i] += 1

for i, _ in enumerate(a):    # this one uses enumerate() instead of range()
    a[i] += 1

for i, x in enumerate(a):    # this one is nice for more complex operations
    a[i] = x + 1

rawDescription: Grasping the basics of in-place operations


code: o = classToUse()

rawDescription: In Python, what's the correct way to instantiate a class from a variable?


code: [c/t for c,t in zip(conversions, trials)]

rawDescription: How do I divide the members of a list by the corresponding members of another list in Python?

description: Divide the members of a list by the corresponding members of another list in Python


code:
types = [doc_type]
if doc_type == 4:
    types.append(5)
invoices = Invoice.objects.filter(type__in=types)
if status is not None:
    invoices = invoices.filter(status=status)

rawDescription: Django conditional queries: How can I avoid this?


code:
data = "AAABAABAAABIAABIAABAA"

result, count = [], 0
for s in data.split('B'):
    result.append([(count, count+len(s)), s])
    count += len(s)
print(result)

rawDescription: Prefixing the results of string.split with the substring indices of each result


rawDescription: How to filter a python dataframe by the maximum grouped Value of a specific column

description: Filter a python dataframe by the maximum grouped Value of a specific column


code: np.delete(new_array,np.where([y.size==0 for y in new_array]))

rawDescription: remove empty numpy array

description: Remove empty numpy array


code:
all_joint  = cmds.ls(type='joint')
for each_joint in all_joints:
    do_something(each_joint)

rawDescription: Suffix if statement

description: Suffix if statement


rawDescription: Dynamic parameters with Python's retry decorator


code:
rows_to_keep = [1, 3, 5, 6]
...
for row in rdr:
    newrow = list()
    for n in rows_to_keep:
        newrow.append(row[n])
    wtr.writerow(newrow)

rawDescription: Dynamic arguments in python write

description: Dynamic arguments in python write


code:
def fmtRow(cursor, row):
    di = dict()
    for i, col in enumerate(cursor.description):
        di[col] = row[i]
    return di

rawDescription: Get query result as a tuple to make substitution


code:
def addnodes(names):
    parent = root
    for name in names:
        newnode = Node.byname.get(name)
        if newnode is None:
            newnode = Node(name, parent)
        parent = newnode

rawDescription: Python: tree structure and numerical codes?


code:
from operator import itemgetter

tple_list = [('4', '4', '1', 'Bart', 'Simpson'),
('1', '2', '6', 'Lisa', 'Simpson'),
('6', '3', '4', 'Homer', 'Simpson'),
('2', '3', '1', 'Hermione', 'Nobody'),
('1', '2', '3', 'Bristol', 'Palace')]

tple_list.sort(key=itemgetter(4, 3)) # lastname, firstname
print(tple_list)

rawDescription: Sort list of tuples by specific tuple element in Python 3


code:
class Player(pygame.sprite.Sprite):
    def __init__ (self, frames, *groups):
        super(player,self).__init__(*groups)
        self.frame = 0
        self.frames = frames
        ...

    def update(self):
        ...  # code to select the current frame

        self.frame = frame
        self.image = self.frames[self.frame]

rawDescription: sprite_sheet system in python and pygame

description: Sprite_sheet system in python and pygame


code:
from .base_tests import TestData

class SubclassOfTestData(TestData):
    # Inherits `setUpTestData`
    pass

rawDescription: Django: Keeping setUpTestData DRY

description: Django: Keeping setUpTestData DRY


code:
#!/usr/bin/env python3
import asyncio

@asyncio.coroutine
def func_normal():
    print('A')
    yield from asyncio.sleep(5)
    print('B')
    return 'saad'

@asyncio.coroutine
def func_infinite():
    for i in range(10):
        print("--%d" % i)
    return 'saad2'

loop = asyncio.get_event_loop()
tasks = func_normal(), func_infinite()
a, b = loop.run_until_complete(asyncio.gather(*tasks))
print("func_normal()={a}, func_infinite()={b}".format(**vars()))
loop.close()

rawDescription: Getting values from functions that run as asyncio tasks


code:
def rot90(m, k=1, axis=2):
    """Rotate an array by 90 degrees in the counter-clockwise direction around the given axis"""
    m = numpy.swapaxes(m, 2, axis)
    m = numpy.rot90(m, 2)
    m = numpy.swapaxes(m, 2, axis)
    return m

rawDescription: How to calculate all 24 rotations of 3d array?

description: Calculate all 24 rotations of 3d array


rawDescription: Saving an Object (Data persistence in Python)


code:
class Cell(object):
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

    def copy(self):
        if self.next is None:
            return Cell(self.value)
        else:
            return Cell(self.value, self.next.copy())

rawDescription: Python copy and concatenate linked lists, preserve order


rawDescription: Compute daily climatology using pandas python


code:
def find_text(text, matches = lambda x: x.group(1) if x else ''):
    return matches(PATTERN.search(text))

assert find_text('foo=bar,key=value,beer=pub') == 'value'
assert find_text('no match here') == ''

rawDescription: Getting captured group in one line

description: Getting captured group in one line


code:
@post('/login')
def login():
    """Authenticate users"""
    username = post_get('username')
    password = post_get('password')
    aaa.login(username, password, fail_redirect='/login')
    dbname = 'mydb'
    connection = pymongo.MongoClient(os.environ['OPENSHIFT_MONGODB_DB_URL'])
    db = connection[dbname]
    collection = db.myCollection
    href = 'my-title'
    query = {'title':href}
    projection = {'_id':0,'content':1}
    cursor = collection.find_one(query,projection)
    response.content_type = 'application/json'
    return dumps(cursor)

rawDescription: How to load MongoDB database content 'in place' after bottle-cork login?

description: Load MongoDB database content 'in place' after bottle-cork login


code:
with open('d.txt', 'r') as infile:
    f = infile.readlines()
    with open('filtered_part1.txt', 'w') as outfile:
        for i in range(len(f)):
            line = f[i]
            if line[16] == '0':
                i += 1
                break
            outfile.write(line)
    while f[i][16] == '0': # skip a few lines
        i += 1
    with open('filtered_part2.txt', 'w') as outfile:
        while i < len(f):
            outfile.write(f[i])
            i += 1

rawDescription: Parsing Data with non-uniform rows in python


code:
import numpy as np
import cv2

img = cv2.imread("peppers.png", 0)

kernel = np.ones((3,3), np.float32) / -9.0
kernel[1][1] = 8.0/9.0

out = cv2.filter2D(img.astype(np.float32), -1, kernel)
out = (out - out.min()) / (out.max() - out.min())

cv2.imshow("image", out)
cv2.waitKey(0)

rawDescription: How do I write this in OpenCV with Python?

description: Write this in OpenCV with Python


code:
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
# with this, your media directory will be the same directory than your settings.py file
# you can also use a standard path like "/var/www/media"
# IMPORTANT : In any case, you have to create the directory by hand
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"

rawDescription: Django - Images not displaying properly

description: Django - Images not displaying properly


rawDescription: How to clean string coming from index

description: Clean string coming from index


code: high = mid

rawDescription: Python number guessing game

description: Python number guessing game


rawDescription: Whats the best way to iterate over multidimensional array and tracking/doing operations on iteration index


code:
def getsize(filename):
    """Return the size of a file, reported by os.stat()."""
    return os.stat(filename).st_size

rawDescription: Whats the best way to get the filesize?

description: Whats the best way to get the filesize


code:
import code

code.interact(local=locals())

rawDescription: python: run interactive python shell from program

description: Python: run interactive python shell from program


code:
similarityArray = doACalculation(np.indices((smallerDim, n)))
mat[:smallerDim] = np.abs(1.0 / (similarityArray + 1))

rawDescription: Optimizing matrix writes in python/numpy


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

A = np.random.random((20,20))
B = np.random.random((20,20))

array_1 = A/B    # A and B are 2 arrays, same shape etc ..

# Mask the array with the required limits
array_1 = np.ma.masked_where(array_1 > 1, array_1)

fig1 = plt.figure()
ax1  = plt.subplot(111)
fig_step1 = ax1.imshow(array_1, interpolation='nearest')
fig1.colorbar(fig_step1,ax=ax1)
ax1.set_xlabel("X (arcmin)")
ax1.set_ylabel("Y (arcmin)")
ax1.set_title("No limits, but masked")

rawDescription: Set the colorbar in function of data

description: Set the colorbar in function of data


code:
fig, ax = plt.subplots()
marker, = ax.plot([0.2], [0.3], linestyle='none', marker='+')

rawDescription: cross hairs in python animation

description: Cross hairs in python animation


code:
x    = np.arange(20.)
flux = x * 2 + 1
mag  = flux_to_mag(flux)

MagTransform = MagScale.InvertedMagTransform(0)

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

ax_flux.plot(x, flux,'-')
ax_flux.set_ylim([1,40])
ax_flux.set_ylabel('flux')

ax_mag  = ax_flux.twinx()
ax_mag.set_ylim(MagTransform.transform_non_affine(ax_flux.get_ylim())) #There may be an easier to do this.
ax_mag.set_yscale('mag')

ax_mag.plot(x,mag,'+')
plt.show()

rawDescription: Two corresponding y-axis

description: Two corresponding y-axis


code:
import csv
data = [[int(i) for i in ln] for ln in csv.reader(open(filename), delimiter=';')]

rawDescription: How can i split text data to a list?

description: Split text data to a list


code: int(str(number), 6)

rawDescription: Converting base 6 to decimal?

description: Converting base 6 to decimal


code:
января
февраля
марта
апреля
мая
июня
июля
августа
сентября
октября
ноября
декабря

rawDescription: Different datetime.strftime output with same locale settings


rawDescription: python average bitrate per second

description: Python average bitrate per second


code: df.index = np.arange(1, len(df) + 1)

rawDescription: In Python pandas, start row index from 1 instead of zero without creating additional column


code:
from datetime import datetime
today = datetime.utcnow().date()
today

rawDescription: Determine start and end time of current day (UTC -> EST -> UTC) ; Python


code:
def chop_char(s):
    if len(s) > 1:
        if s[-2].istitle() and not s[-1].istitle():
            return s[:-1]
    return s

rawDescription: regular expression: chopping last character if second last is upper case?

description: Regular expression: chopping last character if second last is upper case


rawDescription: Probabilistic selection from a numpy array


code:
mb.menu.add_command(label="Argonian", command=lambda: changename("Argonian"))
mb.menu.add_command(label="Khajiit", command=lambda: changename("Khajiit"))

rawDescription: Creating a drop down menu item selection Python


code:
[i+1 for i in a]
[i<2 for i in a]

rawDescription: Numpy: return boolean array after condition checking


code:
u'''line[0] is -

line[0] is 1
Printing field 1
    17824

line[0] is 2
Printing field 2
    20131125192004.9

line[0] is 3
Printing field 3
    690714s1969    dcu           000 0 eng

line[0] is 4
Printing field 4
a      75601809

line[0] is 4
Printing field 4
a   DLC

line[0] is 4
Printing field 4
b   eng

line[0] is 4
Printing field 4
c   DLC

line[0] is 5
Printing field 5
a   WA 750

line[0] is -

line[0] is 1
Printing field 1
    3224

line[0] is 2
Printing field 2
    20w125192004.9

line[0] is 3
Printing field 3
    690714s1969    dcu           000 0 eng

line[0] is 5
Printing field 5
a   WA 120

line[0] is -

line[0] is 1
Printing field 1
    6563453

line[0] is 2
Printing field 2
    2013341524626245.9

line[0] is 3
Printing field 3
    484914s1969    dcu           000 0 eng

line[0] is 4
Printing field 4
a      75601809

line[0] is 4
Printing field 4
a   eng

line[0] is 4
Printing field 4
c   DLC

line[0] is 5
Printing field 5
a   WA 345'''

rawDescription: Python: iteration problems

description: Python: iteration problems


code:
def kurt(X, w):
    n, m = X.shape
    K = np.zeros_like(X)

    for i in xrange(w, n-w):                       # 5000 iterations
        for j in xrange(w, m-w):                   # 5000 iterations
            x = X[i-w:i+w+1,j-w:j+w+1].flatten()   # copy 25*25=625 values
            x -= x.mean()                          # calculate and subtract mean
            x /= np.sqrt((x**2).mean())            # normalize by stddev (625 mult.)
            K[i,j] = (x**4).mean() - 3.            # 2*625 = 1250 multiplications
    return K

rawDescription: Implementing a "Kurtosis filter" using scipys generic_filter


code:
from itertools import izip_longest

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] )
for a,b,c,d in zip(*izip_longest(*tup)):
    print(a,b,c,d)
(1, 2, None, None)
(2, 3, 5, None)
(4, 3, None, None)
(4, 5, 6, 7)

rawDescription: python - iterate through list whose elements have variable length

description: Python - iterate through list whose elements have variable length


code: self.ref_id = self.canvas.create_image(132,100, image = self.photo)

rawDescription: Tkinter canvas refreshing

description: Tkinter canvas refreshing


code:
def before_step(context, step):
    context.step = step

rawDescription: How to get the current behave step with Python?

description: Get the current behave step with Python


code:
def new_sku(s):
    s = s[::-1]
    already_added = False
    new_sku = str()

    for i in s:
        if not already_added:
            if (i < 'Z'):
                already_added = True
            new_sku += chr((ord(i)+1)%65%26 + 65)
        else:
            new_sku += i

    if not already_added: # carry still left?
        new_sku += 'A'

    return new_sku[::-1]

rawDescription: Addition of chars adding one character in front


code:
def guessSize(sets,n,trials):
    return max(len(intersect(random.sample(sets,n))) for trial in range(trials))

def maxIntersection(sets,n,trials = 100000):
    k = guessSize(sets,n,trials)
    filteredSets = [s for s in sets if len(s) >= k]
    return largestIntersection(filteredSets,n)

rawDescription: Find all subsets from list of sets that appears in at least N different sets


rawDescription: Proxy pattern in Python

description: Proxy pattern in Python


code:
pw = ''
while len(pw) < 6 or len(pw) > 12:
    pw = raw_input('Please enter a password between 6-12 characters long: ')

rawDescription: Restart a while loop?

description: Restart a while loop


code: out = data.ravel()[ind.ravel() + np.repeat(range(0, 8*ind.shape[0], 8), ind.shape[1])].reshape(ind.shape)

rawDescription: Extract elements of a 2d array with indices from another 2d array


code:
import numpy as np
seq = np.array(range(100))
seq2 = seq.reshape((10, 10))
seq2[:, :2]
seq2[:, :2].reshape((2*10,))

rawDescription: What is the pythonic way of slicing an array into stepped contiguous blocks?


code:
query = Category.select().order_by(Category.name)
return jsonify({'rows':[model_to_dict(c) for c in query]})

rawDescription: Get full result back from PeeWee query (for conversion to JSON)


rawDescription: Split list of datetime objects into keys(date) and values(times)


code:
import Tkinter as tk

window = tk.Tk()
var = tk.StringVar()
def validate(*args):
    print("Validation took place")
    return True
entry = tk.Entry(validate="focusin", validatecommand=validate)
print("Entry created. Associating textvariable")
entry.config(textvariable=var)
print("textvariable associated. Changing value")
entry.config(validate="none")
var.set("Text")
entry.config(validate="focusin")
print("Value changed")
entry.pack()
tk.mainloop()

rawDescription: Preventing a tkinter Entry from gaining focus when its associated StringVar changes


code:
import wx
a = wx.App()
user_string = wx.GetTextFromUser("Enter Equation:")

rawDescription: How to pop up the python console?

description: Pop up the python console


rawDescription: Does a line profiler for code require a parse tree and is that sufficient?


rawDescription: Python Optimize Grouper Function to avoid None elements


code: ftp.retrbinary('RETR %s' % filename, fhandle.write)

rawDescription: Python shutil copyfile - missing last few lines


code:
import re
t = "foo <bar e word> f ga <foo b>"
t2 = re.sub(r"(^|\s+)(?![^<>]*?>)", " #", t).lstrip()
t2

rawDescription: Regular expression that takes <...> as one item in "foo bar <hello world> and so on" (Goal: Simple music/lilypond parsing)


rawDescription: Python parse issue

description: Python parse issue


rawDescription: How to solve TypeError: cannot serialize float Python Elementtree

description: Solve TypeError: cannot serialize float Python Elementtree


code:
s = "This is my test string"
words = s.split()

for i in range(0,len(words)):
    for j in range(0,i+1):
        print(words[j]),  # add comma after print statement to not enforce newline
    print  # print newline here

rawDescription: how to sort csv file with python to progressively add rows of data to output

description: Sort csv file with python to progressively add rows of data to output


code:
for _, item in zip(range(limit), items):
    print(item)

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code:
from itertools import chain
tup_after = list(chain.from_iterable(tup_Before))

rawDescription: Flattening a list of tuples

description: Flattening a list of tuples


code:
import matplotlib.mlab as mlab
import numpy as np
import scipy

def define_grid(rawdata):
    xmin, xmax = np.amin(rawdata[:, 1]), np.amax(rawdata[:,1])
    ymin, ymax = np.amin(rawdata[:, 2]), np.amax(rawdata[:,2])

    x, y, z = rawdata[:, 1], rawdata[:, 2], rawdata[:, 0]

    # Size of regular grid
    ny, nx = (ymax - ymin), (xmax - xmin)

    # Generate a regular grid to interpolate the data.
    xi = np.linspace(xmin, xmax, nx)
    yi = np.linspace(ymin, ymax, ny)
    xi, yi = np.meshgrid(xi, yi)

    # Interpolate using delaunay triangularization
    zi = mlab.griddata(x,y,z,xi,yi)
    return xi, yi, zi

def grid_as_array(xi,yi,zi):
    xi_flat, yi_flat, zi_flat = np.ravel(xi), np.ravel(yi), np.ravel(zi)

    # reduce arrays for faster calculation, take only every second element
    xi_red, yi_red, zi_red = xi_flat[1::2], yi_flat[1::2], zi_flat[1::2]

    # stack to array with elements [x y z], but there are z values that are 'nan'
    xyz_with_nan = np.hstack((xi_red[:, np.newaxis], yi_red[:, np.newaxis],
                              zi_red[:, np.newaxis]))

    # sort out those elements with 'nan'
    xyz = xyz_with_nan[~np.isnan(xyz_with_nan).any(axis=1)]
    return xyz

rawDescription: Finding nearest xy-point in numpy array and second nearest with condition


code:
import time

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
for _ in range(8):
    actions.send_keys(Keys.SPACE).perform()
    time.sleep(1)

rawDescription: Python Selenium press down arrow to dispay all page contents


code:
import multiprocessing as mp
import itertools as IT
import logging

logger = mp.log_to_stderr(logging.DEBUG)
logger.setLevel(logging.DEBUG)

if __name__ == '__main__':
    pool = mp.Pool()
    for module, result in IT.izip(modules, results):
        pool.apply_async(module.save, args=(result, options))

    pool.close()
    pool.join()

rawDescription: Distributing tasks to modules in python

description: Distributing tasks to modules in python


code:
#!/usr/bin/env python
with open('letters') as file:
    letters = file.read().splitlines()

def combine_ids(letters):
    with open('numbers') as file:
        for line in file:
            id, space, numbers_str = line.lstrip().partition(' ')
            try:
                numbers = list(map(int, numbers_str.split(',')))
            except ValueError:
                continue # skip invalid lines
            for n in numbers:
                try:
                    yield letters[n], id
                except IndexError:
                    pass

result = dict(combine_ids(letters))
print(result)

rawDescription: Iterate and match in large files in python


code: sum(f(x) for x in xlist)

rawDescription: Quickest way to sum(f(x)) in Python

description: Quickest way to sum(f(x)) in Python


code:
while len(luckynumbers) < 3000:
    item = sieve[0]
    luckynumbers.append(item)
    del sieve[::item]

rawDescription: Python: speed up removal of every n-th element from list


rawDescription: Converting Python dict to kwargs?

description: Converting Python dict to kwargs


rawDescription: wxPython wx.TextCtrl dynamically resizing to fill panel width

description: WxPython wx.TextCtrl dynamically resizing to fill panel width


rawDescription: Define a column type as 'list' in Pandas


rawDescription: Transform a 3 columns (x, y, result) Python Pandas DataFrame to a DataFrame of result values with x (unique) as row and y (unique) as column


code:
def get_col_name(row):
    b = (df.ix[row.name] == row['value'])
    return b.index[b.argmax()]

rawDescription: Get column name where value is something in pandas dataframe


code: df.groupby(level=0).apply(lambda x:x.head(int(x.shape[0] * 0.5))).reset_index(level=0, drop=True)

rawDescription: pandas - get a fraction of each multi-index level label rows

description: Pandas - get a fraction of each multi-index level label rows


code:
def parse(self, response):
    hxs = HtmlXPathSelector(response)
    rows = hxs.select('//div[@class="content"]/p[@class="row"]')

    for row in rows:
        item = CraigslistSampleItem()
        link = row.xpath('.//span[@class="pl"]/a')
        item['title'] = link.xpath("text()").extract()
        item['link'] = link.xpath("@href").extract()
        item['price'] = row.xpath('.//span[@class="l2"]/span[@class="price"]/text()').extract()

        url = 'http://medford.craigslist.org{}'.format(''.join(item['link']))
        yield Request(url=url, meta={'item': item}, callback=self.parse_item_page)

rawDescription: Python Recursive Scraping with Scrapy

description: Python Recursive Scraping with Scrapy


code:
#!/usr/bin/env python
import os
import shutil
import sys

with os.fdopen(sys.stdin.fileno(), 'rb') as input_file,\
     open(sys.argv[1], 'wb') as output_file:
    shutil.copyfileobj(input_file, output_file)

rawDescription: bash or python script to read binary data from STDIN and save to a file

description: Bash or python script to read binary data from STDIN and save to a file


rawDescription: Python remove whitespace from regex substring match in file


code:
import pprint
pprint.pprint(out[:4])
pprint.pprint(out[-4:])

rawDescription: Python all combinations for multiple lists with variable k


code:
import a
mydocstring = a.__doc__

rawDescription: Getting doc string of a python file

description: Getting doc string of a python file


code:
a=np.arange(6)
b=np.zeros((6,3))
b[np.arange(6),np.arange(3).repeat(2)]=a
b

rawDescription: change the format of a numpy array with no loops

description: Change the format of a numpy array with no loops


code:
x = x(u, v)
y = y(u, v)
z = z(u, v)

rawDescription: Ploting solid of revolution in Python 3 (matplotlib maybe)


code:
def months_between(d1, d2):
    dd1 = min(d1, d2)
    dd2 = max(d1, d2)
    return (dd2.year - dd1.year)*12 + dd2.month - dd1.month

In [125]: months_between(pd.to_datetime('2015-01-02 12:13:14'), pd.to_datetime('2012-03-02 12:13:14'))
Out[125]: 34

rawDescription: pandas: function equivalent to SQL's datediff()?

description: Pandas: function equivalent to SQL's datediff()


code:
import requests
r = requests.post('http://server/myapp/method',
    data=file('binary_data_file.bin','rb').read())

rawDescription: pycurl equivalent of "curl --data-binary"

description: Pycurl equivalent of "curl --data-binary"


code:
ax.scatter(x, y, color = rgb)
plt.show()
# plt.savefig('/tmp/out.png')    # to save the figure to a file

rawDescription: Plot 2-dimensional NumPy array using specific columns


code:
byte_str = uni_str.encode('utf-8')
byte_str = byte_str[:size].decode('utf-8', 'ignore').encode('utf-8')

rawDescription: Fixed length data field and variable length utf-8 encoding


code:
user_obj = authenticate(username=account, password=passwd)
profile_obj = UserProfile.objects(user = user_obj).first()
profile_obj.name = "Mongo"
profile_obj.save()

rawDescription: Migrating From Django to Pyramid

description: Migrating From Django to Pyramid


code:
if host_id in myDict.keys():
    speed = myDict[host_id]

rawDescription: search dictionary in python for the matching value

description: Search dictionary in python for the matching value


code: GraphicsPage (someParent, 20, 30)

rawDescription: How to pass arguments to a custom class in python?

description: Pass arguments to a custom class in python


code:
def select_sample(pop, size):
    x = pop[-size:]
    pop[-size:] = []
    return x

rawDescription: Selection without replacement - by mutating the list


code: newstring = re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring)

rawDescription: find string with format '[number]' using regex

description: Find string with format '[number]' using regex


code:
with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Do stuff with byte.
        byte = f.read(1)

rawDescription: Reading binary file in Python and looping over each byte


code:
@endpoints.api(name='healthsecure', version='v1',
           allowed_client_ids=[WEB_CLIENT_ID, ANDROID_CLIENT_ID,
                               IOS_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID],
           audiences=[ANDROID_AUDIENCE],
           scopes=[endpoints.EMAIL_SCOPE])
class HealthSecureApi(remote.Service):
      """healthsecure API v1."""
      @Person.method(path='person', http_method='POST', name='person.insert')
      def PersonInsert(self, person):

          person.do_insert(person.name)

          return person

rawDescription: App won't display results inserted by api, will for ones inserted by site


code:
def myupdate( self ):
    return db( db.table.id == id ).update( field1 = self.field1,
                                           field2 = self.field2
                                           )

rawDescription: web2py: how to update multiple fields in table

description: Web2py: how to update multiple fields in table


code:
directions = {"UP":move(steps,operator.add,"x"),
              "DOWN":move(steps,operator.sub,"x"),
              "RIGHT":move(steps,operator.add,"y"),
              "LEFT":move(steps,operator.sub,"y")}

rawDescription: global varriable doesn't change

description: Global varriable doesn't change


code:
import string
if set(string.ascii_lowercase) == set(sentence):
    print('pangram')
...

rawDescription: Testing sentence against string of alphabet to see if all letters are in the sentence


code:
my_list=[]
for i in xrange(53,256):
    for j in xrange(0,208):
        for k in xrange(0,208):
            item = str(hex(i))+str(hex(j))+str(hex(k))
            item2 = item.replace("0x", "")
            my_list.append(item2)

rawDescription: Create a list of hex codes given an Rgb range


code: hashdict = dict(zip(df['ID'], df['NAME']))

rawDescription: How do to fuzzy matching on excel file using Pandas?


code:
INSTALLED_APPS = (
    # ... your other installed apps
    'tags_input',
)

TAGS_INPUT_MAPPINGS = {
    'your_app.Item': {
        'field': 'name',
    },
}

rawDescription: Using `raw_id_fields` to select related objects in the admin


code:
from zope.interface.interface import InterfaceClass

IMemberExtended = InterfaceClass('IMemberExtended', (IMember,), fields)

rawDescription: How to dynamically add attributes to an interface

description: Dynamically add attributes to an interface


rawDescription: Sleeping after every Selenium function call


rawDescription: Reuse part of a Regex pattern

description: Reuse part of a Regex pattern


code:
@status_display_with_comment('a comment')
def a_function():
    print('a_function executes')

a_function()

rawDescription: A more elegant way for this python decorator


rawDescription: Compute percentile for pandas dataframe row based on previous years data


rawDescription: How to know the position of items in a Python's ordered dictionary

description: Know the position of items in a Python's ordered dictionary


code:
list1 = [...]
list2 = [...]
list3 = [...]
features = set( list1 + list2 + list3 )

rawDescription: Remove duplicate nodes in an XML

description: Remove duplicate nodes in an XML


rawDescription: What does the [0]*x syntax do in Python?

description: What does the [0]*x syntax do in Python


code: [[xs[i][j] for i in range(len(xs))] for j in range(len(xs[0]))]

rawDescription: List Comprehension Running Sequence

description: List Comprehension Running Sequence


rawDescription: Converting time zone pandas dataframe

description: Converting time zone pandas dataframe


code:
table = [[i]+[i in l for l in (list1, list2, list3, list4, list5)]
         for i in set(list1+list2+list3+list4+list5)]

rawDescription: Create indicator list

description: Create indicator list


code:
a = ['Hello']
b = tuple(a)
print (type(b))  #<type 'tuple'> -- It thinks it is a tuple
print (b[0])  #'Hello' -- It acts like a tuple too -- Must be :)

rawDescription: How to properly convert list of one element to a tuple with one element

description: Properly convert list of one element to a tuple with one element


code:
class MyClass():
    def __cmp__(self, other):
        return cmp(self.get_list(), other.get_list())

rawDescription: Python class returning value

description: Python class returning value


rawDescription: Compare & manipulate strings with python


code:
def vowel(w,i):
    vowel_list = ['a','e','i','o','u']
    if w[i].lower() in vowel_list:
        print(True)
    else:
        print (False)

s = "hellO World!"
vowel(s,0) #false
vowel(s,4) #true
vowel(s,7) #true

rawDescription: Writing def vowel(w,i):

description: Writing def vowel(w,i):


code:
class Foo(object):
    def __init__(self):
            self.instance_var1 = {'two': 2}

foo = Foo()
foo.instance_var2 = {'three': 3}
foo.instance_var1
foo.instance_var2
Foo.instance_var1

rawDescription: Python: Static objects in a class

description: Python: Static objects in a class


code:
def __create_QLineEdit(self):
    b = QtGui.QLineEdit()
    return b

def __create_QPushButton(self):
    b = QtGui.QPushButton("Choose")
    b.clicked.connect(self.openCal)
    self.dob = QtGui.QLabel()
    grid.addWidget(self.dob, 3, 3)
    column -= 1
    return b

...

rawDescription: Pyqt4 accessing objects when creating a dynamic form


code: print(list(currencies))

rawDescription: Choosing which dictionary to use based on user input in Python


code:
#pg 73 from Python in Finance
import numpy as np
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt

sym1 = 'AAPL'
sym2 = 'FB'

symbol1 = web.DataReader(sym1, data_source='yahoo',start='1/1/2015', end='1/28/2016')
symbol2 = web.DataReader(sym2, data_source='yahoo',start='1/1/2015', end='1/28/2016')
ratio = symbol1;
ratio['Close'] = symbol1['Close'] / symbol2['Close'];

#symbol1['Close'].plot(grid=True, figsize=(8, 5))
#symbol2['Close'].plot(grid=True, figsize=(8, 5))

ratio['Close'].plot(grid=True, figsize=(8, 5))

ratio['42d'] = np.round(pd.rolling_mean(ratio['Close'], window=42), 2)
ratio['252d'] = np.round(pd.rolling_mean(ratio['Close'], window=252), 2)
ratio[['Close', '42d', '252d']].plot(grid=True, figsize=(8, 5))

plt.savefig('foo.png') # save to png
plt.savefig('foo.png') # save to pdf
# plt.show() shows image

rawDescription: Python pandas.io.data save plot?

description: Python pandas.io.data save plot


code:
def find_path2(graph, start, end, path=None):
    if path is None:
        path = []

rawDescription: The meaning of += on list in Python

description: The meaning of += on list in Python


rawDescription: Regex: Why do empty strings get included (in a list of tuples) in re.findall()?


code: quad(lambda x: x*fn(x), -100,100)

rawDescription: Fast way to find the mean of a function?

description: Fast way to find the mean of a function


code:
from suds.transport import Transport
import httplib2, StringIO

class Httplib2Response:
    pass
class Httplib2Transport(Transport):

    def __init__(self, **kwargs):
        Transport.__init__(self)
        self.http = httplib2.Http()

    def send(self, request):
        url = request.url
        message = request.message
        headers = request.headers
        headers['User-Agent']='XYZ'
        response = Httplib2Response()
        response.headers, response.message = self.http.request(url,
                "PUT", body=message, headers=headers)

        return response

    def open(self, request):
        response = Httplib2Response()
        request.headers['User-Agent']='XYZ'

        response.headers, response.message = self.http.request(request.url, "GET",
            body=request.message, headers=request.headers)
        return StringIO.StringIO(response.message)

rawDescription: Set useragent on Client __init__ (Python suds)


rawDescription: Alternatives to variable-width lookbehind in Python regex


code:
from __future__ import print_function

import asyncore
import collections
import logging
import socket

MAX_MESSAGE_LENGTH = 1024

class RemoteClient(asyncore.dispatcher):

    """Wraps a remote client socket."""

    def __init__(self, host, socket, address):
        asyncore.dispatcher.__init__(self, socket)
        self.host = host
        self.outbox = collections.deque()

    def say(self, message):
        self.outbox.append(message)

    def handle_read(self):
        client_message = self.recv(MAX_MESSAGE_LENGTH)
        self.host.broadcast(client_message)

    def handle_write(self):
        if not self.outbox:
            return
        message = self.outbox.popleft()
        if len(message) > MAX_MESSAGE_LENGTH:
            raise ValueError('Message too long')
        self.send(message)

class Host(asyncore.dispatcher):

    log = logging.getLogger('Host')

    def __init__(self, address=('localhost', 0)):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(address)
        self.listen(1)
        self.remote_clients = []

    def handle_accept(self):
        socket, addr = self.accept() # For the remote client.
        self.log.info('Accepted client at %s', addr)
        self.remote_clients.append(RemoteClient(self, socket, addr))

    def handle_read(self):
        self.log.info('Received message: %s', self.read())

    def broadcast(self, message):
        self.log.info('Broadcasting message: %s', message)
        for remote_client in self.remote_clients:
            remote_client.say(message)

class Client(asyncore.dispatcher):

    def __init__(self, host_address, name):
        asyncore.dispatcher.__init__(self)
        self.log = logging.getLogger('Client (%7s)' % name)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.name = name
        self.log.info('Connecting to host at %s', host_address)
        self.connect(host_address)
        self.outbox = collections.deque()

    def say(self, message):
        self.outbox.append(message)
        self.log.info('Enqueued message: %s', message)

    def handle_write(self):
        if not self.outbox:
            return
        message = self.outbox.popleft()
        if len(message) > MAX_MESSAGE_LENGTH:
            raise ValueError('Message too long')
        self.send(message)

    def handle_read(self):
        message = self.recv(MAX_MESSAGE_LENGTH)
        self.log.info('Received message: %s', message)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    logging.info('Creating host')
    host = Host()
    logging.info('Creating clients')
    alice = Client(host.getsockname(), 'Alice')
    bob = Client(host.getsockname(), 'Bob')
    alice.say('Hello, everybody!')
    logging.info('Looping')
    asyncore.loop()

rawDescription: Python SocketServer: sending to multiple clients?


code:
sorted_lists = sorted(zip(new_date_list, flipkart_sale_list, paytm_sale_list), key=lambda x: datetime.datetime.strptime(x[0], "%b %d"))
new_date_list, flipkart_sale_list, paytm_sale_list = [[x[i] for x in sorted_lists] for i in range(3)]

rawDescription: python sort lists from 1 list based on date elements

description: Python sort lists from 1 list based on date elements


code:
def nest(f, g):
    def h():
        return f(g())
    return h

expr = lambda: (_vec, _init)[1]
expr = nest(lambda x: T.set_subtensor(x[1], x[0] * 2)[1], expr)
expr = nest(lambda x: T.set_subtensor(x[2], x[1] * 2)[1], expr)
expr = nest(lambda x: T.set_subtensor(x[3], x[2] * 2)[1], expr)
expr = nest(lambda x: T.set_subtensor(x[4], x[3] * 2)[1], expr)

test_vector = function([], outputs=expr)
subt = test_vector()

rawDescription: Concatenation/creation of symbolic expressions/statements


code:
import datetime
target_time = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond = 0)
now = datetime.datetime.now()
time_to_go = target_time - now
print(time_to_go)

rawDescription: Python: TimeDate Issue

description: Python: TimeDate Issue


code:
data = result['data']
pprint(data)

rawDescription: Python: Retrieve result from inner dictionary


code: print([float(ele) if ele not in {"NaN","Infinity"} else 0 for ele in arr])

rawDescription: how do I import an array with mixed floats and non-numeric strings, with strings converted to zeros

description: Import an array with mixed floats and non-numeric strings, with strings converted to zeros


code:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory

rawDescription: Get parent of current directory from Python script


rawDescription: Provide your own coefficients in Pandas regression


code:
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
c.InteractiveShellApp.exec_lines.append('print("Warning: disable autoreload in ipython_config.py to improve performance.")')

rawDescription: IPython notebook: how to reload all modules in a specific Python file?


code:
car1 = {'brand': 'foo', 'model': 'bar', 'hp': 23}
car2 = {'brand': 'baz', 'model': 'bar', 'hp': 34}
car2 = {'brand': 'baz', 'model': 'bar', 'hp': 14}
car_list = [car1, car2, car3]

car_list.sort(key=lambda c: c['hp'])

rawDescription: Python collections of non-base type?

description: Python collections of non-base type


code:
matches = []
with open("data.txt") as fh:
    for line in fh:
        if line.startswith("City2"):
            matches.append([])
            for _ in range(3):
                matches[-1].append(line.strip())
                line = next(fh)
            continue
for match in matches:
    print("City: {}; Time: {}; Local: {}".format(*match))

rawDescription: Python - delimited list from file

description: Python - delimited list from file


code: df.loc[df.index <= ts]

rawDescription: Subset Pandas Dataframe Everything up to a Date


code: name, value = Fa

rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
from decimal import Context, MAX_EMAX
Context(Emax=MAX_EMAX+1, prec=1).create_decimal('9e'+str(MAX_EMAX+1))
from _pydecimal import Context, MAX_EMAX
Context(Emax=MAX_EMAX+1, prec=1).create_decimal('9e'+str(MAX_EMAX+1))

rawDescription: What is the largest number the Decimal class can handle?


code:
re_badpositions = [r"\b{word}\b".format(word=word) for word in badpositions]

indexes = {badpositions[i]:re.search(re_badpositions[i],text) for i in range(len(badpositions))}

rawDescription: Add in word boundary syntax to list of strings


code:
from itertools import cycle  # will repeat after end

# look for s in items of huge_list
matches = cycle(i for i in huge_list if s in i)
next(matches)

rawDescription: Find + Find next in Python

description: Find + Find next in Python


code:
import numpy as np

A = np.random.randint(0,9,(8,5)) # Sample input array
B = [2,4]                        # Sample blocksize (rows x columns)

# Parameters
M,N = A.shape
col_extent = N - B[1] + 1
row_extent = M - B[0] + 1

# Get Starting block indices
start_idx = np.arange(B[0])[:,None]*N + np.arange(B[1])

# Get offsetted indices across the height and width of input array
offset_idx = np.arange(row_extent)[:,None]*N + np.arange(col_extent)

# Get all actual indices & index into input array for final output
out = np.take (A,start_idx.ravel()[:,None] + offset_idx.ravel())

rawDescription: Implement MATLAB's im2col 'sliding' in Python


code:
def first(iterable, fn):
    for item in iterable:
        if fn(item): return item
    return None

rawDescription: Comparing list of unique objects with custom function


rawDescription: Finding and deleting repeated data entries with two identical features identified by a third unique feature


code:
import re
a = " this is a demonstration sentence. "
print(re.sub(r'''(?x)      # VERBOSE mode
             (             #
              ^            # start of string
              \s*          # zero-or-more whitespaces
              \w           # followed by an alphanumeric character
              )
             |             # OR
             (
             \w            # an alphanumeric character
             \S*           # zero-or-more non-space characters
             \s*           # zero-or-more whitespaces
             $             # end of string
             )
             ''',
             lambda m: m.group().title(),
             a))

rawDescription: Replace First and Last Word of String in the Most Pythonic Way


code:
def countup(n):
    if n >= 0:
        countup(n - 1)
        print(n)

rawDescription: python recursive function that prints from 0 to n?

description: Python recursive function that prints from 0 to n


code: [np.all((x[i], y[i])) for i in range(1000)]

rawDescription: Why is numpy.all much slower than python standard all?


rawDescription: Extracting rows from a table

description: Extracting rows from a table


rawDescription: Python CSV: reading rows terminated by comma results in an empty result


code:
PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy

rawDescription: Python csv to nested JSON

description: Python csv to nested JSON


code:
def __init__(self, **kwargs):
    super(Npcs, self).__init__(**kwargs)
    self.collidetext=kwargs["collidetext"]

rawDescription: How to assign attributes to an instance during creation?

description: Assign attributes to an instance during creation


code:
from bs4 import BeautifulSoup

html = """<root>

1

2

3

    1

</root>"""
soup = BeautifulSoup(html)

rawDescription: Python 3 BeautifulSoup4 search for text in source page


code:
# Use add_axes or add_subplot.
ax = fig.add_axes([0.01, 0.01, 0.98, 0.98],
                   projection=ccrs.InterruptedGoodeHomolosine())

# ax = fig.add_subplot(1, 1, 1, projection=ccrs.InterruptedGoodeHomolosine())

ax.set_global()
ax.stock_img()
ax.coastlines()

rawDescription: How to Embed Cartopy in a Python Tkinter GUI?

description: Embed Cartopy in a Python Tkinter GUI


code:
sh = SubHandler()
sh.prepare()

rawDescription: In python, how can I ensure that one of my class's methods is always called even if a subclass overrides it?


rawDescription: How do I subset a pandas data frame based on a list of string values?

description: Subset a pandas data frame based on a list of string values


code:
def test_signal_registry(self):
    from foo.models import bar_func  # The function I want to register.
    from django.db.models import signals
    registered_functions = [r[1]() for r in signals.pre_delete.receivers]
    self.assertIn(bar_func, registered_functions)

rawDescription: Testing that I have connected to a particular signal in Django


code:
def compare(x, y):
    "Return True if all the elements of x are in y, False otherwise"
    return all([item in y for item in x])

rawDescription: How to check elements in two different lists in python with condition?

description: Check elements in two different lists in python with condition


code:
import tkinter as tk

root = tk.Tk()

btn = tk.Button(root, text="HOVER", activebackground='blue', activeforeground='red')
btn.pack()

root.mainloop()

rawDescription: Adding a hovering option to my buttons in a class


code:
r[u'b']=[x.strip() for x in r[u'b'].split(',')]
r

rawDescription: Converting a single dictionary value in to a list?


code: my_gen = (x == 2 for x in [1, 2, 3]) # a generator expression

rawDescription: Using the split function

description: Using the split function


code:
def argmax(**kw):
    wk = dict([(v,k) for k,v in kw.items()])
    return wk[max(wk)]

argmax(foo=3, bar=5, frotz=1, kaka=-3)

rawDescription: Create function in python to find the highest of all function arguments, and return the "tag" of the value


code:
class Thing(object):
    def __init__(self, name):
        self.name = name
        self.inside = []

rawDescription: setting up iterative item query in python

description: Setting up iterative item query in python


code: random_choice = random.choice(choices)

rawDescription: Print a variable selected by a random number


code: links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()]

rawDescription: Get all related Django model objects

description: Get all related Django model objects


code:
from collections import Counter

# create the counter, from most common to least common. reverse it, and get the first item.
item, num = Counter(b['Item'] for b in bookings).most_common()[::-1][0]

rawDescription: Pythonic way to find fewest occurrences of object in list


code:
class MyClass(object):
    def __init__(self, defaultmembers, members):
        # defaultmembers is a list
        # members is a dict
        for func in defaultmembers:
            setattr(self, func.__name__, func)
        for name, func in members.items():
            setattr(self, name, func)

rawDescription: On-demand creation of member methods using __getattr__()


code:
liste_usager = input("Veuillez entrer la liste d'entiers:")

lst = []                           # A list to hold the numbers
for n in liste_usager.split(' '):  # For each item in liste_usager.split(' ')
    n = int(n)                     # Convert it into an integer
    lst.append(n)                  # And add it to lst

liste_usager = lst                 # Reassign liste_usager to lst

print(liste_usager)

rawDescription: Convert this string to int list

description: Convert this string to int list


rawDescription: Transforming the string representation of a dictionary into a real dictionary


code:
VERBOSE = True
IGNORE_WARNINGS = True

rawDescription: What is an easy way to create a trivial one-off Python object?


code:
x = np.arange(25).reshape((5, 5))
x

rawDescription: Centering a Numpy array of images

description: Centering a Numpy array of images


code:
mask = (flat >= 0.2) & (flat < 0.7)
flat[mask] = func(flat[mask], 0)

rawDescription: How to modify a Numpy array with conditional and function

description: Modify a Numpy array with conditional and function


code:
a = np.random.rand(200,1,64,64)
a1,a2,a3 = np.vsplit(a[np.random.permutation(a.shape[0])],(160,180))
a.shape
a1.shape
a2.shape
a3.shape

rawDescription: Numpy: split array randomly

description: Numpy: split array randomly


code:
str_to_id = {}
for s in strings:
    str_to_id.setdefault(s, len(str_to_id))

rawDescription: The most effective way to assign unique integer id to a string?


code:
reg = regex.compile(r'\b[0-9]{1,3}(?:\s\p{L}+)+')
reg.search("xxx 35 rue Hote de ma maison, 060 06 ").group(0)
reg.search('"xxx 34 rue Roveré').group(0)

rawDescription: Regular expression - street address pattern


code:
def names(teacher):
    return {name for c in teacher['colleagues'] for name in {c['name']} | names(c)}

names(teacher)
def names(teacher):
    direct = {c['name'] for c in teacher['colleagues']}
    return direct.union(*(names(c) for c in teacher['colleagues']))

names(teacher)

rawDescription: Extract set of values from nested dictionaries/lists Python


code:
import sys

if sys.platform == "win32":
   import os, msvcrt
   msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

rawDescription: Make Python stop emitting a carriage return when writing newlines to sys.stdout


rawDescription: Python , Printing Hex removes first 0?

description: Python , Printing Hex removes first 0


code:
#!/usr/bin/python
from random import sample, choice
from cPickle import dump

# Generate sample dataset
value_ceiling = 1000
dataset_size = 900000
dataset_filename = 'dataset.pkl'

# number of distinct values per column
col_distrib = [400,20,20,20,20,20,20]

col_values = [ sample(xrange(value_ceiling),x) for x in col_distrib ]

dataset = []
for _ in xrange(dataset_size):
  dataset.append(tuple([ choice(x) for x in col_values ]))

dump(dataset,open(dataset_filename,'wb'))

rawDescription: What's the fastest way to filter a table of integers in Python?


code:
df['start'] = pd.to_datetime(df['start'],unit='s')
df['end'] = pd.to_datetime(df['end'],unit='s')

rawDescription: calculating rolling mean pandas with time-weighted values

description: Calculating rolling mean pandas with time-weighted values


rawDescription: django/python variables inside strings?

description: Django/python variables inside strings


code:
class EST(datetime.tzinfo):
    def utcoffset(self, dt):
      return datetime.timedelta(hours=-5)

    def dst(self, dt):
        return datetime.timedelta(0)

rawDescription: Python - datetime of a specific timezone


code: listz = (list(i) for i in zip(listx, listy))

rawDescription: Any way to zip to list of lists?

description: Any way to zip to list of lists


code:
from itertools import takewhile
l = takewhile(lambda x: x < 10000, generate())

rawDescription: Python Generator Cutoff

description: Python Generator Cutoff


code: links.add((name, target.group()))

rawDescription: Python Beautifulsoup find unique links

description: Python Beautifulsoup find unique links


code:
Code
import cv2
import dlib
import numpy

PREDICTOR_PATH = "/home/zed/dlib/files/shape_predictor_68_face_landmarks.dat"
predictor = dlib.shape_predictor(PREDICTOR_PATH)
cascade_path='haarcascade_frontalface_default.xml'
cascade = cv2.CascadeClassifier(cascade_path)

# #This is using the Dlib Face Detector . Better result more time taking
# def get_landmarks(im):
#     rects = detector(im, 1)
#     rect=rects[0]
#     print type(rect.width())
#     fwd=int(rect.width())
#     if len(rects) == 0:
#         return None,None

#     return np.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()]),fwd

def get_landmarks(im):
    rects = cascade.detectMultiScale(im, 1.3,5)
    x,y,w,h =rects[0]
    rect=dlib.rectangle(x,y,x+w,y+h)
    return numpy.matrix([[p.x, p.y] for p in predictor(im, rect).parts()])

def annotate_landmarks(im, landmarks):
    im = im.copy()
    for idx, point in enumerate(landmarks):
        pos = (point[0, 0], point[0, 1])
        cv2.putText(im, str(idx), pos,
                    fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
                    fontScale=0.4,
                    color=(0, 0, 255))
        cv2.circle(im, pos, 3, color=(0, 255, 255))
    return im

im=cv2.imread('face_leo1.jpg')
cv2.imshow('Result',annotate_landmarks(im,get_landmarks(im)))
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: OpenCV detect face landmarks (ear-chin-ear line)


rawDescription: How to do a group by in pandas of N observatios

description: Do a group by in pandas of N observatios


code:
ndarray.T
ndarray.transpose()

rawDescription: Transform numpy ndarray from a column list to row list


code:
def __init__(self):
    super(myDialog, self).__init__()
    self.t = QtGui.QTreeView()
    self.m = QtGui.QStandardItemModel()
    self.t.setModel(self.m)
    layout = QtGui.QVBoxLayout()
    layout.addWidget(self.t)
    self.setLayout(layout)
    self.l = [
        ['one', False], ['two', True],
        ['three', False], ['four', True],
        ['five', False]]
    self.populate()

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

rawDescription: QTableView item selection based on a QStandardItem data attribute


code:
st = ''
for x in newcode:
    if x in list1:
        n=list1.index(x)
        n2=n-n1
        y=list1[n2]
        st += y
    else:
        st += x
print(st)

rawDescription: How can i get python to check if every term of a input is in list1, and if not print the term as is?

description: Get python to check if every term of a input is in list1, and if not print the term as is


code:
current = repo.branches['feature']
current

rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


code:
import pprint

my_dict = {'alim2': {'running': 1470.0, 'swimming': 650.0, 'total': 2120.0, 'cycling': 0}, 'brownv4': {'running': 0, 'swimming': 0, 'total': 0, 'cycling': 0},
'mahroosm5': {'running': 1180.0, 'swimming': 590, 'total': 6647.0, 'cycling': 4877.0},
'turnerb3': {'running': 1180.0, 'swimming': 500, 'total': 1680.0, 'cycling': 0}}

pprint.pprint(sorted(my_dict.items(), key=lambda key_:key_[1]['total']))

rawDescription: How to sort a nested dictionary by a nested key

description: Sort a nested dictionary by a nested key


code:
class LocationProxy(object):
    def __init__(self, ops = None):
        self.ops = ops or []
    def __getitem__(self, item):
        self.ops.append((True, item))
        return self
    def __getattr__(self, attr):
        self.ops.append((False, attr))
        return self
    @staticmethod
    def iterativeget(obj, ops):
        for isitem, key in ops:
            obj = obj[key] if isitem else getattr(obj, key)
        return obj
    def get(self, obj):
        return self.iterativeget(obj, self.ops)
    def set(self, obj, value):
        isitem, key = self.ops[-1]
        obj = self.iterativeget(obj, self.ops[:-1])
        if isitem:
            obj[key] = value
        else:
            setattr(obj, key, value)
    def set_from_object(self, obj):
        return lambda value: self.set(obj, value)
    def set_to_value(self, value):
        return lambda obj: self.set(obj, value)
    @staticmethod
    def object_value_setter(obj, value):
        return lambda location: location.set(obj, value)
    @staticmethod
    def object_setter(obj):
        return lambda location, value: location.set(obj, value)
    @staticmethod
    def value_setter(value):
        return lambda location, obj: location.set(obj, value)

rawDescription: Descend through an object and sub-objects to set an arbitrary item or attribute in the hierarchy


code: qaresults = QAResult.objects.filter(company__id__in = expected_values)

rawDescription: Django filtering based on list value

description: Django filtering based on list value


code:
import traceback

def foo(**kwargs):
    # stack is a list of 4-tuples: (filename, line number, function name, text)
    # see http://docs.python.org/library/traceback.html#module-traceback

    (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
    print('foo was called: %s'%text)

foo(**{})
# foo was called: foo(**{})
foo()
# foo was called: foo()

rawDescription: How can I detect if the caller passed any variables to my function in Python?

description: Detect if the caller passed any variables to my function in Python


code:
name = property(**host())
host = property(**host())

rawDescription: Can I make a property refernence to different getter in python

description: Make a property refernence to different getter in python


code:
url(r'^login/$',
    auth_views.login,
    {'template_name': 'registration/login.html',
     'redirect_field_name': 'next',
     'extra_context': {'redirect_to': 'foo_url'}
    },
    name='foo_login'),

url(r'^login/$',
    auth_views.login,
    {'template_name': 'registration/login.html',
     'redirect_field_name': 'next',
     'extra_context': {'redirect_to': 'bar_url'}
    },
    name='bar_login'),

rawDescription: Dynamic login/logout URLs in Django

description: Dynamic login/logout URLs in Django


code:
from PyQt4 import QtGui
import sys

class ImageWidget(QtGui.QWidget):

    def __init__(self, imagePath, parent):
        super(ImageWidget, self).__init__(parent)
        self.picture = QtGui.QPixmap(imagePath)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.picture)

class TableWidget(QtGui.QTableWidget):

    def setImage(self, row, col, imagePath):
        image = ImageWidget(imagePath, self)
        self.setCellWidget(row, col, image)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    tableWidget = TableWidget(10, 2)
    tableWidget.setImage(0, 1, "<your image path here>")
    tableWidget.show()
    sys.exit(app.exec_())

rawDescription: Adding images to a QTableWidget in PyQt

description: Adding images to a QTableWidget in PyQt


code:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^create/$', views.add_model, name='create'),
    url(r'^(?P<pk>[0-9]+)/edit/$', views.update_model, name='update'),
    url(r'^(?P<pk>[0-9]+)/delete/$', views.delete_model, name='delete')
]

rawDescription: Python/Django handling HTTP requests in the right way


code:
import numpy as np
# idx:           0     1     2     3     4     5     6     7
x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
y = np.array([ 110,  101,  110,  106,  102,  104,  112,  115]) # load

lower, upper = 0.03, 0.07
mask = (x >= lower) & (x < 0.07)
# array([False, False,  True,  True,  True,  True, False, False], dtype=bool)

# select those values of x and y
masked_y = y[mask]
masked_x = x[mask]

# find the min index with respect to masked_y
min_idx = masked_y.argmin()

# find the values of x and y restricted to the mask, having the min y value
min_x = masked_x[min_idx]
min_y = masked_y[min_idx]

print (min_x)
# 0.05

print (min_y)
# 102

rawDescription: Finding minimum in an array

description: Finding minimum in an array


code:
class MyClass(object):
    def __init__(self):
        add_property(self, 'foo', lambda _ : 2)

rawDescription: How to lock a method in python (prevent it to be overwritten)?

description: Lock a method in python (prevent it to be overwritten)


code:
# Predefine some constants / inputs
testbed_dict = { "_id" : "xxxxxxxxxxxxx", "platform" : "ABC456" }
inputFile = "ABC456.txt"

with open(inputFile,"r") as infh:
  inputLines = infh.readlines()
  image_start_indices = [inputLines.index(x) for x in inputLines if x.split(":")[0].strip() == "Image"]
  image_end_indices = [x-1 for x in image_start_indices[1:]]
  image_end_indices.append(len(inputLines)-1)
  image_start_stops = zip(image_start_indices, image_end_indices)
  suite_start_indices = [i for i, x in enumerate(inputLines) if x.split(":")[0].strip() == "Suite"]
  suite_end_indices = [i+1 for i, x in enumerate(inputLines) if x.split(":")[0].strip() == "Notes"]
  suite_start_stops = zip(suite_start_indices,suite_end_indices)
  for image_start_index, image_stop_index in image_start_stops:
    suiteCount = 1
    image_suite_indices, suites, image_dict = [], [], {}
    for start, stop in suite_start_stops:
      if start >= image_stop_index or image_start_index >= stop:
        continue
      image_suite_indices.append((start,stop))
    suites = [inputLines[x:y] for x, y in image_suite_indices]
    header_end_index = min([x for x, y in image_suite_indices])
    for line in inputLines[image_start_index:header_end_index]:
      if line.strip() == "":
        continue
      key, value = (line.split(":")[0].strip().lower(), line.split(":")[1].strip())
      image_dict[key] = value
    for suite in suites:
      suite_dict = {}
      for line in suite:
        if line.strip() == "":
          continue
        key, value = (line.split(":")[0].strip().lower(), line.split(":")[1].strip())
        suite_dict[key] = value
      image_dict["suite "+str(suiteCount)] = suite_dict
      suiteCount += 1
    with open(image_dict["image"]+".txt","w") as outfh:
      outfh.write('{\n')
      for key, value in testbed_dict.iteritems():
        outfh.write('\t"'+key+'" : "'+testbed_dict[key]+'"\n')
      for key, value in image_dict.iteritems():
        if 'suite' in key:
          continue
        else:
          outfh.write('\t"'+key+'" : "'+value+'",\n')
      for key, value in image_dict.iteritems():
        if 'suite' not in key:
          continue
        else:
          outfh.write('\t"suite" : [\n\t\t{\n')
          for suitekey, suitevalue in value.iteritems():
            outfh.write('\t\t\t"'+suitekey+'" : "'+str(suitevalue)+'",\n')
          outfh.write("\t\t}\n")
          outfh.write("\t],\n")
      outfh.write('}\n')

rawDescription: Parsing relatively structured text files in python and inserting in mongodb


code:
# get the logger instance
logger = logging.getLogger("main_logger")
# configuration follows
...

rawDescription: python logging ensure a handler is added only once

description: Python logging ensure a handler is added only once


rawDescription: Adding characters to certain laces in string


code:
for x in range(100):
  if x not in mydic:
    mydic[x] = x  # or whatever value you want

rawDescription: in a loop, only add to a dictionary or list or tuple if doesn't contains the key

description: In a loop, only add to a dictionary or list or tuple if doesn't contains the key


code:
idx = np.argsort(counts)[::-1]
values[idx]
counts[idx]

rawDescription: Sorting a scipy.stats.itemfreq result containing strings


code:
from functools import wraps
def showinfo(f):
    @wraps(f)
    def wrapper(*args, **kwds):
         print(f.__name__, f.__hash__)
         return f(*args, **kwds)
    return wrapper

@showinfo
def aa():
    pass

rawDescription: is there a self flag can reference python function inside itself?

description: Is there a self flag can reference python function inside itself


code:
def dispatch(inputfile):
    # if the separator lines must be included, set to True
    need_separator = True
    new = False
    rec = []
    with open(inputfile) as f:
        for line in f:
            if "Admin server interface begins" in line:
                new = True
                if need_separator:
                    rec = [line]
                else:
                    rec = []
            elif "Admin server interface ends" in line:
                if need_separator:
                    rec.append(line)
                new = False
                # if you do not need to process further, uncomment the following line
                #return ''.join(rec)
            elif new:
                rec.append(line)
    return ''.join(rec)

rawDescription: how to read from a particular line upto a particular line in python

description: Read from a particular line upto a particular line in python


code:
dat1 = {}
with open('dat1') as f:
    for line in f.readlines():
        dat1[line.split(',')[0]] = line.strip().split(',')[1:]

dat2 = {}
with open('dat2') as f:
    for line in f.readlines():
        key = line.strip().split()[0].split('-')[1]
        dat2[key] = line.strip().split()[1:]

for key in dat1.keys():
    print("%s,%s,%s" % (key, str.join(',', dat1[key]), str.join(',', dat2[key])))

rawDescription: How to merge two text files around a common value in python

description: Merge two text files around a common value in python


code:
Check = Mat<0
if np.any(Check):
    Mat[Check] = 0
    ...

rawDescription: python array conditional change on elements check numpy

description: Python array conditional change on elements check numpy


code:
doc_hash = {}
doc_hash[doc.id] = doc

rawDescription: Python hash table design

description: Python hash table design


code: df.loc[(df['str1'] == some_string) & (df['time'] < june2014 ), 'str2'] = some_new_str_val

rawDescription: Pandas - Python - How to change the contents of one column based on the content of two others?


code:
a = range(8)
b = list("abc")
len_ab = len(a) + len(b)
groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)), key=lambda x:x[0])
[j[i] for k,g in groups for i,j in enumerate(g)]

rawDescription: How to elegantly interleave two lists of uneven length in python?

description: Elegantly interleave two lists of uneven length in python


code:
bar = self.scroll.verticalScrollBar()
bar.rangeChanged.connect( lambda x,y: bar.setValue(y) )

rawDescription: pyside - auto scroll down in qscrollarea

description: Pyside - auto scroll down in qscrollarea


code:
timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"\s*")s="          hello world!"*10000', number=100000)
timeit.timeit('"".join(itertools.takewhile(lambda x:x.isspace(),s))', 'import itertools;s="          hello world!"*10000', number=100000)
timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s="          hello world!"*10000', number=100000)
timeit.timeit('s[:-len(s.lstrip())]', 's="          hello world!"*10000', number=100000)

rawDescription: Grab a line's whitespace/indention with Python


code: arr[arr > 255] = x

rawDescription: Replace all elements of Python NumPy Array that are greater than some value


code:
class MyModel(models.Model):
    _first_name = models.CharField(max_length=100, db_column='first_name')

    @property
    def first_name(self):
        return self._first_name or self.user.first_name

    @first_name.setter
    def first_name(self, value):
       self._first_name = value

rawDescription: Django empty field fallback

description: Django empty field fallback


code:
def go(self):
    tp = ThreadPool(20)  # <-- 20 thread workers
    for i in self.api_calls:
        tp.add_job(self.query_api, args=(self.q, i))
    tp.join()
    tp.deactivate()

rawDescription: Limiting Threads within Python Threading, Queue


rawDescription: How to specify test timeout for python unittest?

description: Specify test timeout for python unittest


code:
with open(...) as f:
    return json.load(f)  # also not that there is no nead to f.read()+json.loads()
                         # if you can just json.load() on the file handle

rawDescription: python 3 open terminal and run program

description: Python 3 open terminal and run program


code:
class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = SpecializedResource.Meta.authentication # works (but hardcoding)

rawDescription: How to access the meta attributes of a superclass in Python?

description: Access the meta attributes of a superclass in Python


code:
class App:

    def __init__(self, t, w=200, h=200):
        self.image = tkinter.PhotoImage(width=w, height=h)  # create empty image
        for x in range(w):  # iterate over width
            for y in range(h):  # and height
                rgb = [randint(0, 255) for _ in range(3)]  # generate one pixel
                self.image.put("#{:02x}{:02x}{:02x}".format(*rgb), (y, x))  # add pixel
        c = tkinter.Canvas(t, width=w, height=h);
        c.create_image(0, 0, image=self.image, anchor=tkinter.NW)
        c.pack()

rawDescription: Python Tkinter puzzling result

description: Python Tkinter puzzling result


code: data.min(), data.max()

rawDescription: Python: Leave Numpy NaN values from matplotlib heatmap and its legend


code: df_earlier = df[df['Time']<=newstime]

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


code:
import matplotlib.pyplot as plt

x = [1, 2, 5]
ymin = [0, 1, 5]
ymax = [1, 2, 6]

plt.margins(0.05) # So the lines aren't at the plot boundaries..
plt.vlines(x, ymin, ymax, color='black', linewidth=2)
plt.show()

rawDescription: How to make matplotlib draw discontinuous line segments?

description: Make matplotlib draw discontinuous line segments


code:
d = OrderedDict([
    (r'api', api_patterns),
    (r'internal', internal_patterns),
    (r'admin', admin.site.urls),
])

main_view_re = r'^!({})/'.format('|'.join(d.keys()))

urlpatterns = [url(r'^{}/'.format(k), include(v)) for k, v in d]
urlpatterns.append(url(main_view_re, MainView.as_view()))

rawDescription: Match all urls without the prefix in Django


code: re.compile('Home', re.IGNORECASE)

rawDescription: Extract links if anchor text contains keyword


rawDescription: Multiplying every element of one array by every element of another array


rawDescription: Pygame cannot find include file "sdl.h"

description: Pygame cannot find include file "sdl.h"


code:
newlist=["John", "Aaron", "Lydia", "Robin"]
name,newlist = drawNames(newlist,"Lydia")
name,newlist = drawNames(newlist,"John")
name,newlist = drawNames(newlist,"Aaron")
name,newlist = drawNames(newlist,"Robin")

rawDescription: Python - list.remove(x) x not in list

description: Python - list.remove(x) x not in list


code: print([(member.name, member.mtime) for member in tarf.getmembers()])

rawDescription: How do I list contents of a gzip file without extracting it in python?

description: List contents of a gzip file without extracting it in python


code:
accumulator = ''
res = []
for subs in r:
    accumulator += subs
    try:
        res.append(json.loads(accumulator))
        accumulator = ''
    except:
        pass

rawDescription: Parse multiple json objects that are in one line


code:
def insert_3d3(A,B,C):
    # without flattening
    shape = list(A.shape)
    shape[1] += 1
    A2 = np.empty(shape, dtype=A.dtype)
    mask = np.ones(shape, dtype=bool)
    for j,i in enumerate(C):
        mask[j,i+1,:] = False
        A2[j,i+1,:] = B[j,i,:]
    A2[mask] = A.ravel()
    return A2

rawDescription: Insertion of non aligned elements in 4-dimensional matrices in numpy


code:
from django.conf import settings
...
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': settings.STATIC_DOC_ROOT}),

rawDescription: Django and SSL Server

description: Django and SSL Server


rawDescription: How to print out specific values from a list

description: Print out specific values from a list


rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code: results = re.split('\n\s?\n', contents)[1]

rawDescription: Gathering a portion of text on a webpage


rawDescription: How do I load specific rows from a .txt file in Python?

description: Load specific rows from a .txt file in Python


code:
import functools

def subtracter(b):
    def wrapped(func):
        @functools.wraps(func)
        def decorated_func(*args, **kwargs):
            return func(*args, **kwargs) - b
        return decorated_func
    return wrapped

rawDescription: How to decorate a function while adding variables in Python

description: Decorate a function while adding variables in Python


rawDescription: Pandas Merge on Name and Closest Date

description: Pandas Merge on Name and Closest Date


code:
import shutil
from urllib.request import urlopen

with urlopen('http://stackoverflow.com') as u, open('so.html', 'wb') as file:
    shutil.copyfileobj(u, file)

rawDescription: how to convert UTF-8 code to symbol characters in python

description: Convert UTF-8 code to symbol characters in python


code:
import os
os.path.splitext("input.txt")

rawDescription: Beginner Python: save output file as argv input filename


code:
cleaner.kill_tags = ['a', 'h1']
cleaner.remove_tags = ['p']

rawDescription: Remove all javascript tags and style tags from html with python and the lxml module


code:
class Fighter:
    def __init__(self, combat, name):
        self.name = name
        self.combat = combat
    def attack(self):
        self.combat.log.append('{name} attacking'.format(name=self.name))

rawDescription: Pattern to access to object instance from other object instances


code:
def matrix_path(pathLen, startFrom=None):
    """
    @param pathLen    Length of path to return
    @param startFrom  Initial location

    Generate all adjacency paths through the matrix
    """

    # bad path length - quit gracefully
    if pathLen<1:
        yield []
        return

    # no starting point specified - start at any point
    if startFrom is None:
        for pos in allpos:
            for res in matrix_path(pathLen, pos):
                yield res
        return

    # end of path
    if pathLen==1:
        yield [startFrom]
        return

    # from current point, recurse to find rest of path
    for pos in nextpos[startFrom]:
        for morePath in matrix_path(pathLen-1, pos):
            yield [startFrom]+morePath

rawDescription: All possible combinations of numbers of length 5 in a 4X4 matrix


code: plt.scatter(range(len(y)), y, c=z, cmap=cm.hot)

rawDescription: gnuplot linecolor variable in matplotlib?

description: Gnuplot linecolor variable in matplotlib


rawDescription: How to check if an element from List A is not present in List B in Python?

description: Check if an element from List A is not present in List B in Python


code:
e = Elements[:,1:].ravel().astype(int)
e

rawDescription: Python - Replace data of an array by 2 values of a second array


code:
def merge_zpairs(grp):
    data = {'Z1': grp['Z1'].tolist(), 'Z2': grp['Z2'].tolist()}
    return pd.Series(data)

zpairs = namepairs.groupby(['Name1', 'Name2']).apply(merge_zpairs).reset_index()

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


code: notification.send([u for u in Users.objects.all()], "friends_invite", {"from_user": from_user})

rawDescription: reusable application for django site wide announcements that displays a message only once per user

description: Reusable application for django site wide announcements that displays a message only once per user


code:
from storages.backends.s3boto import S3BotoStorage, parse_ts_extended

class MyS3BotoStorage(S3BotoStorage):
    def exists(self, name):
        name = self._normalize_name(self._clean_name(name))
        k = self.bucket.new_key(self._encode_name(name))
        return k.exists()

    def size(self, name):
        name = self._normalize_name(self._clean_name(name))
        return self.bucket.get_key(self._encode_name(name)).size

    def modified_time(self, name):
        name = self._normalize_name(self._clean_name(name))
        k = self.bucket.get_key(self._encode_name(name))
        return parse_ts_extended(k.last_modified)

rawDescription: Why does default_storate.exists() with django-storages with S3Boto backend cause a memory error with a large S3 bucket?


code:
[u'ABERCROMBIE, HON.NEIL', u'HI01', u'2008', u'FD Amendment']
[u'ABERCROMBIE, HON.NEIL', u'HI01', u'2008', u'FD Original']
[u'ACKERMAN, HON.GARY L.', u'NY05', u'2008', u'FD Amendment']
[u'ACKERMAN, HON.GARY L.', u'NY05', u'2008', u'FD Amendment']
...

rawDescription: Scraping aspx with Python mechanize - getting search results


code:
MySQLConnectionPool(pool_name=None,
                    pool_size=5,
                    pool_reset_session=True,
                    **kwargs)

rawDescription: How to create a mysql connection pool or any better way to initialize the multiple databases?

description: Create a mysql connection pool or any better way to initialize the multiple databases


code:
import itertools

def resample(obj, n):
    try:
        return list(itertools.chain.from_iterable((resample(row, n) for c in xrange(n)) for row in obj))
    except TypeError:
        return obj

rawDescription: How to resample an array in python

description: Resample an array in python


code:
#mymodule.py
GLOBAL_VAR = 'Magic String' #or matrix...

def myfunc():
    global GLOBAL_VAR
    #do something

rawDescription: How do you declare a global constant in Python?

description: Declare a global constant in Python


code:
import pickle
import math
pickle.dumps(math.sin)

rawDescription: pickling and mulitprocessing

description: Pickling and mulitprocessing


code:
from PIL import Image
from multiprocessing import Pool, Lock
import numpy

img = Image.open("/path/to/image.jpg")

def rz():
    totalPatchCount = 20000
    imgArray = numpy.asarray(patch, dtype=numpy.float32)
    list_im_arr = [imgArray] * totalPatchCount  # A more elegant way than a for loop
    return list_im_arr

if __name__ == '__main__':
    # patch = img....  Your code to get generate patch here
    patch = patch.resize((60,40), Image.ANTIALIAS)
    patch = patch.convert('L')

    pool = Pool(2)
    imdata = [pool.apply_async(rz).get() for x in range(2)]
    pool.close()
    pool.join()

rawDescription: Better way to share memory for multiprocessing in Python?


code:
class Child(db.Model):
    __tablename__ = 'children'

    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parents.id', ondelete='SET NULL'), nullable=True)
    parent = db.relationship('Parent', backref=db.backref('children', passive_deletes=True))
    name = db.Column(db.String)

rawDescription: How to nullify childre's foreign key when parent deleted using sqlalchemy?

description: Nullify childre's foreign key when parent deleted using sqlalchemy


code:
# Parse CSV file with header
# Extract 4th column
# Reshape column into new matrix
# Save matrix to text file

rawDescription: Splitting Text File - Column to Rows in Python


code:
# Python 2.7
{k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
# Python 3.x
{k: sum(map(float, v.values())) for k, v in mydict.items()}
# Python 2.6 and before
dict((k, sum(float(f) for f in v.values())) for k, v in mydict.iteritems())

rawDescription: Sum up values from a dictionary (the Python way)


code: AUTH_USER_MODEL = 'sample_app.MyUser'

rawDescription: How to Access the custom column from auth_user table in Django?


code:
class Document(models.Model):
    classeur = models.ForeignKey(
        Classeur,
        limit_choices_to={'type_classeur__id': 1},
        verbose_name=u"classeur",
        null=True
    )
    #some other attribute

rawDescription: django modelForm filter isn't effective?

description: Django modelForm filter isn't effective


rawDescription: How to get all orderings of a list such that the list is equal to another list?

description: Get all orderings of a list such that the list is equal to another list


code:
# pick a cmap
cmap = plt.cm.RdYlBu

# get the colors
# if you pass floats to a cmap, the range is from 0 to 1,
# if you pass integer, the range is from 0 to 255
rgba_colors = cmap(np.linspace(0,1,numlines))

# the colors need to be converted to hexadecimal format
hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()]

rawDescription: Use a colourmap to change line colour

description: Use a colourmap to change line colour


code:
class Vertex(ctypes.Structure):
    _fields_ = [("index", ctypes.c_int),
                ("x", ctypes.c_float),
                ("y", ctypes.c_float)]

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


code:
import ast
ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")

rawDescription: Converting a String to Dictionary?

description: Converting a String to Dictionary


code:
from osv import osv
from osv import fields

class cus(osv.osv):
    _name = "lis.lab"
    _description = "This table is for keeping lab data of cord blood"
    _columns = {
        'name': fields.char('Lab Id',size=20,required=True),
        'customer_name': fields.many2one('res.partner', 'Customer Name', domain=[('customer', '=', True)]),
        'customer_city': fields.char('City', size=20),
        'customer_email': fields.char('Email', size=20),
        'customer_mobile': fields.char('Mobile', size=20)
    }

    def on_change_customer(self, cr, uid, ids, customer_name, context=None):
        values = {}
        if customer_name:
            cust = self.pool.get('res.partner').browse(cr, uid, customer_name, context=context)
            values = {
                'customer_city': cust.city,
                'customer_email': cust.email,
                'customer_mobile': cust.mobile
            }
        return {'value' : values}

class test(osv.osv):
    _inherit = "lis.lab"
    _name = "test.lab"
    _description = "Lab Result"
    _columns = {
        'lab_id': fields.many2one('lis.lab','Lab Id'),
        'tot_vol': fields.char('Total Volume', size=20),
        'cd45': fields.char('CD45 viability (%)', size=20),
        'tncpre': fields.char('TNC pre (x10 exp 8)', size=20),
        'tncpost': fields.char('TNC post (x10 exp 8)', size=20),
        'cd34': fields.char('Amount CD34+', size=20)
    }

    def on_change_labid(self, cr, uid, ids, name, context=None):
        values = {}
        if name:
            custinfo = self.pool.get('lis.lab').browse(cr, uid, name, context=context)
            values = {
            }
        return {'value' : values}

rawDescription: ('ValidateError', u'Error occurred while validating the field(s) arch: Invalid XML for View Architecture!')


code: i, j = a.nonzero()

rawDescription: matlab find() for nonzero element in python

description: Matlab find() for nonzero element in python


rawDescription: an efficient equivalent to numpy isnan or where that looks over a window of N values

description: An efficient equivalent to numpy isnan or where that looks over a window of N values


code: value_holder = set()

rawDescription: More efficient way to get unique first occurrence from a Python dict


code:
def my_func(self):
    return 'ok'
my_func = cachedProperty(name='test')(my_func)

rawDescription: python decorator arguments with @ syntax

description: Python decorator arguments with @ syntax


code:
class PacketDecoder(object):

    STX = ...
    ETX = ...

    def __init__(self):
        self._stream = ''

    def feed(self, buffer):
        self._stream += buffer

    def decode(self):
        '''
        Yields packets from the current stream.
        '''
        while len(self._stream) > 2:
            end = self._stream.find(self.ETX)
            if end == -1:
                break

            packet_len = ord(self._stream[1])
            packet = self._stream[:end]
            if packet_len >= 5 and check_sum_valid(packet):
                yield packet
            self._stream = self._stream[end+1:]

rawDescription: Decoding tcp packets using python

description: Decoding tcp packets using python


code: GET /post/52/edit

rawDescription: Is www.example.com/post/21/edit a RESTful URI? I think I know the answer, but have another question


code:
rem = re.match(pat, s)
dist_between_ggagg_and_start_codon = len(rem.group(1))

rawDescription: Number of repeats in a regex in python

description: Number of repeats in a regex in python


code:
hello = ['1', '1', '2', '1', '2', '2', '7']
from collections import Counter
c = Counter(hello)
c
common = c.most_common()
common

rawDescription: Python max with same number of instances


code: np.fill_diagonal(corrs.values, -2)

rawDescription: Pandas: How to drop self correlation from correlation matrix


rawDescription: python, regular expressions, named groups and "logical or" operator

description: Python, regular expressions, named groups and "logical or" operator


code:
for label, x, y in zip(bagOlabels, time, height):
    offset = (50, 20)
    if x > mid_x:
       offset = (-50, 20)  # (-50, -20) could be better

ax.annotate(...)

rawDescription: Keeping data point annotation on figure

description: Keeping data point annotation on figure


code:
# lock_keywords.py
from lockfile import LockFile

def read_file_with_locking(filename):
    lock = LockFile(filename)
    with lock:
        with open(filename, "r") as f:
            data = f.read()
    return data

rawDescription: Locking a file in robotframework

description: Locking a file in robotframework


code:
# use normal python comments

value1 = 32
value2 = u"A unicode value"
value3 = "A plain string value"

value4 = ["lists", "are", "handy"]
value5 = {"and": "so", "are": "dictionaries"}

rawDescription: Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school


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

x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)

styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
    return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]

def animate(i):
    for j, line in enumerate(lines, start=1):
        line.set_ydata(np.sin(j*x + i/10.0))
    return lines

# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
                              interval=0, blit=True)
plt.show()

rawDescription: why is plotting with Matplotlib so slow?

description: Why is plotting with Matplotlib so slow


code:
y = None
while (x != y) and (i < t):
    y = core(x)
    i += 1

rawDescription: Return a value from a function called in while loop


code:
rolls = {4: [], 6: [], 12: []} # dictionary to hold rolls
while True:
    sides = int(input("Which dice would you like to roll? --> ")) # store sides
    rolls.get(sides, rolls[4]).append(dice_roll(sides)) # roll and add to dict
    doRepeat=input("Go again? --> ")
    if doRepeat == "no":
        break

rawDescription: Using return values from a function

description: Using return values from a function


rawDescription: Lucky Number Finder

description: Lucky Number Finder


code:
for i in text[20:50]:
    print(i)

rawDescription: Python - Loadtext for specific number of lines


code:
from collections import Counter
import re

Counter(re.findall(r"\w+", text))

rawDescription: Python - Number of word occurrences

description: Python - Number of word occurrences


code:
rule_syntax = {
    '#': r'[AEIOUY]+',
    '+': r'[EIY]',
    ':': r'[BCDFGHJKLMNPQRSTVWXZ]*',
    '^': r'[BCDFGHJKLMNPQRSTVWXZ]',
    '.': r'[BVDGJLMNRWZ]',
    '%': r'(?:ER|E|ES|ED|ING|EL)',
    '&': r'(?:[SCGZXJ]|CH|SH)',
    '@': r'(?:[TSRDLZNJ]|TH|CH|SH)',
}

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


code: row = line.split()

rawDescription: Change values in CSV or text style file

description: Change values in CSV or text style file


code:
def count_digits(s):
    res = [0]*10
    for x in s:
        res[int(x)] += 1
    return res

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

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


rawDescription: Why does + (plus) can concatenate two strings in Python?


code:
class Graph(object):
    def __init__(self, source, destination, weight, angle):
        self.source = source
        self.destination = destination
        self.weight = weight
        self.angle = angle

rawDescription: Complex Sorting - Multi Key

description: Complex Sorting - Multi Key


code:
s = "4:34.234"
hours, minutes, seconds = (["0", "0"] + s.split(":"))[-3:]
hours = int(hours)
minutes = int(minutes)
seconds = float(seconds)
miliseconds = int(3600000 * hours + 60000 * minutes + 1000 * seconds)

rawDescription: How to convert time format into milliseconds and back in Python?

description: Convert time format into milliseconds and back in Python


code: prg.try_this7(queue, (1,), None,...)

rawDescription: How to pass a list of strings to an opencl kernel using pyopencl?

description: Pass a list of strings to an opencl kernel using pyopencl


code: update = prev_in + lr * net.blobs['data'].diff

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


code:
def all_prime(list_of_nums):
    for num in list_of_nums:
        if not is_prime(num):
            return False
    else:
        return True

rawDescription: Implement a function which takes a list of numbers as an argument and returns true if that list only contains prime numbers and false if it does not


rawDescription: Iterate through a dataframe to find number of times a str value appears in an array of tuples


code:
np.eye(2)
np.tril_indices(2,-1)

rawDescription: How can I accelerate the array assignment in python?

description: Accelerate the array assignment in python


rawDescription: Spark Dataframe distinguish columns with duplicated name


code:
class ItemMetaclass(type):
    def __new__(cls, clsname, bases, dct):
        if "fields" not in dct:
            raise TypeError("Subclass must define 'fields'.")
        return type.__new__(cls, clsname, bases, dct)

class Item(object):
    __metaclass__ = ItemMetaclass
    fields = None

    def __init__(self):
        if type(self) == Item:
            raise NotImplementedError("Must subclass Type.")

    def __setattr__(self, name, value):
        if name in self.fields:
            self.__dict__[name] = value
        else:
            raise AttributeError("The item has no such attribute.")

class MyItem(Item):
    fields = ("one", "two", "three")

rawDescription: Ruby like DSL in Python

description: Ruby like DSL in Python


rawDescription: How can i get csrftoken in view?

description: Get csrftoken in view


code:
a = np.array([[1, 2], [1, 2]])
print(a.shape)
# (2,  2)

# indexing with np.newaxis inserts a new 3rd dimension, which we then repeat the
# array along, (you can achieve the same effect by indexing with None, see below)
b = np.repeat(a[:, :, np.newaxis], 3, axis=2)

print(b.shape)
# (2, 2, 3)

print(b[:, :, 0])
# [[1 2]
#  [1 2]]

print(b[:, :, 1])
# [[1 2]
#  [1 2]]

print(b[:, :, 2])
# [[1 2]
#  [1 2]]

rawDescription: copy 2D array into 3rd dimension, N times (Python)

description: Copy 2D array into 3rd dimension, N times (Python)


code:
class Foo(object):
    def __init__(self, *values):
        self.some_sequence = values

    def __iter__(self):
        for key in self.some_sequence:
            yield (key, 'Value for {}'.format(key))

rawDescription: Overloading __dict__() on python class

description: Overloading __dict__() on python class


code:
ln, = ax.plot(...) # adds a line
img = ax.imshow( ) # adds an image
ln.remove()        # removes the line
img.remove()       # removes the image

rawDescription: how to remove generic content of matplotlib regardless of type plotted

description: Remove generic content of matplotlib regardless of type plotted


code:
a = 5
def my_func():
    global a
    a += 5
    print(a)
my_func()

rawDescription: Calling Python functions from C++ with namespace


rawDescription: Add, modify, remove celery.schedules at run time


code:
def delete_tree_nodes_clicked(self):
    root = self.treeWidget.invisibleRootItem()
    # delete treewidget items from gui
    for item in self.treeWidget.selectedItems():
        (item.parent() or root).removeChild(item)
        self.highlighted.discard(item)
        persons_count[item.person] -= 1
        if not persons_count[item.person]: del persons_count[item.person]

rawDescription: Removing list item if not in another list - python


rawDescription: Efficient 1D array comparison, scaling and summation


rawDescription: os.system for submitting command

description: Os.system for submitting command


code: found = re.search(pattern, filenames[0])

rawDescription: Find 1 letter and 2 numbers using RegEx

description: Find 1 letter and 2 numbers using RegEx


code:
while(not self.terminate):
    eventName, info = self.eventQueue.get()
    event = trigger(eventName, info)

rawDescription: Are python condition variables busy waiting?


code: dateobj = datetime.datetime.strptime(inputstring.rsplit(None, 2)[0], '%B %d, %Y').date()

rawDescription: convert a full string type time into datetime type - Python

description: Convert a full string type time into datetime type - Python


code:
lb = LabelBinarizer()
X_month_dummies = lb.fit_transform(month)

rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


code:
from distutils.core import setup
setup(name='cls', py_modules=['cls'])

rawDescription: How to write a Python package/module?

description: Write a Python package/module