code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.offsetbox as offsetbox
from matplotlib import rc

rc('text', usetex=True)

# Figure top-level container. Weird size is because
# this is part of a larger code.
fig = plt.figure(figsize=(30, 25))
gs = gridspec.GridSpec(10, 12)
ax_t = plt.subplot(gs[4:6, 10:12])

# Some mock values.
cp_r = [0.001, 8.3, 0.18, 15.2, 5000, 0.3]
cp_e = [0.0005, 0.2, 0.11, 0.3, 200, 0.1]

# Remove axis from frame.
ax_t.axis('off')

# Text lines.
text1 = r'\begin{eqnarray*} '
text2 = r'y &=& ' + str(cp_r[0]) + '\pm ' + str(cp_e[0]) + '\\\\'
text3 = r'\log(ret) &=& ' + str(cp_r[1]) + '\pm ' + str(cp_e[1]) + '\\\\'
text4 = r'A_{{(B-C)}} &=& ' + str(cp_r[2]) + '\pm ' + str(cp_e[2]) + '\\\\'
text5 = r'(n-N)_o &=& ' + str(cp_r[3]) + '\pm ' + str(cp_e[3]) + '\\\\'
text6 = r'K_{{\odot}} &=& ' + str(cp_r[4]) + '\pm ' + str(cp_e[4]) + '\\\\'
text7 = r'd_{{frac}} &=& ' + str(cp_r[5]) + '\pm ' + str(cp_e[5])
text8 = r'\end{eqnarray*}'
text = text1 + text2 + text3 + text4 + text5 + text6 + text7 + text8

# Draw text box.
ob = offsetbox.AnchoredText(text, pad=1, loc=6, prop=dict(size=13))
ob.patch.set(alpha=0.85)
ax_t.add_artist(ob)

plt.savefig('out.png', dpi=300)

rawDescription: Align LaTeX math text in matplotlib text box


code: results = dict.fromkeys(inputs, [])

rawDescription: How do I create a unique value for each key using dict.fromkeys?

description: Create a unique value for each key using dict.fromkeys


code: re.sub(r'^((.*?cat.*?){2})cat', r'\1Bull', "cat goose  mouse horse pig cat foo cat cow")

rawDescription: How to find and replace nth occurence of word in a sentence using python regular expression?

description: Find and replace nth occurence of word in a sentence using python regular expression


code:
def new(im):
    rows,cols = im.shape
    final = np.zeros((rows, cols, 3, 3))
    for x in (0,1,2):
        for y in (0,1,2):
            im1 = np.vstack((im[x:],im[:x]))
            im1 = np.column_stack((im1[:,y:],im1[:,:y]))
            final[x::3,y::3] = np.swapaxes(im1.reshape(rows/3,3,cols/3,-1),1,2)
    return final

rawDescription: Find a 3x3 sliding window over an image

description: Find a 3x3 sliding window over an image


rawDescription: Python BeautifulSoup find span inside class


code: jmeter_md5_list.sort(key = lambda val: sortable_key_from_string(val))

rawDescription: Python3 Make tie-breaking lambda sort more pythonic?


rawDescription: Split string value of a dictionary

description: Split string value of a dictionary


code:
def newline(self, options, text = ''):
  if getattr(self, 'lpp', None) == self.lines[self.pages]:
    self.newpage()

  if getattr(self, 'y', None) > self.h - self.bm * inch:
    self.newpage()

rawDescription: In reportlab add as many empty rows to a long table as fit on the last page


rawDescription: json parser in python

description: Json parser in python


code:
def lowest_price(store_dict):
    return [(k,min(v)) if len(v) > 0 else (k,False) for k,v in store_dict.items()]
storeDict = {"socks" : [6.99, 4.50, 5.00, 4.99], "shoes" : [14.99,19.99],
"napkin" : [],"shirt" : [8.99, 7.00, 6.50, 10.25, 8.99]}
lowest_price(storeDict)

rawDescription: dictionary to list of tuples with smallest value

description: Dictionary to list of tuples with smallest value


code:
soup = BeautifulSoup(html)#make soup that is parse-able by bs
soup.findAll('div')

rawDescription: get div from HTML with Python

description: Get div from HTML with Python


code:
from twisted.python import log
from twisted.web import http, proxy

class ProxyClient(proxy.ProxyClient):
    """Mangle returned header, content here.

    Use `self.father` methods to modify request directly.
    """
    def handleHeader(self, key, value):
        # change response header here
        log.msg("Header: %s: %s" % (key, value))
        proxy.ProxyClient.handleHeader(self, key, value)

    def handleResponsePart(self, buffer):
        # change response part here
        log.msg("Content: %s" % (buffer[:50],))
        # make all content upper case
        proxy.ProxyClient.handleResponsePart(self, buffer.upper())

class ProxyClientFactory(proxy.ProxyClientFactory):
    protocol = ProxyClient

class ProxyRequest(proxy.ProxyRequest):
    protocols = dict(http=ProxyClientFactory)

class Proxy(proxy.Proxy):
    requestFactory = ProxyRequest

class ProxyFactory(http.HTTPFactory):
    protocol = Proxy

rawDescription: Python - Twisted, Proxy and modifying content


code:
class Count(object):
    def __init__(self, start=0):
        self.count=start

    def __call__(self):
        self.count+=1
        return self.count

c=Count()
li = [[11, 12, 13, 14], [15, 16, 17]]
print([['Point %i = %i' % (c(),e) for e in sl] for sl in li])
# [['Point 1 = 11', 'Point 2 = 12', 'Point 3 = 13', 'Point 4 = 14'], ['Point 5 = 15', 'Point 6 = 16', 'Point 7 = 17']]

rawDescription: list length + list concatenate on uneven lists

description: List length + list concatenate on uneven lists


code:
from urllib.parse import urlparse
urlparse('foo://user:pass@host:port')
urlparse('foo://host:port')
urlparse('user@host')
urlparse('host')

rawDescription: What's the pythonic way to parse such a URI 'foo://user:pass@host:port' into proper variables?


code:
def example(f):
    return f(1) + f(2)

rawDescription: How can I pass functions or operators as arguments to a function in Python?

description: Pass functions or operators as arguments to a function in Python


code:
lower = (len(x)-L)/2+1
upper = (len(x)+L)/2+1
x[lower:upper]

rawDescription: which are the high frequency terms in numpy.fftn?

description: Which are the high frequency terms in numpy.fftn


code:
import re
text = '''\
string1
string2
string3
==== bump
string4
string5
string6
==== bump'''

print(re.split(r'(=== bump)', text, maxsplit=1)[-1])

rawDescription: How to find line with regex and remove any preceding lines

description: Find line with regex and remove any preceding lines


rawDescription: Returning an lvalue from a function in python


code:
with open("test.txt", "r") as myfile:
    fil = myfile.read().rstrip('\n')
with open("test.txt", "w") as f:
    f.write(re.sub(r'(?m)$', r'append text', fil))

rawDescription: Append in each line of a .txt file a specific string using Python


code:
nx.draw_spring(G, nodelist=sorted(G.nodes()), font_size=20, width=2,
               node_size=[1000, 1000, 2000, 3000],
               node_color=["#A0CBE2", "#A0CBE2", "#FF0000", "#FFFF00"])

rawDescription: How to determine specific color and size of chosen nodes in Networkx graph plot

description: Determine specific color and size of chosen nodes in Networkx graph plot


rawDescription: Is there a way to generate a list of indices using numpy


code:
import email.utils as eut
eut.parsedate('Wed, 23 Sep 2009 22:15:29 GMT')

rawDescription: How do I parse an HTTP date-string in Python?

description: Parse an HTTP date-string in Python


code:
utcdate = localdate - DT.timedelta(hours=offset)
assert date == utcdate

timetuple = utcdate.utctimetuple()
timestamp2 = calendar.timegm(timetuple)
print(timestamp2)
# 1425508527
assert timestamp == timestamp2

rawDescription: Python datetime and utc offset conversion ignoring timezone/daylight savings


code:
html_static_path = ['_static']
def setup(app):
   app.add_stylesheet('cli.css')

rawDescription: Documenting CLI commands with Sphinx doc


code:
def sum_axis_i(arr, axis, i):
    idx = np.index_exp[:] * axis + np.index_exp[i]
    return arr[idx].sum()

rawDescription: select all dimensions of an ndarray but one

description: Select all dimensions of an ndarray but one


rawDescription: Input List - Double/Triple Digits

description: Input List - Double/Triple Digits


code:
def GetURL(self):
  url_target = ("http://www." + self.EntryText.get())
  self.req = urllib2.urlopen(url_target)

rawDescription: Python\Tkinter: Use the variable stored in a function of a class, outside the class


code:
letters=['A', 'I', 'R']
[letters[start:end+1]
 for start in xrange(len(letters))
 for end in xrange(start, len(letters))]

[['A'], ['A', 'I'], ['A', 'I', 'R'], ['I'], ['I', 'R'], ['R']]

rawDescription: How do I get ALL Combination of Sequential elements of list Pythonically?

description: Get ALL Combination of Sequential elements of list Pythonically


code: g.apply(lambda x: x[x['key2'] == 'one']['data1'].sum())

rawDescription: Python Pandas Conditional Sums

description: Python Pandas Conditional Sums


rawDescription: django-postman + django-ajax-selects usage

description: Django-postman + django-ajax-selects usage


code:
import json
import webapp2
from google.appengine.ext import db

import jinja2

JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)

# serialize datastore model to JSON format
def serialize(model):

   allInstances = model.all() # fetching every instance of model
   itemsList = [] #initial empty list
   for p in allInstances:
      d = db.to_dict(p)
      itemsList.append(d)

return  json.dumps(itemsList)

class myModel(db.Model):
    v  = db.FloatProperty()
    c = db.FloatProperty()
    tdate = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp2.RequestHandler):
    def get(self):
       myModel(v=4.5, c=3.0).put()

       #creating template variables
       template_values = {
           'json_data':  serialize(myModel)
       }

       template = JINJA_ENVIRONMENT.get_template('index.html')
       self.response.write(template.render(template_values))

rawDescription: Passing Google App Engine datastore models to javascript code


code:
import matplotlib.pyplot as plt
points = 1e4 #Number of points
xmin, xmax = -1, 5
xlist = map(lambda x: float(xmax - xmin)*x/points, range(points+1))
ylist = map(lambda y: function(y, -1, 5), xlist)
plt.plot(xlist, ylist)
plt.show()

rawDescription: Python - Plot function over a range PYPLOT


code:
import functools

@functools.lru_cache(maxsize=1)
def once():
    print("calculating expensive result")
    return "expensive result"

once()
once()

rawDescription: Python method which computes the result only on the first call, without extra parameters


code:
fl=[e for sub in a for e in sub]
fl[1]=1
fl[2]=2
fl

rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
eggs = marshal.loads( bytes )
exec( eggs )

rawDescription: Possible to execute Python bytecode from a script?


code:
d_next = d + datetime.timedelta(weeks=4)
if weekday_index(d_next) < weekday_index(d):
    d_next += datetime.timedelta(weeks=1)

rawDescription: Python: weekday position of following months


code:
class RequiredFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(RequiredFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

rawDescription: Django formsets: make first required?

description: Django formsets: make first required


code:
day = 16
month = 4
d = (month, day)

rawDescription: How to tell if a date is between two other dates in Python?

description: Tell if a date is between two other dates in Python


code:
def myfunc(strline):
    ...
    return name, otime, lat, lon, depth

rawDescription: How to introduce the attributes of an object in python by calling a method in __init__ method?

description: Introduce the attributes of an object in python by calling a method in __init__ method


code:
d.GetLicense.restype = ctypes.c_void_p
p = d.GetLicense()

d.C_GetApplicationStatus.argtypes = [ctypes.c_void_p]
status = d.P_GetApplicationStatus(p)

rawDescription: C Class Instance from Void Pointer using Ctypes


code:
scrollbar.pack(side="right", fill="y")
listbox.pack(side="left", fill="both", expand=True)

rawDescription: tkinter - Expanding a Listbox inside a Notebook

description: Tkinter - Expanding a Listbox inside a Notebook


code:
with open("name.txt") as file:
    listofdict = [dict(zip(['name','surname','age']), l.strip().split('|')) for l in file]
    return listofdict

rawDescription: How to delete characters from string values of dictionaries in list?

description: Delete characters from string values of dictionaries in list


code:
from itertools import groupby

def merge(line):
    cnt = len(line)
    # Move all numbers left, removing zeros
    line = [num for num in line if num != 0]
    out = []
    # Combine like numbers
    for num, niter in groupby(line):
        ncnt = len(list(niter))
        out.extend([num * 2] * (ncnt // 2))
        if ncnt % 2:
            out.append(num)
    # Right pad the list with zeros to the original line length
    out.extend([0] * (cnt - len(out)))
    return out

rawDescription: How to evaluate two items of the same list and return their sum if equal?

description: Evaluate two items of the same list and return their sum if equal


rawDescription: Any way to optimize numpy stats functions (e.g., via numexpr)?


code:
suffix_tuple, input_string = ("s", "r", "t"), "clear"
next((suffix for suffix in suffix_tuple if input_string.endswith(suffix)), None)
# r

rawDescription: Python: Check which tuple item string ends with, if it ends with one at all


code:
from string import Template
Template(r'\textbf{This and that} plus \textbf{$val}').substitute(val='6')

rawDescription: Format a string that has extra curly braces in it


code:
def datetime_to_float(d):
    epoch = datetime.datetime.utcfromtimestamp(0)
    total_seconds =  (d - epoch).total_seconds()
    # total_seconds will be in decimals (millisecond precision)
    return total_seconds

def float_to_datetime(fl):
    return datetime.datetime.fromtimestamp(fl)

rawDescription: python datetime to float with millisecond precision [Solved]

description: Python datetime to float with millisecond precision [Solved]


code:
start = line.index('data-name') + len('data-name="')
start
line[start:]

rawDescription: Writing from one file to another python

description: Writing from one file to another python


rawDescription: How to split a string based on either a colon or a hyphen?

description: Split a string based on either a colon or a hyphen


code:
class Person(models.Model):
    user = models.ForeignKey(User) #many to one relationship to User table
    week = models.PositiveIntegerField()
    weight = models.PositiveIntegerField()

rawDescription: Need an Example for Building Django Form Fields with Multiple Columns


rawDescription: creating multiple dataframes which contain subsets of an orginal pandas dataframe

description: Creating multiple dataframes which contain subsets of an orginal pandas dataframe


code: t_list = list(set(t_list))

rawDescription: Replacing references in Python3

description: Replacing references in Python3


rawDescription: Numpy boolean index mask for conditional subtraction of existing values


code: ts

rawDescription: Using Pandas To Find the Number Of Periods Since the Rolling High


code:
nli = NestedListIter(l3)
nli.find(5)
nli.insert(9)
nli.nested_list

rawDescription: Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list


code:
classes = ('colore1', 'colore2', 'colore3', 'colore4', 'colore5', 'colore6', 'colore7', 'colore8', 'colore9', 'colore10')
result = dict(zip(set(test_input), classes))

rawDescription: python dict.fromkeys with function as parameter

description: Python dict.fromkeys with function as parameter


rawDescription: Best way to find strings between two points

description: Find strings between two points


code: [my_string + str(x) for x in range(1, my_integer + 1)]

rawDescription: Repeat a string with a subscript over a given range in python


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

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

N = 5
ind = np.arange(N)
width = 0.5
vals = [1,2,3,4,5]
colors = ['r','b','b','b','b']
ax.barh(ind, vals, width, color=colors)

plt.show()

rawDescription: how to change the color of a single bar if condition is True matplotlib

description: Change the color of a single bar if condition is True matplotlib


code:
img = img[(height/4):(3*height/4), (width/4):(3*width/4), :]
height, width, dim = img.shape

img_vec = np.reshape(img, [height * width, dim] )

kmeans = KMeans(n_clusters=3)
kmeans.fit( img_vec )

rawDescription: Color detection of object in Image

description: Color detection of object in Image


rawDescription: Is there a possibility to define dtype only once for all columns?


code: result = ', '.join(str(item) for item in iterable)

rawDescription: Does python have an equivalent to C#'s Enumerable.Aggregate?


code:
Output
ABCDE1
FGHiJ
ABCDE
FGHi

rawDescription: Python - How can I change bytes in a file


rawDescription: Convert from 24 bit signed to latitude / longitude?


code:
date_str='on Jun 03, 02010 at 22:22PM'
date=dt.datetime.strptime(date_str,'on %b %d, 0%Y at %H:%M%p')
print(date)
# 2010-06-03 22:22:00

rawDescription: Convert 12hr date/time string to 24hr datetime


code:
def justify(n):
    return float(n) / 1<<(n.bit_length()-1)

rawDescription: Bitwise operations to produce power of two in Python


code:
from PIL import Image
Image.register_open(BmpAlphaImageFile.format, BmpAlphaImageFile)
# XXX register_save

Image.register_extension(BmpAlphaImageFile.format, ".bmp")

rawDescription: Load RGBA bitmap with PIL

description: Load RGBA bitmap with PIL


rawDescription: How to read negative numbers from a file?

description: Read negative numbers from a file


code:
APP_CFG = {
  'webapp2_extras.auth': {
    'user_model': User,  # default is webapp2_extras.appengine.auth.models.User
    'user_attributes': ['username']  # list of User model properties
  }
}

app = webapp2.WSGIApplication(config=APP_CFG)

rawDescription: Adding a username property to webapp2 User model after entity has been created (with Simpleauth)


rawDescription: Finding the maximum return value of a function and the corresponding input for a given number of inputs


code:
from scipy.integrate import quad

def debye_func(p, T, r):
    # [...] the rest of your code from above here
    err_debye = r - rho0 - coeff * quad(debye_integrand, 0, T/TD, args=(n,))
    return np.sum(err_debye**2)

rawDescription: Fit an integral function with parametric limit to data with Python (Debye Model)


code:
if cond1 == 'val1' and cond2 == 'val2' and \
                       cond3 == 'val3' and \
                       cond4 == 'val4':
    do_something

rawDescription: Python style: multiple-line conditions in IFs


code:
import random
def find(S, m, d):
    return random.sample(list(itertools.combinations(S, m)), d)

rawDescription: Python- exact number of subsets

description: Python- exact number of subsets


code:
while True:
    windowSurface.fill(WHITE) #This clears the screen on each redraw
    pygame.draw.polygon(windowSurface,BLUE,((0+x,250+y),(120+x,120+y),(55+x,55+y)))
    pygame.draw.polygon(windowSurface,RED,((0+x,150+y),(85+x,85+y),(100+x,175+y),(0+x,150+y)))
    pygame.draw.line(windowSurface,BLACK,(60+x,85+y), (120+x, 110+y), 6)
    pygame.draw.circle(windowSurface, GREEN , (75+x,100+y), 13, 0)

rawDescription: Moving object across screen in Pygame

description: Moving object across screen in Pygame


code: ['gave it', 'he gave', 'it to', 'to i']

rawDescription: CountVectorizer ignoring 'I'

description: CountVectorizer ignoring 'I'


code:
def daycheck(name, dolist):
    days = ['monday', 'tuesday', 'wednesday','thursday', 'friday',
            'saturday', 'sunday']
    print('type in', name, "'s day off, please!")
    dayoff = input()
    if dayoff.strip().lower() in days:
        print(name, "'s dayoff is", dayoff, '!!!')
        dolist.append(dayoff)
    else:
        print("I don't know this day! Please try again!")
        daycheck(name, dolist)

daycheck('A', dolist)

rawDescription: Create object from several lists

description: Create object from several lists


code:
with open('file.txt', 'r') as f:
    print(f.read())

rawDescription: Python: Opening a file within a print() function


rawDescription: Python Compare rows in two columns and write a result conditionally


rawDescription: Django Rest Framework receive primary key value in POST and return model object as nested serializer


code: df.ix[df.index.get_level_values('Period') != 0, 'Value'] = 0

rawDescription: pandas multi-index how to mask the data by the second level

description: Pandas multi-index how to mask the data by the second level


code:
def sdev_area_mn(x):
    return np.polyval(fit, x) - sdev
def sdev_area_mx(x):
    return np.polyval(fit, x) + sdev

rawDescription: Python numpy polynomial fit: How to draw region of uncertainty curve?


code:
import subprocess
PIPE, STDOUT = subprocess.PIPE, subprocess.STDOUT
arpA_req = subprocess.Popen(
    ['arp', '-a'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
out, err = arpA_req.communicate()
print(out)

rawDescription: Subprocess arp -a yielding less results than cmd arp -a


code: re.split(" +", "hello world sample text")

rawDescription: Python regex separate space-delimited words into a list


code:
def add_term(self):
    self.txt.insert(tk.SEL_FIRST, '\\term{', 'term')
    self.txt.insert(tk.SEL_LAST, '}', 'term')

rawDescription: Adding coloured text to selected text - Tkinter


code:
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters
punkt_param = PunktParameters()
punkt_param.abbrev_types = set(['dr', 'vs', 'mr', 'mrs', 'prof', 'inc'])
sentence_splitter = PunktSentenceTokenizer(punkt_param)
text = "is THAT what you mean, Mrs. Hussey?"
sentences = sentence_splitter.tokenize(text)

rawDescription: How to tweak the NLTK sentence tokenizer

description: Tweak the NLTK sentence tokenizer


code:
def mahalanobis_sqdist2(d, mean, Sigma):
   Sigma_inv = np.linalg.inv(Sigma)
   xdiff = d - mean
   return np.einsum('ij,im,mj->i', xdiff, xdiff, Sigma_inv)

rawDescription: python-numpy: Apply a function to each row of a ndarray

description: Python-numpy: Apply a function to each row of a ndarray


code:
start = 0
count = 0
for match in iter(lambda: find(target, key, start), -1):
  count += 1
  start = match + 1
return count

rawDescription: Assigning value in a while comparison expression


rawDescription: Python3 SQL Update not committing

description: Python3 SQL Update not committing


code:
list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']

list3 = set(list1)&set(list2) # we don't need to list3 to actually be a list

list4 = sorted(list3, key = lambda k : list1.index(k))

rawDescription: In Python, how do I find common words from two lists while preserving word order?


code:
tup=(imgs, imgs.copy())
tup

rawDescription: How can I make a "tuple of an ndarray of ndarrays"?

description: Make a "tuple of an ndarray of ndarrays"


code:
class PropertyAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'address', get_city, 'status']

rawDescription: django model for city and places

description: Django model for city and places


code:
import csv
import random
from collections import defaultdict

reader = csv.DictReader(open(inputname), delimiter=' ')
out1 = open(output1name,'wb')
out2 = open(output2name,'wb')

# create a dictionary with a random default integer value [0, 1] for
# keys that are accessed for the first time
group_scores = defaultdict(lambda: random.randint(0,1))

for row in reader:
    # set a score for current row according to it's group
    # if none found - defaultdict will call it's lambda for new keys
    # and create a score for this row and all who follow
    score = group_scores[row['Group']]
    if score==0:
        out1.write(row['ID'])
        out1.write("\n")
    if score==1:
        out2.write(row['ID'])
        out2.write("\n")

out1.close()
out2.close()

rawDescription: How to efficiently process a large file with a grouping variable in Python

description: Efficiently process a large file with a grouping variable in Python


code:
def foo(bar=42, qux=None):
    pass

rawDescription: Is there a way in flask to get each object in the request.json and save each attribute on the model?


code:
count = {}
for letter in message:
    if letter in count:  # saw this letter before
        count[letter] += 1
    else:   # first time we've seen this - make its first dict entry
        count[letter] = 1

rawDescription: Count number of occurrences of a character in a string


rawDescription: Python: list directory using user input as directory name not working


code:
mock = Mock()
mock.foo()
mock.foo.assert_called_once()

rawDescription: Automocking for Python?

description: Automocking for Python


code:
#!/usr/bin/python

import time
import multiprocessing as mp

def worker(chunk):
    print('working')
    time.sleep(10)
    return

def main():
    pool = mp.Pool(2)  # Only two workers
    for n in range(0, 8):
        pool.apply_async(worker, n)
        print("called it")
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()

rawDescription: What happens when I multiprocessing.pool.apply_async more times than I have processors


code: df.loc['JSE', 'OML'] = df.loc['JSE', 'OML'].apply(np.sqrt)

rawDescription: Update dataframe row from a series

description: Update dataframe row from a series


code:
a_form.instance = b
a_form.save()

rawDescription: Binding ModelForm to Model's instance when saving


code:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = 'secret.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

rawDescription: How to apply decorator do dispatch method in class-based views Django

description: Apply decorator do dispatch method in class-based views Django


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)

def interpolate_gaps(values, limit=None):
    """
    Fill gaps using linear interpolation, optionally only fill gaps up to a
    size of `limit`.
    """
    values = np.asarray(values)
    i = np.arange(values.size)
    valid = np.isfinite(values)
    filled = np.interp(i, i[valid], values[valid])

    if limit is not None:
        invalid = ~valid
        for n in range(1, limit+1):
            invalid[:-n] &= invalid[n:]
        filled[invalid] = np.nan

    return filled

x = np.random.normal(0, 1, 1000).cumsum()

# Set every third value to NaN
x[::3] = np.nan

# Set a few bigger gaps...
x[20:100], x[200:300], x[400:450] = np.nan, np.nan, np.nan

# Interpolate small gaps using numpy
filled = interpolate_gaps(x, limit=2)

# Let's plot the results
fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot(x, color='lightblue')
axes[1].plot(filled, color='lightblue')

axes[0].set(ylabel='Original Data')
axes[1].set(ylabel='Filled Data')

plt.show()

rawDescription: Working with NaN values in matplotlib

description: Working with NaN values in matplotlib


code: straight = any(a[4+i] - a[i] == 4 for i in range(len(a)-4))

rawDescription: Check a tuple for at least 5 consecutive numbers


rawDescription: Peak curvature in Scipy spline

description: Peak curvature in Scipy spline


code:
from Queue import Queue
from threading import Thread

class MessageQueuer(object):
    def __init__(self, queue):
        self.queue = queue

    def messageReceived(self, message):
        self.queue.put(message)

def main():
    queue = Queue()
    twistedServer = ...
    twistedServer.start(MessageQueuer(queue))
    Thread(target=reactor.run, args=(False,)).start()

    while True:
        message = queue.get()
        response = handleMessage(message)
        reactor.callFromThread(twistedServer.sendResponse, response)

main()

rawDescription: Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue?


code:
from collections import defaultdict

reverse_node_map = defaultdict(set)
for k, nodes in mydict.iteritems():
    for node in nodes:
        reverse_node_map[node].add(k)

rawDescription: Pythonic way to delete an item completely from a dictionary


code:
d[k]  # Existing
d(k)  # Proposed

rawDescription: Why aren't dictionaries callable?

description: Why aren't dictionaries callable


rawDescription: Iterate with last element repeated as first in next iteration


code:
def argsort(seq):
    # http://stackoverflow.com/questions/3382352/3382369#3382369
    # http://stackoverflow.com/questions/3071415/3071441#3071441
    '''
    >>> seq=[1,3,0,4,2]
    >>> index=argsort(seq)
    [2, 0, 4, 1, 3]

    Given seq and the index, you can construct the sorted seq:
    >>> sorted_seq=[seq[x] for x in index]
    >>> assert sorted_seq == sorted(seq)

    Given the sorted seq and the index, you can reconstruct seq:
    >>> assert [sorted_seq[x] for x in argsort(index)] == seq
    '''
    return sorted(range(len(seq)), key=seq.__getitem__)

def f(seq):
    idx = argsort(seq)
    return argsort(idx)

print(f([3,1,2]))
# [2, 0, 1]

print(f([3,1,2,2,3]))
# [3, 0, 1, 2, 4]

rawDescription: Given a "jumbled" list L, get a list where each element is the index of the corresponding element of L, if L was sorted


code:
def build_icmpv6_chunk(type_and_code, other):
    type_code_bytes = bytearray.fromhex(type_and_code)
    checksum = struct.pack(">I", 0)  # make sure checksum is set to 0 here
    other_bytes = bytearray.fromhex(other)
    return type_code_bytes + checksum + other_bytes

rawDescription: Computing 16-bit checksum of ICMPv6 header


code:
def f():
    yield result

def f_as_list():
    return list(f())

rawDescription: Optional yield or return in python3. How to?


code:
def convertType(value):
   try:
       return int(value) if value.strip().isdigit() else float(value)
   except:
       return value # or None or float("-inf") or something depending on desired behavior

rawDescription: Python - Assign a type to a value in a dictionary


rawDescription: Iterating and selecting a specific array from a multidimensional array in Python


code:
import numpy as np

def int2base(x, base, size=None, order='decreasing'):
    x = np.asarray(x)
    if size is None:
        size = int(np.ceil(np.log(np.max(x))/np.log(base)))
    if order == "decreasing":
        powers = base ** np.arange(size - 1, -1, -1)
    else:
        powers = base ** np.arange(size)
    digits = (x.reshape(x.shape + (1,)) // powers) % base
    return digits

rawDescription: Base conversion for an array of integers


code:
import collections
histogram = collections.defaultdict(int)

rawDescription: python: creating histogram out of dictionary

description: Python: creating histogram out of dictionary


rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
def traverse(l):
    for x in l:
        if isinstance(x, list):
            traverse(x)
    callback(l)

rawDescription: Iterating nested list inside-out

description: Iterating nested list inside-out


code:
from collections import defaultdict

a = [1, 2, 3]
b = [1, 2, 3, 1, 2, 3]

# Build up the count of occurrences in b
d = defaultdict(int)
for bb in b:
    d[bb] += 1

# Remove one for each occurrence in a
for aa in a:
    d[aa] -= 1

# Create a list for all elements that still have a count of one or more
result = []
for k, v in d.iteritems():
    if v > 0:
        result += [k] * v

rawDescription: Removing Elements in A from B

description: Removing Elements in A from B


code:
class ResultSet(list):
    """A ResultSet is just a list that keeps track of the SoupStrainer
    that created it."""
    def __init__(self, source, result=()):
        super(ResultSet, self).__init__(result)
        self.source = source

rawDescription: BeautifulSoup find_all <td>'s except last four ones


code: add(name="Hello")

rawDescription: Dynamically add keyword arguments

description: Dynamically add keyword arguments


code:
windows = skimage.util.view_as_windows(roi, pattern.shape)
diff = np.sum((windows - pattern)**2, axis=2).sum(axis=2)

rawDescription: Searching for a line in a jpg file Python


code:
class Mammal:
    ...

class Amphibian:
    ...

class Fish:
    ...

animals = [Mammal(), Amphibian(), Fish()]

rawDescription: get the name of the class and wrap it in an if statement

description: Get the name of the class and wrap it in an if statement


rawDescription: Python group data into one hour intervalls


code:
l = []
urls = ["http://a-restaurant.com/menu", "http://another-restaurant.com/menu"]
for url in urls:
    menu_url = url + '/' + str(food)
    l.append(print_page_sequential(menu_url, 10))

loop.run_until_complete(asyncio.wait(l))

rawDescription: Fetching data with Python's asyncio in a sequential order


code:
lst = ['blahblah', 'boy', 'cool']

for word in lst:
    print(type(word.decode("utf-8")))

rawDescription: How to add unicode character before a string? [Python]

description: Add unicode character before a string? [Python]


code:
mpl_packages = [
    'Building Matplotlib',
    setupext.Matplotlib(),
    setupext.Python(),
    setupext.Platform(),
    'Required dependencies and extensions',
    setupext.Numpy(),
    setupext.Dateutil(),
    setupext.FuncTools32(),
    setupext.Pytz(),
    setupext.Cycler(),
    setupext.Tornado(),
    setupext.Pyparsing(),
    setupext.LibAgg(),
    setupext.FreeType(),
    setupext.FT2Font(),
    setupext.Png(),
    setupext.Qhull(),
    setupext.Image(),
    setupext.TTConv(),
    setupext.Path(),
    setupext.ContourLegacy(),
    setupext.Contour(),
    setupext.Delaunay(),
    setupext.QhullWrap(),
    setupext.Tri(),
    setupext.Externals(),
    'Optional subpackages',
    setupext.SampleData(),
    setupext.Toolkits(),
    setupext.Tests(),
    setupext.Toolkits_Tests(),
    'Optional backend extensions',
    # These backends are listed in order of preference, the first
    # being the most preferred.  The first one that looks like it will
    # work will be selected as the default backend.
    setupext.BackendMacOSX(),
    setupext.BackendQt5(),
    setupext.BackendQt4(),
    setupext.BackendGtk3Agg(),
    setupext.BackendGtk3Cairo(),
    setupext.BackendGtkAgg(),
    setupext.BackendTkAgg(),
    setupext.BackendWxAgg(),
    setupext.BackendGtk(),
    setupext.BackendAgg(),
    setupext.BackendCairo(),
    setupext.Windowing(),
    'Optional LaTeX dependencies',
    setupext.DviPng(),
    setupext.Ghostscript(),
    setupext.LaTeX(),
    setupext.PdfToPs(),
    'Optional package data',
    setupext.Dlls(),
    ]

rawDescription: How to know the enabled features of a matplotlib installation?

description: Know the enabled features of a matplotlib installation


code: x = x+y+z

rawDescription: Possible to append multiple lists at once? (Python)


code: sum(divmod(num, 10))

rawDescription: python addition 2 digit number

description: Python addition 2 digit number


code:
@property
def somePyClassProp(self):
   return bound_int(42, self)

rawDescription: How to know which next attribute is requested in python

description: Know which next attribute is requested in python


code:
with open('file.txt') as f:
    MACHINE = [line.split()[0] for line in f]

MACHINE

rawDescription: output as a list in Python

description: Output as a list in Python


rawDescription: Environment variables and RStudio

description: Environment variables and RStudio


code:
a
out

rawDescription: How to count num of elements vector with numpy python

description: Count num of elements vector with numpy python


code:
def update_graph_links():
    """register each node with neighbours pointing at it"""
    global pr_nodes
    for node in pr_nodes.itervalues():
        for u in node.links_to_node:
            if u in pr_nodes:
                pr_nodes[u].links_from_node.add(node.url)
    return

rawDescription: PageRank toy example fails to converge

description: PageRank toy example fails to converge


code:
vbump = np.vectorize(bump, otypes=[float])
vbump(np.linspace(-1.1, 1.1, 10))

rawDescription: Python - expanding numpy array changes all values of vectorized function


code: temp = np.empty((my_array.shape[0], my_array.shape[1]+1))

rawDescription: Formatting a NumPy array

description: Formatting a NumPy array


code: result = decorator_expr(foo)()

rawDescription: Decorated function along with original, without having to re-write the function


code: my_dict['total'] = sum(value for value in my_dict.values())

rawDescription: Accessing dictionary key values within the same dictionary


code:
import functools

new_func = functools.partial(func, y=20)
new_func(100)

rawDescription: Can I change function parameters when passing them as variables?

description: Change function parameters when passing them as variables


rawDescription: Pandas Time Grouper: Custom Ranges

description: Pandas Time Grouper: Custom Ranges


code:
def create_list(n):
    import random
    return [random.randint(1,6) for _ in range(n)]  # using a list comprehension

def count_list(l):
    from collections import Counter  # using the Counter class
    return Counter(l)

def main():
    nums = create_list(1000)
    counts = count_list(nums)
    for i in range(1,7):
        print(i, counts[i])

rawDescription: I need to get my main function working

description: I need to get my main function working


code:
def filter_kwargs(kwargs, f):
    s = set(parms_of(f))
    return dict((k, v) for k, v in kwargs.items()
                if k in s)

class SuperClass:
    def __init__(self, **kwargs):
        self.one = OneAttribute(**filter_kwargs(kwargs, OneAttribute.__init__))
        self.two = TwoAttributes(**filter_kwargs(kwargs, TwoAttributes.__init__))

rawDescription: Initializing a class in another class, but passing only set attributes


rawDescription: new python pandas dataframe column based on value of variable, using function

description: New python pandas dataframe column based on value of variable, using function


code:
start = times.takeOrdered(1)[0]
end = times.top(1)[0]

rawDescription: Using Apache-Spark to analyze time series


code:
btn = event.GetEventObject()
btn.GetId()
btn.GetName()

rawDescription: Generate wxPython widget groups from lists


code:
import win32com.client
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open(SourceFile)  # Open a workbook

# Your code to modify the excel file.
wb.RefreshAll()

# Call wb.Save() to save your changes.
wb.Save()
xl.Quit()

rawDescription: Dialog box handling in excel through python


rawDescription: how to change 39.54484700000000 to 39.54 and using python

description: Change 39.54484700000000 to 39.54 and using python


code:
urlpatterns = patterns('django.views.generic.simple',
    (r'^foo/$',             'direct_to_template', {'template': 'foo_index.html'}),
    (r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)

rawDescription: How do I go straight to template, in Django's urls.py?

description: Go straight to template, in Django's urls.py


code:
import os
import glob

csv_files = [(index, file, os.path.splitext(file)[0]) for index, file in enumerate(glob.glob('*.csv'))]

rawDescription: Add new column in a csv file and manipulate on the on records


code:
vec.pop(3)
del vec[3]

rawDescription: How can I keep a vector in the same order after removing an element in Python

description: Keep a vector in the same order after removing an element in Python


code:
with open('1.csv','r') as in_file, open('2.csv','w') as out_file:
    seen = set() # set for fast O(1) amortized lookup
    for line in in_file:
        if line in seen: continue # skip duplicate

        seen.add(line)
        out_file.write(line)

rawDescription: Removing duplicate rows from a csv file using a python script


code:
import unittest
from mock import patch, Mock
from my_code import func

class SirTestsAlot(unittest.TestCase):

    @patch('my_code.open')
    @patch('my_code.FTP')
    def test_func_happy_path(self, MockFTP, m_open):
        MockFTP.return_value = Mock()
        mock_ftp_obj = MockFTP()

        m_open.return_value = Mock()

        func('localhost', 'fred', 's3Kr3t')

        assert mock_ftp_obj.retrbinary.called
        assert m_open.called
        # To leverage off of the other solution proposed, you can also
        # check assert called with here too
        m_open.assert_called_once_with('README', 'wb')

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

rawDescription: Mocking FTP in unit test

description: Mocking FTP in unit test


rawDescription: Difference between np.random.seed() and np.random.RandomState()


code: df['date'] = pd.to_datetime(df['date'])

rawDescription: Select dataframe rows between two dates

description: Select dataframe rows between two dates


rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code:
import pandas as pd
import numpy as np

def plot_bar(corr_df):

    dfstacked = corr_df.stack().order()
    dfstacked.plot(kind='bar', rot=60)

def plot_heatmap(corr_df):

    corr_df = corr_df.fillna(value=0)
    plt.pcolormesh(corr_df.values, cmap=plt.cm.Blues)
    plt.yticks(np.arange(0.5, len(corr_df.index), 1), corr_df.index)
    plt.xticks(np.arange(0.5, len(corr_df.columns), 1), corr_df.columns)

df = pd.DataFrame(range(10))

fig, axes = plt.subplots(2)

plt.subplot2grid((1,5), (0,0), colspan=3)
plot_bar(df)

plt.subplot2grid((1,5), (0,3), colspan=2)
plot_heatmap(df)

plt.show()

rawDescription: Creating a subplot instead of separate plots


code:
f = Foo()
f.bar = 3
f.bar
f.bar = "three"

rawDescription: Force python class member variable to be specific type


code:
source
import os, sys

import pyinotify

class VideoComplete(pyinotify.ProcessEvent):
    def process_IN_CLOSE_WRITE(self, event):
        sys.stdout.write(
            'video complete: {}\n'.format(event.pathname)
        )
        sys.stdout.flush()

def main():
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(
        wm, default_proc_fun=VideoComplete(),
        )
    mask = pyinotify.ALL_EVENTS
    path = os.path.expanduser('~/Downloads/incoming')
    wm.add_watch(path, mask, rec=True, auto_add=True)
    notifier.loop()

if __name__=='__main__':
    main()

rawDescription: How to stream video from different files?

description: Stream video from different files


code:
df["GroupId"] = df.groupby(["Name", "Rank"]).grouper.group_info[0]
df

rawDescription: Get group id back into pandas dataframe

description: Get group id back into pandas dataframe


code:
print(rawdict._buffer)
# deque(['{1}'], maxlen=5)
print(rawdict.data)
# {1}

rawDescription: How to build an undo storage with limit?

description: Build an undo storage with limit


rawDescription: Use xpath to get maximum value within tables


rawDescription: checking to see if same value in two lists

description: Checking to see if same value in two lists


code:
def myview(request):
    #Retrieve data or whatever you need
    return render_to_pdf(
            'mytemplate.html',
            {
                'pagesize':'A4',
                'mylist': results,
            }
        )

rawDescription: Render HTML to PDF in Django site

description: Render HTML to PDF in Django site


code:
logging.config.dictConfig(MY_DICTIONARY)
mylogger = logging.getLogger('RunAll_Logger')

rawDescription: Which module should contain logging.config.dictConfig(my_dictionary)? What about my_dictionary?


code:
def combs2(elt2color, combination_size=4, max_colors=3):
    from collections import defaultdict
    from itertools import combinations
    color2elts = defaultdict(list)
    for elt, color in elt2color.items():
        color2elts[color].append(elt)

    def at_least_one_from_each(iterables, n):
        if n < len(iterables):
            return # impossible
        if not n or not iterables:
            if not n and not iterables:
                yield ()
            return
        # Must have n - num_from_first >= len(iterables) - 1,
        # so num_from_first <= n - len(iterables) + 1
        for num_from_first in range(1, min(len(iterables[0]) + 1,
                                           n - len(iterables) + 2)):
            for from_first in combinations(iterables[0],
                                           num_from_first):
                for rest in at_least_one_from_each(iterables[1:],
                                             n - num_from_first):
                    yield from_first + rest

    for numcolors in range(1, max_colors + 1):
        for colors in combinations(color2elts, numcolors):
            # Now this gets tricky.  We need to pick
            # combination_size elements across all the colors, but
            # must pick at least one from each color.
            for elements in at_least_one_from_each(
                    [color2elts[color] for color in colors],
                    combination_size):
                yield elements

rawDescription: Efficient combinations of N colored elements with restriction in the number of colors


code:
hello
hellO
helLo
helLO
heLlo
heLlO
heLLo
heLLO
...

rawDescription: How to get all capitalizations of a word?

description: Get all capitalizations of a word


code: inds = np.random.choice(range(majority_x.shape[0]), 20)

rawDescription: random subsampling of the majority class

description: Random subsampling of the majority class


code: circulant(np.roll(r, -1)).T[:-1]

rawDescription: Create a "wrapped" ndarray from a given array


code:
import networkx as nx

data = [
 ('productA','productB'),
 ('productB','productC'),
 ('productC','productD'),
 ('productA','productD'),
 ('productD','productB'),
 ('productC','productA'),
 ('productE','productF'),
 ('productF','productG'),
 ('productG','productH'),
 ('productG','productE'),
]

G = nx.Graph()
G.add_edges_from(data)
for connected_component in nx.connected_components(G):
    print(connected_component)

rawDescription: An algorithm to create clusters from data pairs in python


rawDescription: Python: how the get the consecutive n-size pieces in a string?


rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


code:
np.cumprod([2 for _ in range(7)])
np.cumprod(np.ones(7,int)*2)

rawDescription: Use Updated Value In Array

description: Use Updated Value In Array


code:
result = []
pizzas = Pizza.objects.select_related().filter(name='deluxe')
for pizza in pizzas:
    for toppings in pizza.toppings.all():
        result.append((pizza.pk, topping.name))

rawDescription: Retrieving values from 2 different tables with Django's QuerySet


code: matching_strings = filter(COMPILED_REGEXP_OBJECT.search, YOUR_LIST_OF_STRING)

rawDescription: Searching list of strings using regular expressions in python


code:
import collections as coll
import csv
import matplotlib.pyplot as plt
import numpy as np
import sys

fs = 100.0
dt = 1.0/fs
alpha = 0.02

Sample = coll.namedtuple("Sample",
    "accZ accY accX rotZ rotY rotX r acc_angZ acc_angY acc_angX cfZ cfY cfX")

def samples_from_file(fname):
    with open(fname) as f:
        next(f)  # discard header row
        csv_reader = csv.reader(f, dialect='excel')

        for i, row in enumerate(csv_reader, 1):
            try:
                values = [float(x) for x in row]
                yield Sample(*values)
            except Exception:
                lst = list(row)
                print("Bad line %d: len %d '%s'" % (i, len(lst), str(lst)))

samples = list(samples_from_file("data.csv"))

cfx = np.zeros(len(samples))

# Excel formula: =R12
cfx[0] = samples[0].acc_angX
# Excel formula: =0.98*(U12+N13*0.01)+0.02*R13
# Excel: U is cfX  N is rotX  R is acc_angX
for i, s in enumerate(samples[1:], 1):
    cfx[i] = (1.0 - alpha) * (cfx[i-1] + s.rotX*dt) + (alpha * s.acc_angX)

check_line = [s.cfX - cf for s, cf in zip(samples, cfx)]

plt.figure(1)
plt.plot(check_line)
plt.plot(cfx)
plt.show()

rawDescription: Complementary Filter Code Not Working

description: Complementary Filter Code Not Working


code:
from signal import *
import sys

def clean(*args):
    delete_temp_file()
    sys.exit(0)

for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
    signal(sig, clean)

rawDescription: Best way to clean a temporary files if script can be interrupted

description: Clean a temporary files if script can be interrupted


code:
cursor.execute ("SELECT winnings, user FROM round_lb WHERE r_id = 5")
rows = cursor.fetchall()
for rank, (winnings, user) in enumerate(sorted(rows, reverse=True), start=1):
    params = (winnings, user, rank)
    cursor.execute("INSERT INTO round_lb (winnings, user, rank) VALUES (%s, %s, %s)", params)

rawDescription: Sort and rank list python and write back to MySQL using python


code:
self.groupBox.setStyleSheet("background-color: rgb(255, 255, 255);\n"
                                    "border:1px solid rgb(255, 170, 255);")

rawDescription: Applying style sheets in pyqt

description: Applying style sheets in pyqt


code:
from datetime import datetime
(datetime.now() - datetime(1601,1,1,0,0)).total_seconds()

rawDescription: Calculating the number of seconds since 1601


code: sample_name = fst('sample_name')

rawDescription: How to create cross-module, on-thy-fly variable name in python?

description: Create cross-module, on-thy-fly variable name in python


code:
if start >= 1:
    function1()
if start >= 2:
    function2()
if start >= 3:
    function3()

rawDescription: How to start at a specific step in a script?

description: Start at a specific step in a script


code:
import inspect

path = inspect.currentframe().f_code.co_filename

rawDescription: Windows Service relative path issue in Python


code: list(next(iter([])) if ind > end else val for ind,val in enumerate(infinite_counter()) if ind >= start)

rawDescription: Get list of subset from infinite generator in Python


code:
engine = AnalyticEuropeanEngine(process)
option.setPricingEngine(engine)
option.NPV()

rawDescription: Calculating EuropeanOptionImpliedVolatility in quantlib-python


code: {{ '{:.0%}'.format(spygames / games|length) }}

rawDescription: Order of Operations for Jinja2 Filters?

description: Order of Operations for Jinja2 Filters


code:
pd.DataFrame({'num_emails':[Table1.email.count()],
              'total_purchasers':[Table1.Total_Orders.count()],
              'total_orders':[np.sum(Table1.Total_Orders)],
              'total_amount':[np.sum(Table1.Amount)]})

rawDescription: How can I output the summary statistics without a group by variable?

description: Output the summary statistics without a group by variable


code:
from itertools import izip
[myfunc(a, b) for a, b in izip(data[::2], data[1::2])]

rawDescription: Perform an action over 2 and 2 elements in a list


code:
class Game:

    # Initialize internal variables, method automatically called on g = Game()
    def __init__(self):
        self._exit = False

        # Array of known commands, used in run, basically maps commands
            # to function and it says: if will get 'go' execute self._go
        self._commands = {
            'go': self._go,
            'quit': self._quit
        }

        # Array of go sub commands, used by _go
        self._commands_go = {
            'north': self._go_north
            # ...
        }

    # Mathod for parsing command, if it gets "comamnd" returns ("command",None)
    # if "command arg1 arg2" returns ("command", "arg1 arg2")
    @staticmethod
    def parse_command(string):
        string = str(string)
        index = string.find(' ')
        if index < 0:
            return (string, None)

        return (string[:index], string[index+1:])

    # This is main method; the only one which should be called from outside
    # It will just read data from input in never ending loop and parse commands
    def run(self):
        while not self._exit:
            src = input('> ')
            (command,args) = Game.parse_command( src)

            # Do we have this command, execute it
            if command in self._commands:
                self._commands[command](args)
            else:
                print( 'I\'m sorry I don\'t known command {}, try one of these:'.format(command))
                print( '\n'.join( self._commands.keys()))

    #######################################################
    # All game commands go here
    #######################################################
    def _quit(self,args):
        self._exit = True
        print( 'Bye bye')

    # Movement handling, will get executed when user types 'go ...' nad '...' will be in arg
    def _go(self,args):
        # No argument
        if args is None:
            print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
            return False

        # Split sub command anr arguments
        (command,args) = Game.parse_command(args)
        if command not in self._commands_go:
            print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
            return False

        if args is not None:
            print( 'Too many arguments for go')
            return False

        self._commands_go[command](args)
        return True

    # Go north
    def _go_north(self, args):
        print( 'Going north')

game = Game()
game.run()

rawDescription: text based game in python

description: Text based game in python


code: pd.merge(df1, df2, on=['Date', 'count'], how='outer')

rawDescription: Pandas join/merge 2 dataframes using date as index


code: CS = plt.contour(X, Y, Z, 24)

rawDescription: Adding extra contour lines using matplotlib 2D contour plotting


rawDescription: Working with bytes and binary data in Python


code:
import requests

# Getting html code
url = "http://store.steampowered.com/app/251570/"
html = requests.get(url).text

rawDescription: Missing source page information using urllib2


code:
# straightforward but deep
def is_full(self):
    for row in self.data:
        for cell in row:
            if cell == ' ':
                return False
    return True

rawDescription: Python Check a 2d list for empty strings?


code:
I = df.columns[(df.ix[0] != df).any()]
J = [pd.get_dummies(df[i], prefix=df[i].name, prefix_sep='') for i in I]
df[[]].join(J)

rawDescription: protein sequence coding

description: Protein sequence coding


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

values = [271238, 329285, -1, 260260, 263711]
timestamps = pd.to_datetime(['2015-01-04 08:29:05',
                             '2015-01-04 08:34:05',
                             '2015-01-04 08:39:05',
                             '2015-01-04 08:44:05',
                             '2015-01-04 08:49:05'])

ts = pd.Series(values, index=timestamps)
ts[ts==-1] = np.nan
ts = ts.resample('T', how='mean')

ts.interpolate(method='spline', order=3).plot()
ts.interpolate(method='time').plot()
lines, labels = plt.gca().get_legend_handles_labels()
labels = ['spline', 'time']
plt.legend(lines, labels, loc='best')
plt.show()

rawDescription: Python pandas time series interpolation and regularization


code:
import itertools
all_friends = itertools.chain.from_iterable(f.friend_list for f in my_friends)
set(all_friends)

rawDescription: Which method is better for combining multiple lists without duplicates?


rawDescription: Insert elements to beginning and end of numpy array


code:
def inject_tag(text, start, end, tagname, **attrs):
    # find the document root
    root = text
    while root.parent:
        root = root.parent

    before = root.new_string(text[:start])
    new_tag = root.new_tag(tagname, **attrs)
    new_tag.string = text[start:end]
    after = root.new_string(text[end:])

    text.replace_with(before)
    before.insert_after(new_tag)
    new_tag.insert_after(after)
    return after

rawDescription: How do you replace specific characters in beautifulSoup?

description: Replace specific characters in beautifulSoup


code:
with open("loginsystem.txt", "r") as loginsystem:
     ...

rawDescription: Python Login: Error reading Text file

description: Python Login: Error reading Text file


rawDescription: How to debug a python module that needs to be executed with -m?

description: Debug a python module that needs to be executed with -m


code:
from operator import methodcaller

# Only count files for finding entry #1000
filesonly = filter(methodcaller('is_file'), os.scandir(somedir))

# Sort by time, and keep the thousandth
# On Windows, you may want st_ctime instead of st_mtime
# Raises IndexError if < 1000 files in dir
file1000 = sorted(filesonly, key=lambda x: x.stat().st_mtime)[999].path

rawDescription: fastest way to get the filename of a specific file from a directory with python

description: Fastest way to get the filename of a specific file from a directory with python


code: ['<User: user10>', '<User: user11>', '<User: user12>', '<User: user13>', '<User: user14>', '<User: user15>', '<User: user16>', '<User: user17>', '<User: user18>', '<User: user19>', '<User: user20>', '<User: user2>', '<User: user3>', '<User: user4>', '<User: user5>', '<User: user6>', '<User: user7>', '<User: user8>', '<User: user9>']

rawDescription: how to sort python dict by its value?

description: Sort python dict by its value


rawDescription: In Python what is it called when you use enclose a variable between 2 plus signs?


code:
for page in Document.Pages:
    Document.ActivePageReference=page

rawDescription: Script to Export Spotfire Graphic to PowerPoint


code:
def __get__(self, obj, objtype):
    """Support instance methods."""
    f = functools.partial(self.__call__, obj)
    f._wrapped = self.func
    return f

rawDescription: How do I get the arguments for any python method?

description: Get the arguments for any python method


code:
for e in [1,2,3].__iter__():
 print(e)

for e in [1,2,3]:
 print(e)

rawDescription: Extending a python list class to perform additional functions on its contents?


rawDescription: Python: How to slice a list to a certain value


code:
self.state = 'new_state'
self.save()

rawDescription: How to change value of a selection using Python on Tryton

description: Change value of a selection using Python on Tryton


code:
words = [str(int(w) + 1) if w.isdigit() else w for w in s.split()]
s = " ".join(words)

rawDescription: incrementing the digit by 1 in python using isdigit()

description: Incrementing the digit by 1 in python using isdigit()


code:
import mock
my_call = mock.call('test', example=3)
name, args, kwargs = my_call
name
args
kwargs

rawDescription: Remove call() when using Mock

description: Remove call() when using Mock


code:
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mysock:
    mysock.connect(('www.py4inf.com', 80))
    mysock.send(b'GET http://www.py4inf.com/cover.jpg HTTP/1.0\n\n')
    header = b''
    while True:
        data = mysock.recv(512)
        if not data:
            raise RuntimeError('no header?')
        header += data
        # end-of-header in buffer yet?
        eoh = header.find(b'\r\n\r\n')
        if eoh != -1:
            break
    # split the header off and keep data read after it.
    header,data = header[:eoh+4],header[eoh+4:]
    print(header.decode())
    with open("stuff.jpg", "wb") as fhand:
        fhand.write(data)
        while True:
            data = mysock.recv(512)
            if not data:
                break
            fhand.write(data)

rawDescription: Receiving an image using Python 3 Sockets


code:
import numpy as np
import itertools as it

data = np.array([[0.5,0,-21],
        [0.5,0,-23],
        [1.0,0,-29],
        [1.0,0,-30],
        [0.5,45,-22],
        [0.5,45,-23]])
# convert signal strength
data[:,-1]= np.pow(10, data[:,-1]/10.)

# get the unique values of radius and angles
uradius = np.unique(data[:,0])
uangle = np.unique(data[:,1])

mean_data = []
for ur, ua in it.product(uradius, uangle):
    samepoints = (data[:,0]==ur) & (data[:,1]==ua)
    if samepoints.sum() > 1:  # check if there is more than one match
        mean_data.append([ur, ua, np.mean(data[samepoints,-1])])
    elif samepoints.sum() == 1:
        mean_data.append([ur, ua, data[samepoints,-1]])

rawDescription: Searching a list of 3 lists for equivalence of 2 lists and averaging all the values in the 3rd list where list 1 and 2 are equal (Python)


code:
def myfunction():
    for i in range(100):
        print(i)

def myotherfunction():
    for i in range(200):
        print(i)

def main():
    """ main program to run over several days """
    for _ in range(3):
        myfunction()

    myotherfunction()

if __name__ == '__main__':
    profile.run('main()') # will execute your program
                          # and show profiling results afterwards

rawDescription: CPU usage increasing over time

description: CPU usage increasing over time


code:
beacon = Beacon.objects.get(factory_id="XXXX-YYYYY")
# Get every campaigns related and only relevant fields (in a list of dict)
campaigns = beacon.campaign_set.all().values('message', 'destination')

for campaign in campaigns:
    print(campaign['message'])
    print(campaign['destination'])

rawDescription: Understanding Querysets, creating the perfect database relationship


code:
from Tkinter import *
master=Tk()
listbox=Listbox(master)
listbox.pack()
for item in ['one','two','three','four']:
    listbox.insert(END, item)

rawDescription: Python Tkinter Listbox Unbind the Default Selection


code:
_, idx = np.unique(g, return_index=True)
np.maximum.reduceat(v, idx)

rawDescription: numpy, get maximum of subsets

description: Numpy, get maximum of subsets


code:
from itertools import chain

filters = filters = ('(product=%s AND employee in ({}))'.format(', '.join('%s' for _ in range(len(pe.split()) - 1))) for pe in prodemployees)
cursor.execute('SELECT * FROM sometable WHERE {}'.format(
                   ' OR '.join(filters)),
               chain.from_iterable(pe.split() for pe in prodemployees))

rawDescription: Python : split a list dynamically

description: Python : split a list dynamically


code:
for item in get_element_by_tag(elemettree, 'technicalContact'):
    ...

rawDescription: Python: Ignore xmlns in elementtree.ElementTree


code:
import string
import random

numcount = 5
chars = []

for num in range(19): #strings are 19 characters long
    if numcount and random.random() < 0.5:
        chars.append(str(random.randint(0, 9)))
        numcount -= 1
    else:
        chars.append(random.choice(string.ascii_uppercase))

fchars = ''.join(chars)

rawDescription: Random String generator python

description: Random String generator python


code:
def fullscreen_toggler(window, event, keysym=gtk.keysyms.F11):
    if event.keyval == keysym:
        fullscreen = bool(
                gtk.gdk.WINDOW_STATE_FULLSCREEN &
                window.get_property('window-state'))
        if fullscreen:
            window.unfullscreen()
        else:
            window.fullscreen()

rawDescription: Simple way to toggle fullscreen with F11 in PyGTK


code:
import re

reg = re.compile(r"IP (?P<IP1>(?:\d{1,3}\.){3}\d{1,3})\.(?P<Port1>\d+) > (?P<IP2>(?:\d{1,3}\.){3}\d{1,3})\.(?P<Port2>\d+): (?:tc|ud)p (?P<size>\d+)")

for line in input_lines:
    m = reg.match(line)
    print(m.group("IP1"))
    print(m.group("Port1"))
    print(m.group("IP2"))
    print(m.group("Port2"))
    print(m.group("size"))

rawDescription: Python Regular Expressions - Parse Out Port From tcpdump


code: from core.models import *

rawDescription: Heroku - Django: Had to change every mentioning of `myproject` into `app` to get my site working. How to best avoid this in the future?


code:
counter += 1
JI_Index_Length +=1

rawDescription: Can you use Python-docx to underline part of a paragraph that is on the same run?

description: Use Python-docx to underline part of a paragraph that is on the same run


rawDescription: Update certain elements in a list

description: Update certain elements in a list


rawDescription: Copy all files with certain extension, while maintaining directory tree


code:
A
setones_between_triggers(A,2,-2)

rawDescription: numpy array set ones between two values, fast

description: Numpy array set ones between two values, fast


rawDescription: Convert 2 lists into a dictionary without having to loop


code:
df = pd.read_csv('energy.csv')
df = df.set_index(['year'])
percent = df.div(df.sum(1)/100,0)
df = df.reset_index('year')

rawDescription: Calculate percent value across a row in a dataframe


code:
tree = {}
for id, lnks in my_objs.items():
    for lnk in lnks:
        uplnks = tree.get(lnk, [])
        uplnks.append(id)
        tree[lnk] = uplnks

rawDescription: How to reverse tree-like linkages in a set?

description: Reverse tree-like linkages in a set


code:
a = np.arange(1,5)
b = np.arange(1,10).reshape((3,3))
a[:,None,None]*b

rawDescription: How to make 1d array multiplied by 2d array resulting in 3d array for python

description: Make 1d array multiplied by 2d array resulting in 3d array for python


code: [k['id'] for i in some_tree for j in i['children'] for k in j['children']]

rawDescription: Evective way of getting list from tree leafs in Python


code:
tree = etree.fromstring('<section> outer <section> inner </section> </section>')
for val in etree.ElementDepthFirstIterator(tree, tag=None, inclusive=False):
 print(etree.tostring(val))

rawDescription: Why won't lxml strip section tags?

description: Why won't lxml strip section tags


code:
def sum(*values, **options):
    s = 0
    for i in values:
        s = s + i
    if "neg" in options:
        if options["neg"]:
            s = -s
    return s

s = sum(1, 2, 3, 4, 5)            # returns 15
s = sum(1, 2, 3, 4, 5, neg=True)  # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15

rawDescription: What does the Star operator mean in Python?


code:
class _StoreAction(Action):

    def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None):
        if nargs == 0:
            raise ValueError('nargs for store actions must be > 0; if you '
                             'have nothing to store, actions such as store '
                             'true or store const may be more appropriate')
        if const is not None and nargs != OPTIONAL:
            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
        super(_StoreAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            const=const,
            default=default,
            type=type,
            choices=choices,
            required=required,
            help=help,
            metavar=metavar)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)

rawDescription: How does string to identifier binding work in python?


code: [myList[i:i+50] for i in range(0, len(myList), 50)]

rawDescription: Print item from list in chunks of 50 in Python


code: df.groupby(['x1', 'x2'])['x3'].agg( {'my_sum':np.sum, 'my_mean':np.mean}).reset_index()

rawDescription: A better way to aggregate data and keep table structure and column names with Pandas


code: [np.bincount(x) for x in a]

rawDescription: How to count occurrences of specific element for arrays in a list?

description: Count occurrences of specific element for arrays in a list


code: from .core import *

rawDescription: How to structure modules to avoid things like "import module.module.module"

description: Structure modules to avoid things like "import module.module.module"


code:
def allMoves():
    for i in range(0,9):
        for j in range(0,9):
            yield ((i,j),(i+1,j))
            yield ((i,j),(i,j+1))

rawDescription: Haskell Algorithm/Candy Crush possible Moves


code:
ar = np.random.rand(25)
ar[np.random.randint(25, size=5)] = np.nan
ar = ar.reshape(5, 5)
N = 2

rawDescription: Selecting values in ndarray occuring after a NaN


rawDescription: How to calculate netmask from 2 ip adresses in Python

description: Calculate netmask from 2 ip adresses in Python


rawDescription: Accessing the first returned object in python


code:
import array

values = array.array('I')
values.fromlist([i for i in range(100)])
bytes = values.tobytes()

rawDescription: Pack 4 byte integers into bytearray or array


rawDescription: Finding specific frame in URL to scrape data using Python BeautifulSoup


code: [('xxx', None), ('xxx', '.suffix'), ('xxx', None), ('xxx', '.suffix')]

rawDescription: Python Regex: How to match filenames with optional suffix? Why '(.*?)(\.suffix)?' doesn't work?


code:
string = 'On {month} {day} it will be {1} months, {0} years'
string.format(*diff, **some_date)

rawDescription: String formatting options: pros and cons


code:
@parallel.depend(minimum_mem, 8 * GB)
def big_mem_task(n):
    import os, socket
    return "big", socket.gethostname(), os.getpid(), n

amr = view.map(big_mem_task, range(10))

rawDescription: Handling various resource requirements in an IPython cluster


rawDescription: Create subplots in Matplotlib in a loop?

description: Create subplots in Matplotlib in a loop


code:
volume_string = ""
for volume in current_volumes:
     volume_string += volume

def template(name=volume_string):
     ...

rawDescription: Pass Two Values in For Loop Python

description: Pass Two Values in For Loop Python


rawDescription: Python: Count overlapping substring in a string


code: count = naive_dac(list(arr[0:len(arr) - 1]))

rawDescription: Average Time Complexity

description: Average Time Complexity


code:
for i in range(0, 3):
    file = request.POST['image%s' % i]
    description = request.POST['description%s' % i]
    # other operations

rawDescription: django request getlist method: does this preserve the sequence of my posted parameters?

description: Django request getlist method: does this preserve the sequence of my posted parameters


code:
matrix = [[True, False, True, False, False, True, False, True],
          [True, False, False, True, True, True, True, True],
          [False]]

res = []
for row in matrix:
    rr = row + [True]
    row_res = [rr[n+1:].index(True) if rr[n] else 0
               for n in range(len(row) - 1)]
    res.append(row_res + [0])

rawDescription: Count number of Falses in 2d list until encountering True (Python)


code:
class Game:
    def __init__(self):
        self.current_room = self.initial_room

    def initial_room(self):
        ...

    def monster_room(self):
        ...

    def monkey_room(self):
        ...

    def display_room(self):
        self.current_room()

rawDescription: Python game logic

description: Python game logic


code: count, best = max((compareGenes(k, target), k) for k in genes)

rawDescription: how to make this a list comprehension

description: Make this a list comprehension


code:
game = {'baseMap': '#here comes your 2D array of tiles',
'objects': [ {'class': Door, 'position': (x, y), 'other Door arguments': ...},
{'class': Door, 'position': (x2, y2), 'other Door arguments': ...},
{'class': Dragon, 'position': (x3, y3), 'dragon arguments': ...}, ] }

rawDescription: Use composition, strategy pattern and dictionnary to better instatiate class stored in dictionnary


code:
joe = User.select().where(User.username == 'Joe')
Message.delete().where(Message.from_user == joe).execute()

rawDescription: Deleting multiple records in a table using join in Peewee?


code: result = z[z_idx, np.indices(z_idx.shape)[0]]

rawDescription: Selecting multiple elements from an 2d array using a 1d array in numpy


code: s = ''.join(l)

rawDescription: Concatenate elements of a list

description: Concatenate elements of a list


code:
class MyPostAdmin(PostAdmin):
    def queryset(self, request):
        return self.model.objects.filter(user = request.user)

create_modeladmin(MyPostAdmin, name='my-posts', model=Post)

rawDescription: Multiple ModelAdmins/views for same model in Django admin


code:
gateway = JavaGateway()
input_stream = gateway.getPCAP(key)
data = gateway.read(input_stream, 1000) # reads 1000 bytes from input_stream

rawDescription: Java InputStream to Python (PY4J)

description: Java InputStream to Python (PY4J)


code:
l=range(5)
i=6
print(l[i] if i < len(l) else None)
i=2
print(l[i] if i < len(l) else None)

rawDescription: Get value at list/array index or "None" if out of range in Python


code:
foo=1 ; foo_dict['foo_key']=1
foo=2 ; foo_dict['foo_key']=2
foo=3 ; foo_dict['foo_key']=3

rawDescription: How to keep variable and dictionary that contains it consistent?

description: Keep variable and dictionary that contains it consistent


code:
from itertools import zip_longest
for row in zip_longest(*([key] + value for key, value in sorted(my_dict.items())), fillvalue=' '):
    print(*row)

rawDescription: How can I print a dictionary in table format?

description: Print a dictionary in table format


code: tag2entries = soup.select('tag1 > tag2')

rawDescription: Python BeautifulSoup find all tags under a certain type of tag


code:
sp_mat.getnnz()
# 6

rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


code: list(expQuestions("?flcopt?"))

rawDescription: elegant way to match two wildcarded strings

description: Elegant way to match two wildcarded strings


code:
dig = []
i = 0
while num > 9:
    dig.append(num % 10)
    i += 1
    num /= 10
dig.append(num)

rawDescription: Divide number into digits and save them in list (array) using python


code: b = [(item[0], tuple(item[1])) for item in a]

rawDescription: how to find whether this python list within list contains duplicates or not?

description: Find whether this python list within list contains duplicates or not


code:
set2 = set(x['id'] for x in list2)
for entry in list1:
  entry['match'] = entry['id'] in set2

rawDescription: mapping two list

description: Mapping two list


code: df.groupby('A').agg(lambda x: np.sum(x[x > 0]))

rawDescription: Count the number of matched element in pandas


code:
if all(v[0]["Times"] for v in d["Showtimes"].itervalues()):
    print(d)

rawDescription: check if the value in a dict is not empty?

description: Check if the value in a dict is not empty


code:
document = db.col.find_one({"some": "condition"}, {"name": 1})
print(document["name"])

rawDescription: Pymongo.find() only return answer

description: Pymongo.find() only return answer


rawDescription: Genericise Function call

description: Genericise Function call


rawDescription: How to check if a string contains only [numbers OR special characters] in python

description: Check if a string contains only [numbers OR special characters] in python


code:
import re

def toevenprettierxml(xml, indent = '  ', newl = '\n'):
   for ind, element in re.findall(r'^(\s*)(\<\w+\s+.+\>)', xml, re.MULTILINE):
      even_prettier_element = re.sub(r'\s+', newl + ind + indent, element)
      even_prettier_element = re.sub(r'(/?\>)', newl + ind + r'\1', even_prettier_element)
      xml = xml.replace(element, even_prettier_element)
   return xml

rawDescription: Make Xml with toprettyxml

description: Make Xml with toprettyxml


code:
if 'form.submitted' in request.params:
    page.title = request.params['title']
    page.content = request.params['content']
    page.no_idea_what = datetime.now()
    DBSession.commit()

rawDescription: Update database using scoped_session.add() in Pyramid & SQLAlchemy


code:
url = 'http://www.investing.com/currencies/usd-brl-historical-data'
r = requests.get(url)

import pandas as pd

df = pd.read_html(r.content,attrs = {'id': 'curr_table'})[0]

rawDescription: Extract Columns from html using Python (Beautifulsoup)


rawDescription: Python construct child class from parent


code:
for scores in d.itervalues():
    scores.sort(key=operator.itemgetter(1), reverse=True)

rawDescription: python: sort a nested dictionary

description: Python: sort a nested dictionary


rawDescription: Self reference for assertions while unittesting


rawDescription: Pythonic way to convert a list with multiple types (including lists!)


code:
R = 1.
n_rings = 10.
n_angles = 10.
density = 10/(dr*da)   # ~ ten points per unit area

rawDescription: Method to uniformly randomly populate a disk with points in python


code: [y for x in (a,b,c) for y in x]

rawDescription: Join many lists using list comprehension


code:
super_list = []
for i in xrange(100):
    short_list = []
    for j in xrange(5):
        short_list.append(MyClass())
    super_list.append(short_list)

rawDescription: Lists of lists of custom objects in Python


code:
g.cax.set_position([.15, .2, .03, .45])
g.savefig("clustermap.png")

rawDescription: How to express classes on the axis of a heatmap in Seaborn

description: Express classes on the axis of a heatmap in Seaborn


code: self.list_customers = [list(rec) for rec in cnx.fetchall()]

rawDescription: Pul MySql Database values to liststore - Python3 and Mysql.connector


code:
from flask import Flask
app = Flask(__name__, static_folder="client")

rawDescription: Serving static html file from another directory from flask restful endpoint


code:
def run_command(command):
    p = subprocess.Popen(command,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

rawDescription: Running Jar files from Python

description: Running Jar files from Python


rawDescription: Django Many-to-Many Relation or One-to-Many relation


code:
unified, ref = unify(raw_data)
uniq, inv = unify2(raw_data)
assert np.allclose(uniq[inv], unified[ref])  # raw_data

rawDescription: Python/Numpy: Build 2D array without adding duplicate rows (for triangular mesh)


code:
if ":!giveaway" in prevdata and senderusr in securelist and agive == 0:
    agive = agive+1
    message("Giveaway started by: " + senderusr)
    t = Timer(3, giveaway)
    t.start()

...

rawDescription: Stay active while sleeping in Python

description: Stay active while sleeping in Python


code: plt.scatter(x, y)

rawDescription: matplotlib remove unseen shapes

description: Matplotlib remove unseen shapes


code:
import shlex
if 'win' in system:
    safe_arg='"%s"'%foo
    assert len(shlex.split(safe_arg)) == 1, "Injection attempt detected"
    cmd = 'echo %s | CLIP' % (safe_arg,)

rawDescription: Preventing Shell Injection on Windows

description: Preventing Shell Injection on Windows


code: return two_directional_slice(mylist, lambda x: x==0, 7)

rawDescription: Cutting list tails based on condition

description: Cutting list tails based on condition


code: map(chr, nums)

rawDescription: How to convert numbers into characters?

description: Convert numbers into characters


rawDescription: Comparing two identical objects in Python (2.7) returns False


code: webpage = webpage.splitlines()

rawDescription: Random and list slicing working strangely with online world list


code:
from __future__ import print_function

import csv
import sys

if sys.version_info.major < 3:
    input = raw_input

input_gender = 'Boy'  # could make this a user-supplied value too

input_year = input('Please enter the year: ').strip()
file_name = 'babyQldAll.csv'

with open(file_name) as fobj:
    csv_file = csv.reader(fobj)
    name_counts = {}
    for row in csv_file:
        year, name, count, gender = (entry.strip() for entry in row)
        if year == input_year and gender == input_gender:
            name_counts[name] = int(count)

print('Popular {} names in year {} are:'.format(input_gender.lower(), input_year))
for name, count in name_counts.items():
    print(name, count)

print('\nBoys names in alphabetical order:')
for name in sorted(name_counts.keys()):
    print(name)

print('\nBoys names in alphabetical order and counts:')
for name, count in sorted(name_counts.items()):
    print('{}: {}'.format(name, count))

rawDescription: Printing elements related to information in 'dict'


code: tuple((head, *tail) for head, tail in zip(x,y))

rawDescription: Append tuple elements to a tuple of tuples in Python


code:
import sqlite3
import decimal
D=decimal.Decimal

def adapt_decimal(d):
    return str(d)

def convert_decimal(s):
    return D(s)

# Register the adapter
sqlite3.register_adapter(D, adapt_decimal)

# Register the converter
sqlite3.register_converter("decimal", convert_decimal)

d = D('4.12')

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(d decimal)")

cur.execute("insert into test(d) values (?)", (d,))
cur.execute("select d from test")
data=cur.fetchone()[0]
print(data)
print(type(data))

cur.close()
con.close()

rawDescription: How to convert Python decimal to SQLite numeric?

description: Convert Python decimal to SQLite numeric


rawDescription: Django exclude(**kwargs) help

description: Django exclude(**kwargs) help


code:
class _TempMetaclass(type):
    pass

class B:
    __metaclass__ = _TempMetaclass # or: type('temp', (type, ), {})

rawDescription: Is there a way to set metaclass after the class definition?


code: alpha = (Decimal(fyt) *  Decimal(qyt)) / (Decimal(fxt) * Decimal(qxt))

rawDescription: Using Decimal type increase the time-cost in power computation


code:
def scene_unit_linear(val):
     _IN_CM = {'m':100, 'in':2.54, 'cm':1, 'ft':30.48}
     _scale = _IN_CM[cmds.currentUnit(q=True, l=True)]
     return _scale * val

rawDescription: pymel getArea() doesnt return real world units

description: Pymel getArea() doesnt return real world units


rawDescription: django unit test for logged in or anonymous user

description: Django unit test for logged in or anonymous user


code:
ov = OnlineVariance()
ov.include(df['Open'])
for n in range(1, 5):
    ov.include(df['Close'].shift(n))
df['std'] = ov.std
print(df)

rawDescription: How do I use pandas' rolling_std to consider two columns in its observation?

description: Use pandas' rolling_std to consider two columns in its observation


code: df['foo'] = np.where(df.even, 1, -1)

rawDescription: How to write a conditional array operation on a Pandas DataFrame

description: Write a conditional array operation on a Pandas DataFrame


code:
import numpy as np,numpy.linalg

def _getAplus(A):
    eigval, eigvec = np.linalg.eig(A)
    Q = np.matrix(eigvec)
    xdiag = np.matrix(np.diag(np.maximum(eigval, 0)))
    return Q*xdiag*Q.T

def _getPs(A, W=None):
    W05 = np.matrix(W**.5)
    return  W05.I * _getAplus(W05 * A * W05) * W05.I

def _getPu(A, W=None):
    Aret = np.array(A.copy())
    Aret[W > 0] = np.array(W)[W > 0]
    return np.matrix(Aret)

def nearPD(A, nit=10):
    n = A.shape[0]
    W = np.identity(n)
# W is the matrix used for the norm (assumed to be Identity matrix here)
# the algorithm should work for any diagonal W
    deltaS = 0
    Yk = A.copy()
    for k in range(nit):
        Rk = Yk - deltaS
        Xk = _getPs(Rk, W=W)
        deltaS = Xk - Rk
        Yk = _getPu(Xk, W=W)
    return Yk

rawDescription: How can I calculate the nearest positive semi-definite matrix?

description: Calculate the nearest positive semi-definite matrix


rawDescription: Numpy - constructing matrix of Jaro (or Levenshtein) distances using numpy.fromfunction


code:
class EchoWebSocket(websocket.WebSocketHandler):
    def initialize(self):
        self._closed = False

    def open(self):
        print(type(self.request))
        print(self.request)
        print(self.request.remote_ip)

rawDescription: How do I get the client IP of a Tornado web socket request?

description: Get the client IP of a Tornado web socket request


code: pixelR, pixelR, pixelR = pixelValueTuple[:3]

rawDescription: How do I change each pixel

description: Change each pixel


rawDescription: Store ten most related items in structured array Python


code:
_number_of_times = 0

def yourfunc(x, y):
    global _number_of_times
    for i in range(x):
        for j in range(y):
            _number_of_times += 1

rawDescription: Static variable in python?

description: Static variable in python


code: Реестр_Платежей

rawDescription: Python decoding from iso-8859-5

description: Python decoding from iso-8859-5


code:
matches = []
with open("target.txt") as target:
    for line in target:
        items = line.split()
        if items[0] in idents:
            matches.append(items)

rawDescription: Finding lines by first value in text file in python


code:
@app.before_request
def check_login():
    if request.endpoint == 'static' and not current_user.is_authenticated():
        abort(401)
    return None

rawDescription: Python : Flask : Catch All Url for login_required


code:
for i in range(num):
    pt0 = pt_list[i]
    ri  = rand_list[i]
    pt1 = pt_list[ri]

    val = 0
    for j in range(3):
        d = pt0[j] - pt1[j]
        val += d*d
    val = math.sqrt(val)

    dist += val

rawDescription: Why is computing point distances so slow in Python?


code: from multiprocessing.dummy import Pool # use threads

rawDescription: Python: To Subprocess or Not To Subprocess into Another Python Subprocess?


rawDescription: Using Python to run nested string searches


code:
ind.sort()
print(a[ind])
print(b[ind])

rawDescription: remove duplicate elements from two numpy arrays

description: Remove duplicate elements from two numpy arrays


code: numpy.frompyfunc((lambda x: x[0:2]), 1, 1)

rawDescription: Python Pandas: How to broadcast an operation using apply without writing a secondary function


code: del sub[key_list[-1]]

rawDescription: Dynamically delete an item from a nested dictionary


code: print(' '.join([(y+"@company.com") for y in x.split()]))

rawDescription: Python regex - extend string

description: Python regex - extend string


code:
data = []
path = '.'
files = [f for f in os.listdir(path) if os.path.isfile(f)]
for f in files:
  with open (f, "r") as myfile:
    data.append(myfile.read())

df = pd.DataFrame(data)

rawDescription: Python read txt files into a dataframe

description: Python read txt files into a dataframe


code: returned_data = v()

rawDescription: get value from function using python

description: Get value from function using python


code:
db.define_table('news_item',
  Field('title', 'string', label='Title', requires=IS_NOT_EMPTY()),
  Field('type', 'string', label='Type', requires=IS_IN_SET(news_types)),
  Field('pub_date', 'date', default=request.now),
  Field('post_date', 'date', default=request.now), # Set date defaults
  Field('link', 'string', label='News Link', requires=IS_EMPTY_OR(IS_URL())),
  Field('img', 'upload', uploadfield='img_file', label='Story Title Image'),
  Field('img_file', 'blob', label='Story Title Image'),
  Field('tagline', 'text', label='Tagline', requires=IS_NOT_EMPTY()),
  Field('published', 'boolean', label='Published?', notnull=True, required=True),
)

rawDescription: Preprocessing form data before using it

description: Preprocessing form data before using it


code:
nfoo = len(foo_list[0])
nbar = len(bar_list[0])

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code:
z = 2+3j
z.real
z.imag
z.conjugate()

rawDescription: Complex numbers usage in python

description: Complex numbers usage in python


code:
if self.repRouterSocket in socketEvents:
    multipart = self.repRouterSocket.recv_multipart()
    self.reqRouterSocket.send_multipart(multipart[1:])

rawDescription: ZMQ Python Request Reply Broker for Addressed Asynchronous Requests


code:
for x in range(1, max_divisor):
    if n % x == 0:
        sum += x
if sum > n:
    print ("Your number is abundant")
else:
    print ("Your number isn't abundant")

rawDescription: Determining a Abundant Number when user inputs a nmber


code:
for d in range(1, n - 1):
    print(c, ' ' * (m - 2), c, sep='')

rawDescription: Printing a frame in python

description: Printing a frame in python


code: from compiler.ast import flatten

rawDescription: Python - Convert array with list with different sizes to string


rawDescription: Django -- How to filter objects with an "author" from a set of "authors"(users)?


code: eq.xreplace({phi(t).diff(t): 1})

rawDescription: Sympy: solve a differential equation

description: Sympy: solve a differential equation


code:
#Find values that are in range
in_range = (lo_lim1 <= v1 <= hi_lim1 and lo_lim2 <= v2 <= hi_lim2 for v1, v2 in zip(values1, values2))

#Find runs of in-range values
runs = (sum(1 for _ in group) for v, group in groupby(in_range) if v)  # this is the same as yours

#Estimate total time spent in-range
defval = Buffer_Value*sample_rate
total_time = sum(v if v > 1 else defval for v in runs)

rawDescription: python generator expressions for two data sets

description: Python generator expressions for two data sets


rawDescription: Where can I find documentation for calling the various types in Python's types module?


code:
def sort(a, num):
  def key(x):
    return int(x[num])
  return sorted(a, reverse=True, key=key)

rawDescription: Understanding lambda functions in python


code: config.get('section1', 'key1')

rawDescription: How to get nested value from option that are in config.ini file using python

description: Get nested value from option that are in config.ini file using python


code:
q = xs.filter(lambda x: x % 2 == 0).map(lambda x: -x)
q.subscribe(print)

rawDescription: How to use Reactive Extensions (Rx) LINQ in Python?

description: Use Reactive Extensions (Rx) LINQ in Python


code:
def testSleep(self):
    self.lineEdit.setText('Start')
    QtCore.QTimer.singleShot(10000, lambda: self.Box.append("Text2"))
    QtCore.QTimer.singleShot(10000,lambda: self.timerEvent)

def timerEvent(self):
    QtCore.QTimer.singleShot(10000, lambda: self.Box.append("Text3"))

rawDescription: Python, PySide sleep without stalling the whole program?


rawDescription: Optional arguments in Python Script for Notepad++


code:
from itertools import imap
any(imap(s.__contains__, substring_list))

rawDescription: Python: How to check a string for substrings from a list?


code:
def f(row):
  if abs(row["Buy"]) > abs(row["Sell"]):
    return row["Price"] / row["Buy"]
  else:
    return row["Price"] / row["Sell"]

rawDescription: Pandas Dataframe row by row fill new column


code: df.groupby('Cancer Stage')['ATG12 Norm','ATG5 Norm'].mean()

rawDescription: Pandas Building a subtable based on means


code:
def foowrap(x):
   return foo(x[0], x[1])

rawDescription: A performance concern when using minimizing a two-parameter function with scipy


code: fprime = formula(*derivative(f))

rawDescription: Given f, is there an automatic way to calculate fprime for Newton's method?


code:
class A:

    def __init__(self):
        self._a = 0

    @property
    def a(self):
        print ("called a getter")
        return self._a

    @a.setter
    def a(self, value):
        print ("called a setter")
        self._a = value

rawDescription: infinite recursion in python3.3 setter

description: Infinite recursion in python3.3 setter


rawDescription: How do I extract text with the Xpath in Scrapy?

description: Extract text with the Xpath in Scrapy


code: __ordering__ = [ 'single', 'double' ]

rawDescription: Ordering enum value in python

description: Ordering enum value in python


rawDescription: Verify CSV against given format

description: Verify CSV against given format


code: result = numpy.where(x == y, x, 0)

rawDescription: Looking for the fastest way to find the exact overlap between two arrays of equal length in numpy


code:
if re.search(r"Crude protein \(min\.\)","Crude protein,protein,Protein,Protein    (crude),Crude protein (min.)") : print("ok")
...
ok

rawDescription: re.search : a lack of understanding through 2 exemples

description: Re.search : a lack of understanding through 2 exemples


code:
from bs4 import BeautifulSoup
text = ''.join('

'.format(i) for i in range(10))
soup = BeautifulSoup(text)

soup.find_all("table", {"class": ["class1", "class7"]})
import re
soup.find_all("table", {"class": re.compile("class[17]")})

soup.find_all("table", {"class": lambda x: 3*int(x[-1])**2-24*int(x[-1])+17 == -4})

rawDescription: Check if class is equal with one of two strings


code:
def islice(iterable, *args):
    s = slice(*args)
    it = iter(xrange(s.start or 0, s.stop or 200, s.step or 1))
    try:
        nexti = next(it)
        consume = False
    except StopIteration:
        if s.start < 1:
            return
        nexti = s.start - 1
        consume = True
    for i, element in enumerate(iterable):
        if i == nexti:
            if consume:
                return
            yield element
            nexti = next(it)

rawDescription: Why is the Python version of itertools.islice not working?


code:
from pylab import *
from matplotlib import *

# 100, 400 and 200 Hz sine 'wave'
dt = 0.0005
t = arange(0.0, 20.0, dt)
s1 = sin(2*pi*100*t)
s2 = 2*sin(2*pi*400*t)
s3 = 2*sin(2*pi*200*t)

# create a transient "chirp"
mask = where(logical_and(t>10, t<12), 1.0, 0.0)
s2 = s2 * mask

# add some noise into the mix
nse = 0.01*randn(len(t))

x = s1 + s2 + +s3 + nse # the signal
NFFT = 1024       # the length of the windowing segments
Fs = int(1.0/dt)  # the sampling frequency

# modified specgram()
def my_specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
             window=mlab.window_hanning, noverlap=128,
             cmap=None, xextent=None, pad_to=None, sides='default',
             scale_by_freq=None, minfreq = None, maxfreq = None, **kwargs):
    """
    call signature::

      specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
               window=mlab.window_hanning, noverlap=128,
               cmap=None, xextent=None, pad_to=None, sides='default',
               scale_by_freq=None, minfreq = None, maxfreq = None, **kwargs)

    Compute a spectrogram of data in *x*.  Data are split into
    *NFFT* length segments and the PSD of each section is
    computed.  The windowing function *window* is applied to each
    segment, and the amount of overlap of each segment is
    specified with *noverlap*.

    %(PSD)s

      *Fc*: integer
        The center frequency of *x* (defaults to 0), which offsets
        the y extents of the plot to reflect the frequency range used
        when a signal is acquired and then filtered and downsampled to
        baseband.

      *cmap*:
        A :class:`matplotlib.cm.Colormap` instance; if *None* use
        default determined by rc

      *xextent*:
        The image extent along the x-axis. xextent = (xmin,xmax)
        The default is (0,max(bins)), where bins is the return
        value from :func:`mlab.specgram`

      *minfreq, maxfreq*
        Limits y-axis. Both required

      *kwargs*:

        Additional kwargs are passed on to imshow which makes the
        specgram image

      Return value is (*Pxx*, *freqs*, *bins*, *im*):

      - *bins* are the time points the spectrogram is calculated over
      - *freqs* is an array of frequencies
      - *Pxx* is a len(times) x len(freqs) array of power
      - *im* is a :class:`matplotlib.image.AxesImage` instance

    Note: If *x* is real (i.e. non-complex), only the positive
    spectrum is shown.  If *x* is complex, both positive and
    negative parts of the spectrum are shown.  This can be
    overridden using the *sides* keyword argument.

    **Example:**

    .. plot:: mpl_examples/pylab_examples/specgram_demo.py

    """

    #####################################
    # modified  axes.specgram() to limit
    # the frequencies plotted
    #####################################

    # this will fail if there isn't a current axis in the global scope
    ax = gca()
    Pxx, freqs, bins = mlab.specgram(x, NFFT, Fs, detrend,
         window, noverlap, pad_to, sides, scale_by_freq)

    # modified here
    #####################################
    if minfreq is not None and maxfreq is not None:
        Pxx = Pxx[(freqs >= minfreq) & (freqs <= maxfreq)]
        freqs = freqs[(freqs >= minfreq) & (freqs <= maxfreq)]
    #####################################

    Z = 10. * np.log10(Pxx)
    Z = np.flipud(Z)

    if xextent is None: xextent = 0, np.amax(bins)
    xmin, xmax = xextent
    freqs += Fc
    extent = xmin, xmax, freqs[0], freqs[-1]
    im = ax.imshow(Z, cmap, extent=extent, **kwargs)
    ax.axis('auto')

    return Pxx, freqs, bins, im

# plot
ax1 = subplot(211)
plot(t, x)
subplot(212, sharex=ax1)

# the minfreq and maxfreq args will limit the frequencies
Pxx, freqs, bins, im = my_specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900,
                                cmap=cm.Accent, minfreq = 180, maxfreq = 220)
show()
close()

rawDescription: Cutting of unused frequencies in specgram matplotlib


code:
import pprint

data = [
    {'title': 'Section 1', 'level': 1, 'page_number': 1},
    {'title': 'Section 1.1', 'level': 2, 'page_number': 2},
    {'title': 'Section 1.2', 'level': 2, 'page_number': 3},
    {'title': 'Section 2', 'level': 1, 'page_number': 4},
    {'title': 'Section 2.1', 'level': 2, 'page_number': 42},
    {'title': 'Section 2.1.1', 'level': 3, 'page_number': 42},
    {'title': 'Section 3', 'level': 1, 'page_number': 42},
]

toc = []
stack = [toc]
for d in data:
    d['sub'] = []
    while d['level'] < len(stack):
        stack.pop()
    while d['level']  > len(stack):
        stack.append(stack[-1][-1]['sub'])
    stack[-1].append(d)

pprint.pprint(toc)

rawDescription: Generate a nested list from flatten data in Python


code: #!/usr/bin/env python

rawDescription: How to run a python program in a shell without typing "python"

description: Run a python program in a shell without typing "python"


code: {country_name: [location, population, president]}

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code:
if request.POST.get('commentup', ''): self.vote += 1
if request.POST.get('commentdown', ''): self.vote -= 1
self.save()

rawDescription: django: Referring to a specific comment in a voting system

description: Django: Referring to a specific comment in a voting system


code:
class TaskThread(object):
    def __call__(self):
        print("in TaskThread.__call__")

pool=multiprocessing.Pool(4)
task=TaskThread()
result = pool.apply_async(task)
result.get()

rawDescription: Is it possible to apply a callable object to a pool of processes?


rawDescription: Return min/max of multidimensional in Python?


code:
import heapq

items = [foo(i) for i in range(10,20)]

queue = [(f.ttu, f.id, f) for f in items]
heapq.heapify(queue)

for t in range(50):
    while t >= queue[0][0]:
        _, _, f = heapq.heappop(queue)
        # update f here
        heapq.heappush(queue, (t + f.ttu, f.id, f))

rawDescription: Vectorising a decrement operation on a list of objects


code:
with open('a.txt') as afile:
    results = []
    for line in afile:
        if 'MyExpression' in line:
            first = int(line.split()[0])
            for nextline in afile:
                if 'MyExpression' in nextline or 'MyExpression2' in nextline:
                    second = int(nextline.split()[0])
                    results.append([first, second])
                    break  # done with the inner loop
    print(results)

rawDescription: For loop when iterating over lines in a file?