rawDescription: How do I modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9?

description: Modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9


code:
class OuterTest:
    def __init__(self, inner_test=None):
        if not inner_test:
            inner_test = InnerTest()
        self.inner_test = inner_test

rawDescription: How to create distinct instances of a class in Python?

description: Create distinct instances of a class in Python


code: [''.join((i,j)) if j != '.' else i for i,j in zip(a,b.ljust(len(a),'.'))]

rawDescription: Zipping strings according to the longer string


code:
import random
import bisect

tasks = list(range(total_lines))
task_indices = random.sample(tasks, 10)

for index in task_indices:
     # find the closest file index
     file_index = offsets[bisect.bisect(offsets, index) - 1]
     path = file_indices[file_index]
     curr_line = file_index
     with open(path) as f:
         while curr_line <= index:
             task = f.readline()
             curr_line += 1
     print(task)
     tasks.remove(index)

rawDescription: Python random lines from subfolders

description: Python random lines from subfolders


rawDescription: Obtain and store adjacent values from a .csv file (Python)


rawDescription: Iterate through XML to get all child nodes text value


code: cafe

rawDescription: Match string with normal characters with special characters in python


code: mod_list(['I', 'did', 'not', 'enjoy', 'the', 'movie'])

rawDescription: How do I modify all terms following a specific term in a list of terms?

description: Modify all terms following a specific term in a list of terms


code: newlist = oldList[:]

rawDescription: Trying to duplicate a list and modify one version of it in Python 2


code: self.driver.execute_script("arguments[arguments.length-1].dir = 'rtl';", TB)

rawDescription: Changing language typing direction using selenium


code:
def verify_auth_token(auth_token):
    serial = Serializer(secret_key)
    try:
        data = serial.loads(auth_token)
    except SignatureExpired:
        return None
    except BadSignature:
        return None
    serial_user = data.get('username')
    return serial_user

rawDescription: Flask RESTful Destroy User Token

description: Flask RESTful Destroy User Token


code:
import sys

fov = float(sys.argv[-1])
...
# Set Scenes camera and output filename
bpy.data.scenes["Scene"].render.file_format = 'PNG'
bpy.data.scenes["Scene"].render.filepath = '//out'

# Render Scene and store the scene
bpy.ops.render.render( write_still=True )

rawDescription: Python script with arguments for command line Blender


rawDescription: itertools dice rolls: doubles roll twice

description: Itertools dice rolls: doubles roll twice


code: output = (np.max(b,axis=1)[...,None] == b) & (b > a)

rawDescription: Numpy: np.where function given argmax

description: Numpy: np.where function given argmax


code: self.FunctionBuffer["stack"].append(lambda: self.ApplyFunction(arg1, arg2, arg3))

rawDescription: Is there a way to append a function with arguments into a list?


rawDescription: How do I match a word if it starts with a nonalphanumeric character in Python?

description: Match a word if it starts with a nonalphanumeric character in Python


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

# data ranges
xr = [5., 8.]
yr = [0., 22.]

# pixel widths
x_pw = np.diff(xr) / (KS_imshow.shape[1])
y_pw = np.diff(yr) / (KS_imshow.shape[0])

# plot the image
plt.imshow(KS_imshow, extent=xr+yr, origin='lower', interpolation='nearest',
        aspect='auto', cmap='Blues', vmin=0., vmax=1.)
cbar = plt.colorbar()

# upscale by a factor of 50 (might be an issue for large arrays)
highres = scipy.ndimage.zoom(KS_imshow, 50, order=0, mode='nearest')

# correct the extent by the pixel widths
extent = np.array(xr+yr) + np.array([x_pw, -x_pw, y_pw, -y_pw]).flatten()/2

# create the contours
CS2 = plt.contour(highres, levels=[0.5], extent=extent, origin='lower',
        colors='r', linewidths=2)
cbar.add_lines(CS2)

plt.show()

rawDescription: How can I have straight contourlines in matplotlib?

description: Have straight contourlines in matplotlib


code:
import json
import json.encoder
import binascii

_default_encode_basestring = json.encoder.encode_basestring
_default_encode_basestring_ascii = json.encoder.encode_basestring_ascii

def _check_string(s):
    if isinstance(s, str):
        try:
            s.decode('utf8')
        except UnicodeDecodeError:
            return False
    return True

def _encode_basestring(s):
    if not _check_string(s):
        s = binascii.b2a_base64(s)
    return _default_encode_basestring(s)

def _encode_basestring_ascii(s):
    if not _check_string(s):
        s = binascii.b2a_base64(s)
    return _default_encode_basestring_ascii(s)

class MyJsonEncoder(json.JSONEncoder):

    def encode(self, o):
        json.encoder.encode_basestring = _encode_basestring
        json.encoder.encode_basestring_ascii = _encode_basestring_ascii
        result = super(MyJsonEncoder, self).encode(o)
        json.encoder.encode_basestring = _default_encode_basestring
        json.encoder.encode_basestring_ascii = _default_encode_basestring_ascii
        return result

rawDescription: How can I override behavior of JSONEncoder for binary data?

description: Override behavior of JSONEncoder for binary data


code:
"""This is the documentation for my module foo."""

def bar(x):
  """This is the documentation for my function foo.bar."""
  return x + 1

rawDescription: Are Python docstrings and comments stored in memory when module is loaded?


code:
def walk_dict(d,depth=0):
    for k,v in sorted(d.items(),key=lambda x: x[0]):
        if isinstance(v, dict):
            print ("  ")*depth + ("%s" % k)
            walk_dict(v,depth+1)
        else:
            print ("  ")*depth + "%s %s" % (k, v)

rawDescription: recursively traverse multidimensional dictionary, dimension unknown

description: Recursively traverse multidimensional dictionary, dimension unknown


code:
def center(self, x):
    'center the data using the mean and sigma from training set a'
    return (x - self.mu)/self.sigma

rawDescription: Basic example for PCA with matplotlib

description: Basic example for PCA with matplotlib


rawDescription: Python: Joining tuples with backslash

description: Python: Joining tuples with backslash


code: target = open("text.txt")

rawDescription: How can I directly access a file in a Python script?

description: Directly access a file in a Python script


code:
def percentage_dict(d):
    s = float(sum(d.values()))
    return {k: 100 * v / s for k, v in d.items()}

rawDescription: Reverse multiple values with keys in dictionary


rawDescription: Retrieving .loc index values in pandas dataframe


code:
f=open('test1.txt', 'w')
for i in range(1000):
    f.write('\n')
f.close()

rawDescription: Python file open/close everytime vs keeping it open until the process is finished


code:
def get_absolute_url(self):
   return "An url computed with resolve() for example"

rawDescription: Navigating from admin site to one of my apps in same project


code:
m = re.match(r"^\s*(\w+)\s*\|(?:\s*(\w+)\s*)*$", " network | level1 level2 leveln ")
m
m.groups()

rawDescription: regex help using repreated groups

description: Regex help using repreated groups


rawDescription: Why does numpy indexing work differently in higher dimensions?


code: [''.join(e) for e in list(izip_longest(*[iter(data)] * 2,fillvalue=''))]

rawDescription: Parse String every 2 letters

description: Parse String every 2 letters


code:
len(data['res'])
bb['res'][0]  # First response
bb['res'][1]  # Second response

rawDescription: Storing Multiple responses in dictionaries


code: merged = [ l1 + l2 for l1,l2 in zip(list1,list2) ]

rawDescription: Conditionally merge lists

description: Conditionally merge lists


code:
from datetime import datetime, timedelta
end = datetime(2014, 9, 1, 22, 45)
end += timedelta(hours=1)
end
end += timedelta(hours=1)
end

rawDescription: How to naturally roll-over to the next day when adding hours to a datetime

description: Naturally roll-over to the next day when adding hours to a datetime


code:
import re
p = re.compile(r'\s*\([^()]*\)[ \t]*$', re.MULTILINE)
s = "%\nO1000\nT1 M6\nG0 G90 G40 G21 G17 G94 G80\nG54 X-75 Y-25 S500 M3  (Start Point)\nG43 Z100 H1\nZ5\nG1 Z-20 F100\nX-50 M8               (Position 1)\nY0                    (Position 2)\nX0 Y50                (Position 3)\nX50 Y0                (Position 4)\nX0 Y-50               (Position 5)\nX-50 Y0               (Position 6)\nY25                   (Position 7)\nX-75                  (Position 8)\nG0 Z100\nM30\n%"
result = p.sub("", s)
print(result)

rawDescription: Regex return everthing but compound expression


code:
# coding: utf-8

import xml.etree.ElementTree as ET

root = ET.Element(u'Prüfung')
main = ET.SubElement(root, 'Test')
main.text = u'\xe4 ' + u'ä'
tree = ET.ElementTree(root)
tree.write('testout.xml', encoding="utf-8")    # The default encoding is us-ascii

rawDescription: Using special characters in XML Tags/Textes


code:
from decimal import Decimal, ROUND_HALF_UP
x = Decimal('2.47')
x.quantize(Decimal('1'), rounding=ROUND_HALF_UP).quantize(Decimal('0.01'))

rawDescription: python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP

description: Python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP


code:
from tempfile import NamedTemporaryFile
from shutil import move

def add_new(new):
    with open("check.txt") as f, NamedTemporaryFile("w",delete=False) as tmp:
        for line in f:
            if line.startswith("Tags ="):
                repl = ", {}]".format(new) if "[]" not in line else "{}]".format(new)
                tmp.write(line.replace("]", repl))
                tmp.writelines(f)
                break
            tmp.write(line)
    move(tmp.name, "check.txt")

rawDescription: Python - Write to specific part of file, not by line - Regex


code:
def succ(self, node):
    size = len(node)

    # find all legal moves going forward
    for pos in range(size-2):
        new_node = list(node)
        if ((node[pos] == 1) and (node[pos+2] == 0)):
            new_node[pos] = 0  # we're moving now
            new_node[pos+2] = 1 # this is where we're moving the peg to
            new_node[pos+1] = 0  # take out the peg here if there was one
            yield new_node

    # find all legal moves going backwards
    for pos in range(1,size):
        new_node = list(node)
        if ((node[pos] == 1) and (node[pos-2] == 0)):
            new_node[pos] = 0  # we're moving now
            new_node[pos-2] = 1 # this is where we're moving the peg
            new_node[pos-1] = 0  # take out the peg here if there was one
            yield new_node

rawDescription: Depth-First search in Python

description: Depth-First search in Python


code:
import re
slangNames = set(["Vikes", "Demmies", "D"])
r = re.compile(r"\bMS Contin\b")
riskNames = set(["enough", "pop", "final", "stress", "trade"])
d =  {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"}

for k,v in d.items():
    spl = v.split()
    if (not slangNames.isdisjoint(spl) or r.search(v)) and not riskNames.isdisjoint(spl):
        print(k,v)

rawDescription: How to match words in 2 list against another string of words without sub-string matching in Python?

description: Match words in 2 list against another string of words without sub-string matching in Python


code:
def __gt__(self, other): # is self greater than other?
    return self.value > other.value # compare value attribute

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


code:
f = open('/usr/share/dict/words')
d = {}
lets = set('abcdefghijklmnopqrstuvwxyz\n')
for word in f:
  if len(set(word) - lets) == 0 and len(word) > 2 and len(word) < 9:
    word = word.strip()
    key = ''.join(sorted(word))
    if key in d:
      d[key].append(word)
    else:
      d[key] = [word]
f.close()
anadict = [' '.join([key]+value) for key, value in d.iteritems()]
anadict.sort()
f = open('anadict.txt','w')
f.write('\n'.join(anadict))
f.close()

rawDescription: How can this Python Scrabble word finder be made faster?


rawDescription: Selecting specific rows from a python dataframe for an ols regression in PANDAS


code:
if my_form.is_valid():
    data = request.FILES['myfile'].read()

rawDescription: Django: Open uploaded file while still in memory; In the Form Clean method?


code:
class foo(object):
    methods = { 1: 'a', 2: 'b' }
    def go(self, n):
        getattr(self, self.methods[n])()

rawDescription: Method entry points in a class variable

description: Method entry points in a class variable


code:
def factorization(n):
    """
    Generate the prime factorization of n in the form of pairs (p, k)
    where the prime p appears k times in the factorization.

    >>> list(factorization(1))
    []
    >>> list(factorization(24))
    [(2, 3), (3, 1)]
    >>> list(factorization(1001))
    [(7, 1), (11, 1), (13, 1)]
    """
    p = 1
    while p * p < n:
        p += 1
        k = 0
        while n % p == 0:
            k += 1
            n //= p
        if k:
            yield p, k
    if n != 1:
        yield n, 1

rawDescription: How would you implement a divisor function?


code:
# Run kernels many times, we will only keep data from last loop iteration.
for j in range(10):
    for k in range(n):
        event[k]['kernel_begin'].record(stream[k])
        my_kernel(d_data[k], block=(N,1,1), stream=stream[k])
#    for k in range(n): # Commenting out this line should break concurrency.
        event[k]['kernel_end'].record(stream[k])

rawDescription: Pycuda Concurrency

description: Pycuda Concurrency


code:
bits3d = BitArray(1000, 1000, 1000)
myvalue = bits3d[x, y, z]

rawDescription: python multidimensional boolean array?

description: Python multidimensional boolean array


code:
df_q = pd.DataFrame()
for col in df:
    df_q[col] = pd.qcut(df[col], 5, labels=list(range(5)))

rawDescription: python - possible to apply percentile cuts to each column in a dataframe?

description: Python - possible to apply percentile cuts to each column in a dataframe


code:
browser = QAxContainer.QAxWidget()
browser.setControl("<ActiveX ID>") # e.g. "{8856F961-340A-11D0-A96B-00C04FD705A2}"
browser.dynamicCall('Navigate(const QString&)', QtCore.QString("google.com"))

rawDescription: How to create a HTML-dialog window in Python with Internet Explorer control?

description: Create a HTML-dialog window in Python with Internet Explorer control


code:
g = df.groupby(['Column2', 'Column3', 'Column4'])
df1 = df.set_index(['Column2', 'Column3', 'Column4'])
df1.index.map(lambda ind: g.indices[ind][0])
df['dup_index'] = df1.index.map(lambda ind: g.indices[ind][0])
df

rawDescription: How to identify the first occurence of duplicate rows in Python pandas Dataframe

description: Identify the first occurence of duplicate rows in Python pandas Dataframe


code: df = df.divide(df.sum(axis=1), axis=0)

rawDescription: 100% area plot of a pandas DataFrame

description: 100% area plot of a pandas DataFrame


code:
import re

uescapes = re.compile(r'(?<!\\)\\u[0-9a-fA-F]{4}', re.UNICODE)
def uescape_decode(match): return match.group().decode('unicode_escape')

uescapes.sub(uescape_decode, response.text)

rawDescription: python mixed single and double unicode escape sequences

description: Python mixed single and double unicode escape sequences


code:
print(max(max(lst) for lst in scores[1:3]))
print(tuple(max(lst) for lst in scores[1:3]))
print(tuple(max(lst) for lst in scores[0:3]))

rawDescription: Max() returns highest list, not number

description: Max() returns highest list, not number


code:
# If script_dir is relative, the current working directory is used, here. This is correct if the current
# working directory is the same as when the script was read by the Python interpreter (which is
# when __file__ was set):
script_dir = os.path.abspath(script_dir)

rawDescription: Where does python look for files in a script?


code: im = Image.fromarray(my_array)

rawDescription: Convert black and white array into an image in python?


code:
fdna == atgggatggtagatggatgggATGGGGTGA
find_ORF_seq(fdna)
['ATGGGATGGTAG', 'ATGGTAG', 'ATGGATGGGATGGGGTGA', 'ATGGGATGGGGTGA']
getSequences(fdna)
['ATGGGATGGTAG', 'ATGGATGGGATGGGGTGA']

rawDescription: Limiting re.findall() to record values before a certain number. Python


code:
d = []
for o in (0, 1):
    t = rating[own == o]
    t["own"] = o
    d.append(t)

res = pd.concat(d).groupby("own").mean()

rawDescription: Pandas: Pivoting with multi-index data

description: Pandas: Pivoting with multi-index data


code:
button1 = Button(master, text='Search')
button1.configure(command=lambda widget=button1: DoSomething(widget))
button2 = Button(master, text='Search')
button2.configure(command=lambda widget=button2: DoSomething(widget))

rawDescription: Python Tkinter one callback function for two buttons


code:
print(local_minima_locations)
# (array([0, 0, 1, 1]), array([0, 4, 1, 3]), array([3, 0, 1, 3]))
print(arr[local_minima_locations])
# [-1 -1 -1 -1]

rawDescription: How to find the local minima of a smooth multidimensional array in NumPy efficiently?

description: Find the local minima of a smooth multidimensional array in NumPy efficiently


code:
stc = sum(tensorcontraction(tp, (1, 2)))
stc

rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


code: comparison |= mask

rawDescription: Python Pandas Compare 2 Large DataFrames of Text for Similarity


code:
def locate_squares(im):
    r,g,b = im.split()
    red = np.array(r)
    green = np.array(g)
    green_template = green[144:194,297:347]  #,144:194]
    gRadius = (green_template.shape[0]/2, green_template.shape[1]/2)
    red_template = red[145:195,252:302]    #,145:195]
    rRadius = (red_template.shape[0]/2, red_template.shape[1]/2)
    #print red_template

    plt.figure(1)
    plt.subplot(1,2,1)
    plt.imshow(green_template)
    plt.subplot(1,2,2)
    plt.imshow(red_template)

    plt.figure(2)
    plt.subplot(1,2,1)
    plt.imshow(green)
    plt.subplot(1,2,2)
    plt.imshow(red)

    plt.show()

rawDescription: Why does skimage.imread() not return RGB values for my bmp?


code:
import numpy as np
np.histogram2d(x, y, bins=(nx,ny), normed=True)

rawDescription: Python: XY density plot

description: Python: XY density plot


code:
fopen = open('infile.txt', 'r+')
fileinput = fopen.read()

for line in fileinput.splitlines():
    for word in line.split():
        print(word)

fopen.close()

rawDescription: Trying to count words in a file using Python


code:
class Wrapped (object):
    __metaclass__ = Wrapper

rawDescription: How to get a method called (decorator?) after every object method

description: Get a method called (decorator?) after every object method


rawDescription: Python: List Comparison to find unique element count of lists


code:
import re
fname = re.sub(r"\.csv$", "", fname)

rawDescription: python strip function is not giving expected output

description: Python strip function is not giving expected output


code:
lista
i = lista[0]      # i points to first element of lista
i
i = 'a'           # Now i points to a new object 'a'
lista             # So lista remains as it was before
lista[0] = 'a'    # Here we are replacing the first element of lista with 'a'
lista

rawDescription: Modifing element in array using for and in


code:
# set the green panel to twice the size of the black one
main_sizer3.Add(tree_panel, 1, wx.EXPAND|wx.RIGHT, 5)
main_sizer3.Add(entry_panel, 2, wx.EXPAND)
# and another proportion missing:
main_sizer2.Add(main_sizer3, 1, wx.EXPAND|wx.ALL, 5)

rawDescription: wxPython Nested Panel and Sizers

description: WxPython Nested Panel and Sizers


code:
class SomeModel(models.Model):
    ...
    user = models.ForeignKey(User)

# Later ...

some_user.somemodel_set.all()

rawDescription: How the datas are connected to the specific user ID?


rawDescription: Python Numpy Structured Array (recarray) assigning values into slices


code:
import os
def touch(fname, mode=0o666, dir_fd=None, **kwargs):
    flags = os.O_CREAT | os.O_APPEND
    with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:
        os.utime(f.fileno() if os.utime in os.supports_fd else fname,
            dir_fd=None if os.supports_fd else dir_fd, **kwargs)

rawDescription: Implement touch using Python?

description: Implement touch using Python


code:
frame.duplicated(['key1', 'key2'])
frame.duplicated(['key1', 'key2'], take_last=True)
frame.duplicated(['key1', 'key2'], take_last=True) | frame.duplicated(['key1', 'key2'])
frame[frame.duplicated(['key1', 'key2'], take_last=True) | frame.duplicated(['key1', 'key2'])]

rawDescription: How to analyze all duplicate entries in this Pandas DataFrame?

description: Analyze all duplicate entries in this Pandas DataFrame


code:
a = {'foo': 3}
json.dumps(a)

rawDescription: What is the difference between json.dumps and json.load


code: print(*objects, sep=' ', end='\n', file=sys.stdout)

rawDescription: Determining a functions output as print or write


code:
df = pd.DataFrame(np.random.randn(8,4))
df.columns = df.columns.astype(float)
df
sliceDataframe(df, 0.5)

rawDescription: Selection of a Series from pandas dataframe by interpolating column labels


code:
def foo(A, B=A):
    do_something()

rawDescription: Python optional function argument to default to another argument's value


code: findpass = lines[i].rstrip('\n')

rawDescription: Python variables stored in text files not working, but should be


code:
import string
import itertools

chars = string.ascii_letters + string.digits

def alpha_perms(index):

    return list(itertools.permutations(chars[index:]))

print(alpha_perms(0)) #0th index to go along with the below statement

rawDescription: How can i start itertools combinations from specific letter/digit?

description: Start itertools combinations from specific letter/digit


rawDescription: Remove list element without mutation

description: Remove list element without mutation


code:
from nltk.tag import pos_tag

sentence = "Michael Jackson likes to eat at McDonalds"
tagged_sent = pos_tag(sentence.split())
# [('Michael', 'NNP'), ('Jackson', 'NNP'), ('likes', 'VBZ'), ('to', 'TO'), ('eat', 'VB'), ('at', 'IN'), ('McDonalds', 'NNP')]

propernouns = [word for word,pos in tagged_sent if pos == 'NNP']
# ['Michael','Jackson', 'McDonalds']

rawDescription: Finding Proper Nouns using NLTK WordNet

description: Finding Proper Nouns using NLTK WordNet


code: hours, minutes = [int(x) for x in "126:00".split(":")]

rawDescription: How to get hhh:mm datetime format with Python?

description: Get hhh:mm datetime format with Python


code:
matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
    for i in k:
        dup.append(i)

print (max(dup), min(dup))

rawDescription: Find maximum and minimum value of a matrix


code:
data = data.join(df['Qnet'], rsuffix='_new')
data['Qnet'] = data['Qnet'].combine_first(data['Qnet_new'])
data.drop(['Qnet_new'], axis=1, inplace=True)

rawDescription: How do I merge two columns in a dataframe based on a datetime index?

description: Merge two columns in a dataframe based on a datetime index


rawDescription: How to generate regex to match access.log acording to its format config?

description: Generate regex to match access.log acording to its format config


code: OrderedDict([(u'to', u'Tove'), (u'from', u'Jani'), (u'heading', u'Reminder'), (u'body', u"Don't forget me this weekend!")])

rawDescription: convert xml to python dict

description: Convert xml to python dict


code:
d.year
d.month
d.day

rawDescription: python: access a date field attributes

description: Python: access a date field attributes


code:
stopwords_set = set(stopwords)
with open('document') as doc:
    words = doc.read()
    with open('set_document', 'w') as set_doc:
        for word in words.split(' '):
            if not word in stopwords_set:
                set_doc.write(word + ' ')

rawDescription: Removing stopwords with Python - quickly and efficiently


code: depth(l)

rawDescription: having trouble understanding this code

description: Having trouble understanding this code


code:
import datetime

first=datetime.date(2009,10,12)
last=datetime.date(2009,10,20)
adate=first
dates=[]
while adate<=last:
    dates.append(adate)
    adate+=datetime.timedelta(1)
print(dates)

rawDescription: Enumerate a DateRange

description: Enumerate a DateRange


code:
x = ['ala@ala.com', 'bala@bala.com']
x
x.remove('ala@ala.com')
x

rawDescription: How to remove specific element in an array using python

description: Remove specific element in an array using python


code:
print(ET.tostring(xml_obj, pretty_print=True))
# <A>
#   <B foo="baz" baz="boo"/>
#   <B foo="blah"/>
# </A>

rawDescription: Getting valueless elements in python lxml


code:
regex = re.compile('sw_apple-mc-stded.*')  # add wildcard at the end to match entire string
firmware = []
for list in lists:
    firmware.extend(regex.findall(list))  # extend as findall returns a list
return firmware

rawDescription: Python regex in lists

description: Python regex in lists


code:
String = "I am Nirman"
String.rindex('a')

rawDescription: Finding index number for a character of a particular word in the string


code:
timeit.timeit('f()', 'from __main__ import withchain as f')
timeit.timeit('f()', 'from __main__ import withsum as f')
timeit.timeit('f()', 'from __main__ import withlistcomp as f')

rawDescription: how to add all array's elements to one list in python

description: Add all array's elements to one list in python


code:
for line in myfile:
   ...

rawDescription: why we recommend iterators instead of lists (low-level explanation)

description: Why we recommend iterators instead of lists (low-level explanation)


code:
funct(
    Data(data1, x="x_val", y="y_val"),
    Data(data2, x="x_val", y="y_val"),
    Data(data3, x="x_val", y="y_val", other_args="other_args_val")
)

rawDescription: Method signature for variable length of arguments


code: df.set_index('model' , inplace=True)

rawDescription: Transforming DataFrame (pivot)

description: Transforming DataFrame (pivot)


code:
from operator import methodcaller
funcs = (lambda x: x + 1, lambda x: x + 2)
obj = 5
map(methodcaller('__call__', obj), funcs)

rawDescription: Apply list of functions on an object in Python


rawDescription: Django query with contains and keywords

description: Django query with contains and keywords


code:
i = 0
while True:
    if i > 100:
       break
    i = i + 10

rawDescription: Steps for "for loop" in python

description: Steps for "for loop" in python


code:
from __future__ import print_function

show = False
for line in fobj:
    if line.strip().startswith('[+]'):
        print()
        show = True
    elif not line.strip():
        show = False
    if show:
        print(line, end='')

rawDescription: In python read from one specific word in a file to another specificword in a file multiple times


rawDescription: Copying specific lines after a string match and using them to replace other lines in another file


code: headers = [header for header in tmp_dict.keys() if not str(header).isdigit()]

rawDescription: Skip keys without Type checking in Python (pymssql)


rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


code:
from sklearn.externals.six import StringIO
import pydot
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

rawDescription: Is it possible to print the decision tree in scikit-learn?


code:
msg['To'] = ",".join(you)

...

s.sendmail(me, you, msg.as_string())

rawDescription: Email multiple contacts in Python

description: Email multiple contacts in Python


code:
from numpy import take,argsort

take(opt,argsort(argsort(perc)[::-1]))

rawDescription: Sort a list based on a given distribution


code: self.selectAll=Button(self, text="select all", command=self.selectAllCallback)

rawDescription: Select all in a tkinter Listbox

description: Select all in a tkinter Listbox


code: ('/post/(\d+)', views.PostHandler)

rawDescription: Is it possible to retrieve an uri chunk on AppEngine?


rawDescription: Draw a cumulative chart from a pandas dataframe?


code: my_current_fav.car = cars[0] # or Car('whatever')

rawDescription: Pointing to another object's attributes and adding your own


code:
# other files:
from main import lock

# use the lock...

rawDescription: Passing locks in python

description: Passing locks in python


code:
from datetime import datetime
from decimal import Decimal

td = datetime.utcnow() - datetime(1970, 1, 1)
timestamp_microseconds = (td.days*86400 + td.seconds)*10**6 + td.microseconds
d = Decimal(timestamp_microseconds).scaleb(-6)

rawDescription: Need a timestamp with microseconds as Decimal


code:
from xml.dom import minidom
import sys
import myParsers # a module containing your parsers

xmldoc = minidom.parse(sys.stdin).documentElement

myParserName = xmldoc.nodeName
myParserClass = getattr(myParsers, myParserName)
# create an instance of myParserClass by calling it with the documentElement
parser = myParserClass(xmldoc)
# do whatever you want with the instance of your parser class
output = parser.generateOutput()

rawDescription: Python metaprogramming for XML parsing

description: Python metaprogramming for XML parsing


rawDescription: Replacing an element of a list with multiple values


code:
import numpy as np
x = np.zeros((parts, 2))
for i in range(parts):
    x[i,0] = i*L + 1
    x[i,1] = (i+1)*L

rawDescription: for looping through arrays in python- from matlab

description: For looping through arrays in python- from matlab


code:
class SourceBase(object):
    __metaclass__=abc.ABCMeta

rawDescription: Dynamically loaded subclass can still instanstiate even without all abstract methods overridden


code:
fd = pickle.load(open("data/fd.txt", 'rb'))

def compute_ave_freq(word_forms):
    total_freq = 0
    for form in word_forms:
        freq = fd.freq(form)
        total_freq += freq
    try:
        ave_freq = total_freq/len(word_forms)
    except ZeroDivisionError:
        ave_freq = 0
    return ave_freq

rawDescription: Faster way to store a NLTK FreqDict?

description: Faster way to store a NLTK FreqDict


code:
syms = symbols("x:4")
s = Matrix(syms)
constraints = [xi**3 - xi for xi in syms]
A*s
solve(list(A*s) + constraints, syms, dict=True)

rawDescription: How to solve non-linear sets of equations

description: Solve non-linear sets of equations


code:
resultat.writerow([info1, info2] + [line[1:18]]) # WRONG (sorry!)
resultat.writerow([info1, info2] + line[1:18]) # RIGHT

rawDescription: How to use csv.reader in python with french character like é,à,ç,ê,ë,

description: Use csv.reader in python with french character like é,à,ç,ê,ë,


rawDescription: group dictionary by values in a new nested one

description: Group dictionary by values in a new nested one


code:
col = ['colnames']
def quality_check(q):
    spl = map(int,q.split(","))  #  make all ints  and split into individual nums
    if set(spl).issubset( [7, 8, 9, 10, 12, 13, 15, 23, 24, 25, 26]):
        return "good"
    else:
        return "poor"

rawDescription: Check list of numbers is a subset

description: Check list of numbers is a subset


code:
from collections import defaultdict
from itertools import chain

def inner_join(a, b):
    d = defaultdict(list)
    for row in chain(a, b):
        d[row[0]].append(row[1:])
    for id, rows in d.iteritems():
        if len(rows) > 1:
            assert len(rows) == 2
            yield (id,) + rows[0] + rows[1]

rawDescription: How do I merge two lists of tuples based on a key?

description: Merge two lists of tuples based on a key


code:
from datetime import date
from operator import attrgetter
l = [date(2014, 4, 11), date(2014, 4, 2), date(2014, 4, 3), date(2014, 4, 8)]
sorted(l, key=attrgetter('day'))
sorted(l, key=attrgetter('day'), reverse=True)

rawDescription: python object list, sort in descending order based on object attribute

description: Python object list, sort in descending order based on object attribute


rawDescription: Count occurences of a row with pandas in python


rawDescription: How can i extend a model through a reusable app?

description: Extend a model through a reusable app


code:
def foo(a):
    a = 2
foo(1)

rawDescription: Hand over global variables to methods in python?


rawDescription: Find values from MongDB from an array for only one date


code:
from __future__ import print_function
print(string, end="")

rawDescription: Methods for printing without adding control characters in python


code:
df
df[df['category'] != 'purple'][['amount','freq']]

rawDescription: slice pandas dataframe by column showing all except the column provided

description: Slice pandas dataframe by column showing all except the column provided


code:
ln, = ax.plot(x,y,z)
# some code that updates the x,y,z values -> new_x,new_y,new_z
ln.remove
ln, = ax.plot(new_x,new_y,new_z)
plt.draw()

rawDescription: How to plot a queue of points?

description: Plot a queue of points


code:
# In main.py
b = module1.Button(command=quitgame)

# In module1.py
def checkClick(self, local):
    ...
    self.command()

rawDescription: Call a function from main script in an imported file


code:
for i in range(1000):
    t = threading.Thread(target = worker)
    threads.append(t)
    t.start()

rawDescription: why using multiple threading to get the sum is correct?

description: Why using multiple threading to get the sum is correct


code: l.sayYourAge(-1, offset=1)  # will say "I am 32, what did you think?"

rawDescription: Decorator and closures

description: Decorator and closures


code:
for smiley, placeholder in d.iteritems():
    s = s.replace(placeholder, smiley)

rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


code:
print(result.dtype)
# [('job', '|S7'), ('avg_income', '<f8')]

rawDescription: pythonic way to aggregate arrays (numpy or not)

description: Pythonic way to aggregate arrays (numpy or not)


rawDescription: Boost::Python class with function templates: How to add instances from the outside?


code:
def search_view(request, a, b):
    myobj = MyModel.objects.get(field1=a, field2=b)

rawDescription: Django template/form for user input

description: Django template/form for user input


code:
for dir_ in directories:
    your_search_function(dir_)

rawDescription: Capture subdirectory names as variable

description: Capture subdirectory names as variable


code: person = Person(firstName='Peter', lastName='Smith', age=21)

rawDescription: Automatically setting getter, setter and deleter in python


code:
import matplotlib as mpl
mpl.is_interactive()

rawDescription: Matplotlib can't suppress figure window

description: Matplotlib can't suppress figure window


code:
import re
import xml.etree.ElementTree as ElementTree

def map_translations(origin_file, translate_file):
    origin_tree = ElementTree.parse(origin_file)
    origin_root = origin_tree.getroot()

    origin_text = [string.text for text_elem in origin_root.iter('Texts')
                   for string in text_elem]

    translate_tree = ElementTree.parse(translate_file)
    translate_root = translate_tree.getroot()

    namespace = re.match('{.*}', translate_root.tag).group()

    translate_text = [text.text for text in translate_root.findall(
                          './/{}TranslatedText'.format(namespace))]

    return dict(zip(origin_text, translate_text))

origin_file = 'some_file_path.xml'
translate_file = 'some_other_path.xml'

mapping = map_translations(origin_file, translate_file)

print(mapping)

rawDescription: Matching the XML Req and Res

description: Matching the XML Req and Res


code: temp = guess

rawDescription: Python overwriting my original list

description: Python overwriting my original list


code: attendee_by_role = session.query(Attendee).filter(getattr(Attendee, role) == True)

rawDescription: Substituting variable into SQLAlchemy / Postgresql Query


code:
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('create table test (col1,col2)')
c.execute("insert into test values (1,'foo')")
c.execute("insert into test values (2,'bar')")
[r for r in dict_gen(c.execute('select * from test'))]

rawDescription: Python - mysqlDB, sqlite result as dictionary


code:
from scipy.ndimage import binary_closing
out = mask | binary_closing(mask, structure=np.ones(threshold))

rawDescription: Find consecutive unmasked values

description: Find consecutive unmasked values


code:
from itertools import groupby
def eliminate_duplicates(lst):
    [k for k,g in groupby(sorted(lst))]

rawDescription: Inquiry about removing duplicates

description: Inquiry about removing duplicates


code:
fieldnames = ['Date', 'Time', 'exid']
writer.writerow({fieldnames[i]: e for i, e in enumerate(item.split())})

rawDescription: Build string by selecting column in csv

description: Build string by selecting column in csv


code:
class TProfiles(models.Model):
    first_name = models.CharField(max_length=45, blank=True)
    surname = models.CharField(max_length=45, blank=True)
    email = models.CharField(max_length=45, blank=True)
    unique_id = models.CharField(max_length=100, blank=True)

    class Meta:
        managed = False
        db_table = 'profiles'

class Photo( models.Model ):
    file = models.FileField( upload_to = settings.MEDIA_ROOT )
    file_name = models.CharField(max_length=45, blank=True)
    unique_id = models.CharField(max_length=100, blank=True)
    event_location_time = models.ForeignKey(TProfiles)

    def extension(self):
        name, extension = os.path.splitext(self.file.name)
        return extension

rawDescription: Join two models together using a common column


code:
mydll=ctypes.CDLL('mydll')
connection_t = ctypes.c_uint32
link = mydll.link
link.argtypes=(ctypes.c_char_p, ctypes.POINTER(connection_t) )
connection = connection_t()
link("localhost: 5412", ctypes.byref(connection))

func=mydll.func
status_t=ctypes.c_uint32
status=status_t()
func.argtypes=(ctypes.POINTER(connection_t),ctypes.POINTER(status_t))
result=func(ctypes.byref(connection), ctypes.byref(status))

rawDescription: passing object as an argument of function

description: Passing object as an argument of function


code: [x[0] for x in lista[:5]]

rawDescription: how to get the items with maximal score in a list

description: Get the items with maximal score in a list


code:
def __init__(self, windowID):

    self._display = Display()
    self._window = self._display.create_resource_object('window', windowID)

def reserve_space(self, left=0, right=0, top=0, bottom=0):

    LEFT    = left
    RIGHT   = right
    TOP     = top
    BOTTOM  = bottom

    self._window.change_property(self._display.intern_atom('_NET_WM_STRUT'),
                                self._display.intern_atom('CARDINAL'),
                                32, [LEFT, RIGHT, TOP, BOTTOM])
    self._display.sync()

rawDescription: Python: tell X to reserve screen space for application


code:
class Test():
    def hello(self):
        global x
        if x == "me":
            x = "Hei..!"
            return "success"

Test().hello() #Use Parenthesis to call the function.

rawDescription: How to access global variable in Python?

description: Access global variable in Python


rawDescription: Making a numpy array with mixed types and writing it as csv


rawDescription: Django All-Auth - Validate against linked object on account creation?


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

fig1 = plt.figure()
plt.plot(np.arange(10))

fig2 = plt.figure()
plt.plot(-np.arange(3, 50), 'r-')

rawDescription: Saving all open matplotlib figures in one file at once


code: set.intersection(*(set(m.group() for m in p.finditer(i)) for i in strList))

rawDescription: FInd repeated pattern between strings

description: FInd repeated pattern between strings


code:
def normalize_ext(image_field):
    try:
        from PIL import Image
    except ImportError:
        import Image
    ext = Image.open(image_field).format
    if hasattr(image_field, 'seek') and callable(image_field.seek):
       image_field.seek(0)
    ext = ext.lower()
    if ext == 'jpeg':
        ext = 'jpg'
    return '.' + ext

rawDescription: Django admin file upload with current model id


rawDescription: Google spreadsheet data into pandas dataframe


code:
# weight initializer, normal by default
def norm_weight(nin, nout=None, scale=0.01, ortho=True):
    if nout is None:
        nout = nin
    if nout == nin and ortho:
        W = ortho_weight(nin)
    else:
        W = scale * numpy.random.randn(nin, nout)
    return W.astype('float32')

def param_init_lstm(options, params, prefix='lstm'):
    """
    GRU. Source: https://github.com/kyunghyuncho/dl4mt-material/blob/master/session0/lm.py
    """
    nin = options['dim_proj']
    dim = options['dim_proj']
    # embedding to gates transformation weights, biases
    W = numpy.concatenate([norm_weight(nin, dim),
                           norm_weight(nin, dim)], axis=1)
    params[_p(prefix, 'W')] = W
    params[_p(prefix, 'b')] = numpy.zeros((2 * dim,)).astype('float32')

    # recurrent transformation weights for gates
    U = numpy.concatenate([ortho_weight(dim),
                           ortho_weight(dim)], axis=1)
    params[_p(prefix, 'U')] = U

    # embedding to hidden state proposal weights, biases
    Wx = norm_weight(nin, dim)
    params[_p(prefix, 'Wx')] = Wx
    params[_p(prefix, 'bx')] = numpy.zeros((dim,)).astype('float32')

    # recurrent transformation weights for hidden state proposal
    Ux = ortho_weight(dim)
    params[_p(prefix, 'Ux')] = Ux
    return params

def lstm_layer(tparams, state_below, options, prefix='lstm', mask=None):

    nsteps = state_below.shape[0]

    if state_below.ndim == 3:
        n_samples = state_below.shape[1]
    else:
        n_samples = state_below.shape[0]

    dim = tparams[_p(prefix, 'Ux')].shape[1]

    if mask is None:
        mask = tensor.alloc(1., state_below.shape[0], 1)

    # utility function to slice a tensor
    def _slice(_x, n, dim):
        if _x.ndim == 3:
            return _x[:, :, n*dim:(n+1)*dim]
        return _x[:, n*dim:(n+1)*dim]

    # state_below is the input word embeddings
    # input to the gates, concatenated
    state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \
        tparams[_p(prefix, 'b')]
    # input to compute the hidden state proposal
    state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + \
        tparams[_p(prefix, 'bx')]

    # step function to be used by scan
    # arguments    | sequences |outputs-info| non-seqs
    def _step_slice(m_, x_, xx_,  h_,          U, Ux):
        preact = tensor.dot(h_, U)
        preact += x_

        # reset and update gates
        r = tensor.nnet.sigmoid(_slice(preact, 0, dim))
        u = tensor.nnet.sigmoid(_slice(preact, 1, dim))

        # compute the hidden state proposal
        preactx = tensor.dot(h_, Ux)
        preactx = preactx * r
        preactx = preactx + xx_

        # hidden state proposal
        h = tensor.tanh(preactx)

        # leaky integrate and obtain next hidden state
        h = u * h_ + (1. - u) * h
        h = m_[:, None] * h + (1. - m_)[:, None] * h_

        return h

    # prepare scan arguments
    seqs = [mask, state_below_, state_belowx]
    _step = _step_slice
    shared_vars = [tparams[_p(prefix, 'U')],
                   tparams[_p(prefix, 'Ux')]]

    init_state = tensor.unbroadcast(tensor.alloc(0., n_samples, dim), 0)

    rval, updates = theano.scan(_step,
                                    sequences=seqs,
                                    outputs_info=[init_state],
                                    non_sequences=shared_vars,
                                    name=_p(prefix, '_layers'),
                                    n_steps=nsteps,
                                    strict=True)
    return rval

rawDescription: GRU implementation in Theano

description: GRU implementation in Theano


rawDescription: How to I extract floats from a file in Python?

description: I extract floats from a file in Python


code:
import requests

url = 'https://api.box.com/2.0/files/content'
h.headers = {'Content-type': 'application/x-www-form-urlencoded',
             'Authorization':'Bearer TOKEN'}

h.kwargs = {"name": "Wolves owners.ppt",
            "parent": {"id": "2841136315"},
            "size": 15243}

resp = requests.options(url, headers=h.headers, data=json.dumps(h.kwargs))

rawDescription: python requests authorization fails when json.dumps included

description: Python requests authorization fails when json.dumps included


code:
k,m,n = A.shape
((A.transpose(2,0,1).reshape(-1,m).dot(B.T)).reshape(n,-1)).dot(A.reshape(-1,n)).T

rawDescription: Simplifying double einsum

description: Simplifying double einsum


rawDescription: make a tree based on the key of each element in list

description: Make a tree based on the key of each element in list


code:
from struct import pack, unpack
unpack('<H', '\x12\x13')
pack('>H', *unpack('<H', '\x12\x13'))

rawDescription: flip bytes using Python's struct module

description: Flip bytes using Python's struct module


code:
df['is_day_max'] = day_max.lookup(df.index.normalize(), len(df) * ['val']) == df.val
df

rawDescription: Hourly frequency count with Python

description: Hourly frequency count with Python


code:
class_room1 = Classroom.objects.get(id=1)
class_room1.student_set.all()

rawDescription: Create data by combining query results in Django


code:
import csv
import requests

from bs4 import BeautifulSoup

columns = ["ACN", "ABN", "Annual Turnover", "QA"]
urls = ["http://www.aidn.org.au/Industry-ViewCompany.asp?CID=3113", ] # ... etc.

with open("data.csv", "w") as csv_file:
    writer = csv.DictWriter(csv_file, columns)
    writer.writeheader()
    for url in urls:
        soup = BeautifulSoup(requests.get(url).text)
        row = {}
        for heading in soup.find_all("td", {"class": "paraheading"}):
            key = " ".join(heading.text.split()).rstrip(":")
            if key in columns:
                next_td = heading.find_next_sibling("td", {"class": "bodytext"})
                value = " ".join(next_td.text.split())
                row[key] = value
        writer.writerow(row)

rawDescription: Scrape a series of tables with BeautifulSoup


code:
self.edits = []
for w in range(x):
    s = "s"+str(w)
    s = QtGui.QLineEdit(self)
    s.setGeometry(QtCore.QRect(15, y, 20, 40))
    s.setObjectName(_fromUtf8(s))
    s_name.show()
    self.edits.append(s)
    y += 40

rawDescription: Dynamically deleting QLineEdit in PyQT4

description: Dynamically deleting QLineEdit in PyQT4


code:
with open('numbers.txt', 'r') as f_input, open('output.txt', 'w') as f_output:
    for number in f_input:
        f_output.write(template.format(number.strip()))

rawDescription: How do i replace a single number (from a set of lines) from a list of numbers?

description: Replace a single number (from a set of lines) from a list of numbers


code:
import os

root = "C:\\test\\"
for path, subdirs, files in os.walk(root):
    if files:
        print(os.path.join(path, min(files)))

rawDescription: Listing a single file in multiple directories with python


code:
from string import punctuation
s = 'I like programming in python. Because it is very fun and simple.'
sorted((word.strip(punctuation) for word in s.split()), key=len)

rawDescription: Python - Printing words by length

description: Python - Printing words by length


code:
replacements = {ord(k): ord(v) for k, v in replacements.iteritems()}
sentence = sentence.translate(replacements)

rawDescription: How to use str.replace() with a dictionary of replacements? Python

description: Use str.replace() with a dictionary of replacements? Python


code:
import threading
build = threading.Thread(target = start_rebuild)
build.start()
progress()
build.join()  # wait for build thread to end

rawDescription: I want to make a function in python that runs every 5 seconds until a variable reaches 100%


code:
import datetime
tow_str = '52300'
datetime.datetime.strptime(tow_str, "%w%H%M")

rawDescription: Python custom datetime(?) format handling


rawDescription: List position changing

description: List position changing


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

fig, ax = plt.subplots()

min_val, max_val, diff = 0., 10., 1.

#imshow portion
N_points = (max_val - min_val) / diff
imshow_data = np.random.rand(N_points, N_points)
ax.imshow(imshow_data, interpolation='nearest')

#text portion
ind_array = np.arange(min_val, max_val, diff)
x, y = np.meshgrid(ind_array, ind_array)

for x_val, y_val in zip(x.flatten(), y.flatten()):
    c = 'x' if (x_val + y_val)%2 else 'o'
    ax.text(x_val, y_val, c, va='center', ha='center')

#set tick marks for grid
ax.set_xticks(np.arange(min_val-diff/2, max_val-diff/2))
ax.set_yticks(np.arange(min_val-diff/2, max_val-diff/2))
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_xlim(min_val-diff/2, max_val-diff/2)
ax.set_ylim(min_val-diff/2, max_val-diff/2)
ax.grid()
plt.show()

rawDescription: Matplotlib imshow/matshow display values on plot


code:
import re

def convert(capital):
    return re.sub(r'([a-z])(.*)$', lambda m: m.group(1).upper() + m.group(2),
                  capital, flags=re.I)

rawDescription: python function capitalize first letter only

description: Python function capitalize first letter only


code:
import skimage.util as ski
import numpy as np
a = np.arange(16).reshape(4,4) # 4x4 array
ski.view_as_blocks(a, (2,2))

rawDescription: Simplify Matrix by Averaging Multiple Cells


rawDescription: Fibonacci numbers integer taken

description: Fibonacci numbers integer taken


code:
from pylab import isnan
boolind = ~isnan(y).any(1)

rawDescription: How to interpolate lines over nans in pylab?

description: Interpolate lines over nans in pylab


code:
q = Queue.Queue()             # word insertion queue
terminate = object()          # sentinel value to tell a thread to terminate

def worker(q):
    while True:
         word = q.get()       # block until next word is available
         if word is terminate:
             break
         insert_word(word)

rawDescription: Concurrent insertions in a Suffix Tree

description: Concurrent insertions in a Suffix Tree


rawDescription: Manipulating browser (window) size using Splinter


code:
seen = set()

[x for x in mylist if x not in seen and not seen.add(x)]
Out[3]: [1, 2, 3, 6, 7, 9, 11]

rawDescription: Python: list filtering using list comprehension


code:
# Put in const.py...
# from http://code.activestate.com/recipes/65207-constants-in-python
class _const:
    class ConstError(TypeError): pass  # base exception class
    class ConstCaseError(ConstError): pass

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError("Can't change const.%s" % name)
        if not name.isupper():
            raise self.ConstCaseError('const name %r is not all uppercase' % name)
        self.__dict__[name] = value

# replace module entry in sys.modules[__name__] with instance of _const
# (and create additional reference to module so it's not deleted --
#  see Stack Overflow question: http://bit.ly/ff94g6)
import sys
_ref, sys.modules[__name__] = sys.modules[__name__], _const()

if __name__ == '__main__':
    import const  # test this module...

    try:
        const.Answer = 42  # not OK, mixed-case attribute name
    except const.ConstCaseError as exc:
        print(exc)
    else:  # test failed - no ConstCaseError exception generated
        raise RuntimeError("Mixed-case const names should't have been allowed!")

    const.ANSWER = 42  # should be OK, all uppercase

    try:
        const.ANSWER = 17  # not OK, attempts to change defined constant
    except const.ConstError as exc:
        print(exc)
    else:  # test failed - no ConstError exception generated
        raise RuntimeError("Shouldn't have been able to change const attribute!")

rawDescription: Can I prevent modifying an object in Python?

description: Prevent modifying an object in Python


code:
format_strings = ['{fw}{lw}', '{fw} {lw}']
[format_string.format(**inputs) for format_string in format_strings]

rawDescription: How to map word combinations in python

description: Map word combinations in python


code:
class Datasource(mapnik.PythonDatasource):
    def __init__(self, mvt):
        super(Datasource, self).__init__()
        self.mvt = mvt

    def features(self, query):
        return mapnik.PythonDatasource.wkb_features(self.mvt)

rawDescription: How to pass a variable to a mapnik datasource class?

description: Pass a variable to a mapnik datasource class


code:
class MyList(list):
    def __getitem__(self, item):
        if isinstance(item, bool):
            raise TypeError('Index can only be an integer got a bool.')
        # in Python 3 use the shorter: super().__getitem__(item)
        return super(MyList, self).__getitem__(item)

rawDescription: Python - Safe Indexing with boolean

description: Python - Safe Indexing with boolean


code:
result = { 'value': False }

def method_1():
    result['value'] = True

rawDescription: Python and closed variables

description: Python and closed variables


code:
def mydoc(func):
    func.__doc__ = 'Here I am.'
    return func

@mydoc
def load_this(dt):
    pass

rawDescription: Python docstring repeated param text

description: Python docstring repeated param text


code:
weight = "%.2f"%(mass * conversion_const)

print('The mass of the load is %s Newtons, which is too heavy'%(weight))
print('The mass of the load is %s Newtons, which is too light'%(weight))
print('The mass of the load is %s Newtons, which is just right'%(weight))
print('The mass of the load is %s Newtons, which is way to heavy'%(weight))

rawDescription: How can I format a number for multiple prints in python3.x?

description: Format a number for multiple prints in python3.x


code:
class Test(object):
    def __init__(self):
        self.inst_var = [1, 2, 3]

rawDescription: Why do attribute references act like this with Python inheritance?


code:
dictionary = { 1: 'one', 2:'two', 3:'three' }
dictionary['ONE'] = dictionary.pop(1)
dictionary
dictionary['ONE'] = dictionary.pop(1)

rawDescription: Change the key value in python dictionary


rawDescription: Find the eigenvalues of a subset of Dataframe in Python


code:
def OnActivated(self, event):
    item = event.GetItem()
    itemObject = self.tree.GetItemData(item).GetData()

rawDescription: wx.Treectrl item look up table

description: Wx.Treectrl item look up table


code: dic['val'], dic['key'] = zip(*sorted(zip(dic['val'], dic['key'])))

rawDescription: how to sort a dictionary val along with the key in python

description: Sort a dictionary val along with the key in python


code:
dx, dy = xx - yy
dx
dy

rawDescription: calculating distance between two numpy arrays

description: Calculating distance between two numpy arrays


code:
import time
def long_running_task(value):
    time.sleep(15)
    return len(value)

rawDescription: How to return data from a CherryPy BackgroundTask running as fast as possible

description: Return data from a CherryPy BackgroundTask running as fast as possible


code:
import csv
import requests
sample = '''\
Y,X,
51.516185371445459,-0.102373799765274,
51.512892732882598,-0.083154776597858,
51.514087813699639,-0.097131850779755,
'''
reader = csv.DictReader(sample.splitlines())
next(reader)
reader = csv.DictReader(sample.splitlines())
coords = ['{X},{Y}'.format(**row) for row in reader]
start, waypoints, end = coords[0], coords[1:-1], coords[-1]
params = {'origin': start,
          'waypoints': '|'.join(waypoints),
          'destination': end,
          'key': 'someapikey'}
params
url = 'https://maps.googleapis.com/maps/api/directions/json'
directions = requests.get(url, params=params).json()
from pprint import pprint
pprint(directions)

rawDescription: Using various input files for fields in Python Requests


code:
def func():
    print("foo")
    return 1

if func():
    print(func())

rawDescription: Python assignment and test of function using elif


rawDescription: Dividing with big(ish) numbers in C (Get a zero, when I know it isn't zero)


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.entry = CustomEntry(self)
        self.button = tk.Button(self, text="Validate", command=self.validate)
        self.entry.pack(side="top", fill="x")
        self.button.pack(side="bottom")

        self.validate() # initialize the border

    def validate(self):
        data = self.entry.get()
        if len(data) == 0:
            self.entry.set_border_color("red")
        else:
            self.entry.set_border_color("blue")

class CustomEntry(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent)
        self.entry = tk.Entry(self, *args, **kwargs)
        self.entry.pack(fill="both", expand=2, padx=2, pady=2)

        self.get = self.entry.get
        self.insert = self.entry.insert

    def set_border_color(self, color):
        self.configure(background=color)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How to change a entry widgets border color in Python Tkinter

description: Change a entry widgets border color in Python Tkinter


code:
import matplotlib.pyplot as plt
import numpy as np
sin, cos = np.sin, np.cos

fig = plt.figure(frameon = False)
fig.set_size_inches(5, 8)
ax = plt.Axes(fig, [0., 0., 1., 1.], )
ax.set_axis_off()
fig.add_axes(ax)

x = np.linspace(-4, 4, 20)
y = np.linspace(-4, 4, 20)
X, Y = np.meshgrid(x, y)
deg = np.arctan(Y**3-3*Y-X)
plt.quiver(X, Y, cos(deg), sin(deg), pivot = 'tail', units = 'dots', color = 'red', )
plt.savefig('/tmp/test.png', dpi = 200)

rawDescription: matplotlib savefig image size with bbox_inches='tight'

description: Matplotlib savefig image size with bbox_inches='tight'


code:
def parse(self, response):
    cat = json.loads(response.body_as_unicode())
    urls = ['http://www.url.com/%s/%s.json' % (c, page)
            for page, c in enumerate(cat)]  # if you want page to start with 1: enumerate(cat, start=1)

    url = urls.pop(0)
    yield Request(url, meta={'urls': urls}, callback=self.parse_cats)

def parse_cats(self, response):
    if response.status == '404':
        # stop crawling
        raise CloseSpider('404 found at %s' % response.url)

    urls = response.meta['urls']
    try:
        url = urls.pop(0)
    except IndexError:
        raise CloseSpider('No more urls to go')

    yield Request(url, meta={'urls': urls}, callback=self.parse_cats)

rawDescription: Scrapy - Break out of loop if response.status == 404


rawDescription: Can I have anonymous function with "static" variables in Python?

description: Have anonymous function with "static" variables in Python


code:
class TextEdit(QtWidgets.QLineEdit):

    def __init__(self, parent=None):
        super(TextEdit, self).__init__(parent)

        self.setPlaceholderText("example : ")
        self._completer = Completer(self)
        self.setCompleter(self._completer)

rawDescription: PyQt - Auto Completer with QLineEdit multiple times


code:
id = self.body['_id']

test = yield db.Result.aggregate(
        [
            { '$match': { '_id': id } },
            { '$group': { '_id' : "$StudentId",
                'Total': {'$max': "$Total"}}
            }
        ]
    )
list = test.get('result')
print(list)

rawDescription: Finding particular value from a list by matching in Python


code:
replacements = {
   'CITY': {
      r'(D.*DO|DOLLARD.*)': 'DOLLARD-DES-ORMEAUX',
      r'I[lL]*[eE]*.*': 'ILLE Perot'}
}

df.replace(replacements, regex=True, inplace=True)

print(df)

rawDescription: Pandas replace multiple values at once

description: Pandas replace multiple values at once


code:
obj = {
  'Name': 'David',
  'Car': {
           'Make': 'Ford',
           'Year': 2008
   }
}
s = "Car.Make"
x = obj
keys = s.split(".")
for key in keys:
    x = x[key]
print(x)

rawDescription: Fetching nested value given dot notation


code:
import datetime
t = datetime.datetime.now()
t - datetime.timedelta(hours=1, minutes=10)

rawDescription: python time offset

description: Python time offset


code:
colour
min_val = min(colour.itervalues())
[k for k, v in colour.iteritems() if v == min_val]

rawDescription: How to return smallest value in dictionary?

description: Return smallest value in dictionary


code: re.split(r'\n(?=TAKE(?: SEL)?\n|(?<!\nTAKE\n)(?<!\nTAKE SEL\n)NAME)', s)

rawDescription: How do you split using re.split as more of a "slice at" function?

description: Split using re.split as more of a "slice at" function


rawDescription: How to print specific things from JSON

description: Print specific things from JSON


rawDescription: Pandas - Remove rows based on combinations of NaN values


rawDescription: What's the best way to automate running MySQL scripts on several databases on a daily basis?


code:
abc = ABC()
abc.someProperty
abc.someFunction()
abc.someProperty

rawDescription: Set the property of a class using decorators on a class method in python


rawDescription: Averaging values in a nested loop in python


code:
def allcumulative():
    for i in range(1000):
        subfunction()

def subfunction():
    for j in range(1000):
        for k in range(1000):
            pass

rawDescription: Python profiling - What are the columns in runsnakerun output?


code: self.Bands = [Band(self.Meta, i) for i in range(3)]

rawDescription: Can an attribute access another attribute?


rawDescription: Pythonic way to generate random uniformly distributed points withing hollow square lamina


code:
z1 = sin(X*Y)
z1 = cos(2*X)
z2 = cos(5*(X+Y))

zm = ma.masked_where( (z2<.5) & (Y>0), z1)

figure()
imshow(z3)
imshow(zm, cmap=cm.gray, alpha=.4, vmin=-2, vmax=2)
show()

rawDescription: matplotlib markers / mask on image pixels

description: Matplotlib markers / mask on image pixels


code:
averages = [sum(items)/len(items)
            for items in zip(*averages_dict.values())]

rawDescription: complicated iteration through a dictionary

description: Complicated iteration through a dictionary


code:
from redis import Redis
from rq import Queue
qfail = Queue("failed", connection=Redis())
qfail.count
qfail.empty()
qfail.count

rawDescription: RQ - Empty & Delete Queues

description: RQ - Empty & Delete Queues


code:
pprint.pprint(get_mp3_info([(("Artist", "Title"), "-")],
              r"(.+-.+)", "Bob-Marley-Roots-Rock-Reggae"))

rawDescription: How to match regex with multiple overlapping patterns?

description: Match regex with multiple overlapping patterns


rawDescription: (python) prepend script dir to a path

description: (python) prepend script dir to a path


code:
from tempfile import NamedTemporaryFile
from shutil import move

with open("test.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    for line in f:
        temp.write("{}\n".format(line.rsplit(None, 1)[0]))

# replace original file with updated content
move(temp.name,"test.txt")

rawDescription: Overwritting characters from a file in Python


code:
from collections import Counter
cn = Counter()

identified_sets = 0
sets = ({randint(1, MAX) for _ in range(MAX)} for i in range(MAX))

for i, st in enumerate(sets):
    cn.update(st)
    if len(st) < 60 or len(st) > 70:
        print("Set {} Set Length: {}, Duplicates discarded: {:.0f}% *****".
              format(i, len(st), (float((MAX - len(st)))/MAX)*100))
        identified_sets += 1
    else:
        print("Set {} Set Length: {}, Duplicates discarded: {:.0f}%".
              format(i, len(st), (float((MAX - len(st)))/MAX)*100))

#print lowest fequency
comm = cn.most_common()
print("key {} : count {}".format(comm[-1][0],comm[-1][1]))

#print highest frequency
print("key {} : count {}".format(comm[0][0], comm[0][1]))

print("Count of identified sets: {}, {:.0f}%".
      format(identified_sets, (float(identified_sets)/MAX)*100))

rawDescription: Looking for unique numbers in a list of sets


rawDescription: How can I use transform to extract a feature based on multiple conditions, using pandas

description: Use transform to extract a feature based on multiple conditions, using pandas


code: num_edges = len(p) - 1 # num_edges = 2

rawDescription: How to find the number of edges bewteen any two nodes using networkx?

description: Find the number of edges bewteen any two nodes using networkx


code:
timeit.timeit('_list', '_list = list', number=10**7)
timeit.timeit('_dict', '_dict = dict', number=10**7)
timeit.timeit('_list()', '_list = list', number=10**7)
timeit.timeit('_dict()', '_dict = dict', number=10**7)

rawDescription: Why is [] faster than list()?

description: Why is [] faster than list()


code:
import pandas as pd
from scipy.spatial.distance import pdist, squareform

df_f_2_norm = pd.read_csv("astrid_data.csv")
g = np.repeat(np.arange(df_f_2_norm.shape[0]//12), 12)

N = 12

N_lim = int(0.5*N*(N-1))
result_index = ['D{}'.format(tag) for tag in range(1,N_lim+1)] # Column labels
two_norm = df_f_2_norm.groupby(g)[["X", "Y", "Z"]].apply(lambda g: pd.Series(pdist(g), index=result_index))

rawDescription: Bizarre issue with pandas' .groupby function, when function applied to rows


code:
dict( (k[0], k[1:]) for k in lst)
# {'kataba': ['V:', '3rd_sg_masc_perf_active'], 'katabat': ['V:', '3rd_sg_fm_perf_active'], 'katabata:': ['V:', '3rd_dual_fm_perf_active'], 'katabu:': ['V:', '3rd_pl_masc_perf_active'], 'kataba:': ['V:', '3rd_dual_masc_perf_active']}

rawDescription: How to Convert Nested List into dictionary in Python where lst[0][0] is the key


code:
ds1 = xr.open_dataset(path_file1, chunks={'year': 10})
ds2 = xr.open_dataset(path_file2, chunks={'year': 10})
(ds1 + ds2).to_netcdf(new_file)

rawDescription: Speeding up reading of very large netcdf file in python


code:
high, avgs = sort_mean("in.txt")
high
avgs

rawDescription: Python: Import from text file to list and sort/average based on multiple columns


code:
yint = range(min(y), math.ceil(max(y))+1)

matplotlib.pyplot.yticks(yint)

rawDescription: Force the Y axis to only use integers

description: Force the Y axis to only use integers


code:
from django.db.models import Sum

ModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name'))

rawDescription: Django SUM Query?

description: Django SUM Query


rawDescription: How to split my strings with re.split?

description: Split my strings with re.split


code:
mat-vec.A # taking advantage of broadcasting
mat-vec.A[:,[0]*3] # explicit broadcasting
mat-vec[:,[0,0,0]] # that also works with csr matrix

rawDescription: Efficiently Subtract Vector from Matrix (Scipy)


code: df

rawDescription: Pandas Apply Function with Multiple **Kwarg Arguments


code:
import re
for c,h,b in np.transpose(gat):
    c = r'$\tt{{{c}}}$'.format(c = re.sub(r'(\d+)',r'_{\1}', c))

rawDescription: How do i annotate with a subscripted text in matplotlib?

description: Annotate with a subscripted text in matplotlib


rawDescription: regex: string with optional parts

description: Regex: string with optional parts


rawDescription: NumPy sum along disjoint indices

description: NumPy sum along disjoint indices


code: df -= median(df, axis=0)

rawDescription: Deducting the median from each column

description: Deducting the median from each column


code:
d = {'key2': [3, 4, 5, 6], 'key1': [1, 2]}
map(lambda a: dict(filter(None, a)), map(None, *[[(k, v) for v in value] for k, value in d.items()]))

rawDescription: Split dictionary of lists into list of dictionaries


rawDescription: Human format date range parsing

description: Human format date range parsing


rawDescription: sort 2-D list python

description: Sort 2-D list python


code:
def subplot(data, fig=None, index=111):
    if fig is None:
        fig = plt.figure()
    ax = fig.add_subplot(index)
    ax.plot(data)

rawDescription: matplotlib: can I create AxesSubplot objects, then add them to a Figure instance?

description: Matplotlib: can I create AxesSubplot objects, then add them to a Figure instance


rawDescription: How to save file automatically after a new window opens in Selenium

description: Save file automatically after a new window opens in Selenium


code: inspect.isroutine( obj )

rawDescription: Is there a common way to check in Python if an object is any function type?


code: data.any(axis=-1) * 255

rawDescription: Numpy fastest 3D to 2D projection

description: Numpy fastest 3D to 2D projection


code:
sorted_x = np.matrix(sorted_sample_values_of_x)
sorted_x = np.transpose(sorted_x).astype(float)
sorted_x
sorted_x[:,1] = sorted_x[:,1]/counts.sum()
sorted_x

rawDescription: saving an ordered pair from a list of numbers using python

description: Saving an ordered pair from a list of numbers using python


code:
def combinations(*seqs):
  if not seqs: return (item for item in ())
  first, rest = seqs[0], seqs[1:]
  if not rest: return ((item,) for item in first)
  return ((item,) + items for item in first for items in combinations(*rest))

rawDescription: What would be a better implementation of all combinations in lexicographic order of a jagged list?


rawDescription: Python: Can one create new variable names from a list of strings?


code:
pool = Pool()
results = pool.map(helper, [obj.method, arg1, arg2])

rawDescription: Parallelize calling of object methods

description: Parallelize calling of object methods


rawDescription: A string that represents encoded characters


code: "Count: %s, Result: %s"%a[0]

rawDescription: How to "unpack" this tuple

description: "unpack" this tuple


code:
bars = [interval_bar_plot.T(line_styles = [None, None],
                            fill_styles = [fill_style.red, None],
                            label=compactlist[n], cluster=(n,len(compactlist)))
        for n,item in enumerate(compactlist)]

rawDescription: For loop inside a function

description: For loop inside a function


code:
import numpy as np
d = np.random.random(10**5)
numbins = 10

bins = np.linspace(d.min(), d.max(), numbins+1)
# This line is not necessary, but without it the smallest bin only has 1 value.
bins = bins[1:]
digitized = bins.searchsorted(d)

bin_means = (np.bincount(digitized, weights=d, minlength=numbins) /
             np.bincount(digitized, minlength=numbins))

rawDescription: Binning data based on one column in 2D array and estimate mean in each bin using cython


code:
import numpy as np
from scipy.ndimage import gaussian_filter
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt

sns.set_style("dark")

img = np.random.normal(size=(100, 100))
img = gaussian_filter(img, 3, 2)

cmap1 = mpl.colors.ListedColormap(sns.color_palette("husl"))

plt.figure()
plt.imshow(img, cmap=cmap1)
plt.colorbar()

rawDescription: seaborn husl or hsl color palette is not working: remains default black and white colors

description: Seaborn husl or hsl color palette is not working: remains default black and white colors


rawDescription: matplotlib: plot hist2d piecewise

description: Matplotlib: plot hist2d piecewise


rawDescription: Generate nested dictionary with list and dict comprehensions


code:
class Pets(EmbeddedDocument):
    name = StringField()

class Person(Document):
    name = StringField()
    address = StringField()
    pets = ListField(EmbeddedDocumentField(Pets))

person = Person()

data = {
    "name": "Hank",
    "address": "Far away",
    "pets": [
        {
            "name": "Scooter"
        }
    ]
}

update_document(person, data)

rawDescription: Update a MongoEngine document using a python dict?


code:
responses  = df.MultipleCheckboxResponse.unique() # find unique responses in each column
u_response = set( [ x for sublist in responses for x in sublist.split('|') ] ) # find total unique responses in dataframe (maps the 2d list responses to a 1d list)
#{'Response1', 'Response2', 'Response3', 'Response4', 'Response7'}

rawDescription: Pandas- Create new columns by splitting cells on | n times


code:
class ReadonlyFoo(object):
    pass

class Foo(Base, ReadonlyFoo):
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))

    readonly_type = ReadonlyFoo

assert type(session.query(Foo).first()) is ReadonlyFoo

rawDescription: SqlAlchemy optimizations for read-only object models


code:
while p >= 0:

    #Here is a bunch of code

    list_of_shapes.append("c")
    list_of_shapes.append(circle) # appends the data for the circles
while p2 >= 0:
    #bunch of code
    list_of_shapes.append("r")
    list_of_shapes.append(rect) # appends the data for the rectangle
while p3 >= 0:
    #code
    list_of_shapes.append("p")
    list_of_shapes.append(poly) # appends the data for the polygon

    return list_of_shapes

rawDescription: How to add strings to a list in Python?

description: Add strings to a list in Python


code:
keys = ['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos']
pairs = zip(keys, entry[1:])
pairs

rawDescription: How to sort a structured list of stock data for later access in Python?

description: Sort a structured list of stock data for later access in Python


code:
def worker():
  while True:
    tick()

    sleep(0.1)

rawDescription: Python - Threading, Timing, or function use?


code:
string = "number %d and float %f" % (1,3.1415)
string = "number %(mynum)d and float %(myfloat)f" % {'mynum':1,'myfloat':3.1415}

rawDescription: What is the % operator in python for?

description: What is the % operator in python for


code:
def gcd_steps(a, b):
    steps = []
    # this is the standard GCD finding algorithm;
    # we simply amend it with "step tracking"
    while b:
        # a, b = b, a % b
        tmp = a
        a = b
        b = tmp % b
        steps.append(a)
    return steps  # normally we'd want to return `a`
                  # but you want the steps not just the result

steps = gcd_steps(125 * 123 * 12314, 25 * 149)

# print the list with `->` between the steps
print(" -> ".join(str(x) for x in steps))

rawDescription: Greatest Common Denominator counter

description: Greatest Common Denominator counter


code:
from pkg_resources import get_distribution, DistributionNotFound
import os.path

try:
    _dist = get_distribution('foobar')
    # Normalize case for Windows systems
    dist_loc = os.path.normcase(_dist.location)
    here = os.path.normcase(__file__)
    if not here.startswith(os.path.join(dist_loc, 'foobar')):
        # not installed, but there is another version that *is*
        raise DistributionNotFound
except DistributionNotFound:
    __version__ = 'Please install this project with setup.py'
else:
    __version__ = _dist.version

rawDescription: What is the correct way to share package version with setup.py and the package?


code: help(res)

rawDescription: In Python, what does getresponse() return?


rawDescription: Other ways to replace single character

description: Other ways to replace single character


rawDescription: PyMongo statistics

description: PyMongo statistics


rawDescription: Is there any way to do HTTP PUT in python


code:
# Assuming that the contact book is formatted `Name` `Number` (split by a space)
name_number = []
for line in contents.split("\n"): # Get each line
    name, number = line.split()
    name_number.append(name + ": " + number) # Append a string of `Name`: `Number` to the list
name_number.sort() # Sort by name

root = Tk()
root.title("Contact Book")
text = Text(root)
text.pack(fill=BOTH)
text.insert("\n".join(name_number))
root.mainloop()

rawDescription: updating tkinter window (Python 3.4)

description: Updating tkinter window (Python 3.4)


code: element

rawDescription: How to identify a specific XML element without ID attributes

description: Identify a specific XML element without ID attributes


rawDescription: Proper way to read/write fortran order array with numpy


code:
class FirstLastNameBackend(object):
    def authenticate(self, username=None, password=None):
        first, last = username.split(' ', 1)
        try:
            user = User.objects.get(first_name=first, last_name=last)
            if user:
                # Check if the password is correct
                # check if the user is active
                # etc., etc.
                return user
        except:
            pass
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except:
            return None

rawDescription: Django, How authenticate user with first name and last name?


code:
[False, False, False, False,  # 1 is in any ofthe tuple range in b?
 False, False, True, False,   # 2 is in any of the tuple range in b?
 False, False, True, False,   # etc. etc....
 False, False, False, False,
 False, False, False, False,
 False, False, False, False,
 False, False, False, False] # searches for each element in a within the range specified by the tuple elements in b

rawDescription: Python - Apply an conditional function (intersection) to every element of a list


code: {'AB303221': 'Acanthopleuribacter pedis     Acanthopleuribacteraceae', 'AJ812213': 'Acaricomes phytoseiuli        Micrococcaceae', 'D50541': 'Abiotrophia defectiva   Aerococcacea'}

rawDescription: Dictionary accession numbers

description: Dictionary accession numbers


code:
for row_idx, row in enumerate(data):
    for col_idx, element in enumerate(row):
        if row_idx >= col_idx:
            continue

rawDescription: Optimizing Very Large Distance Matrix Processing Workflow


code:
for i in f:
    # i holds the line, not the index
    index, page_id = i.strip().split()[:2]
    url="http://graph.facebook.com/"+page_id+"?fields=likes"
    # ...

rawDescription: facebook page info using Graph Api 2.2

description: Facebook page info using Graph Api 2.2


code: return cmp(self.id, other.id)

rawDescription: Function to compare lists: no __cmp__

description: Function to compare lists: no __cmp__


code: my_list[i:end] = [1]*(end-i)

rawDescription: iterating over a sublist in python

description: Iterating over a sublist in python


code: i = __import__('matplotlib.text')

rawDescription: import module from string variable

description: Import module from string variable


code:
lists = []
i = 0
j = 0
limit1 = 2
limit2 = 3
while (i < limit1 and j < limit2):
    lists.append ('First index: %d, Second index: %d' % (i, j))
    j += 1
    lists.append ('First index: %d, Second index: %d' % (i, j))
    i += 1
    j += 1
for i in lists:
    print (i)

rawDescription: Iterate with 2 Indexes Variable in Python


rawDescription: Reading array from config file in python


code:
[
    ['Aloha', 'drink', 'fakla', 'fotoaparat', 'harpuna', 'hrad', 'kalamar', 'kamene'],
    ['Aloha', 'klobuk', 'koral', 'kormidlo', 'kosatka', 'kotva', 'krab', 'lehatko'],
    ['Aloha', 'lietajuciTanier', 'lopta', 'majak', 'meduza', 'melon', 'more', 'morskaPanna'],
    ['Aloha', 'morskyJez', 'morskyKon', 'motyka', 'mraznicka', 'musla', 'nanuk', 'naramok'],
    ['Aloha', 'odtlacokMusle', 'opalovaciKrem', 'osuska', 'palma', 'pelikan', 'pistol', 'plachetnica'],
    ['Aloha', 'plavky', 'plutva', 'ponorka', 'potapacskeOkuliare', 'raketa', 'rukavnik', 'ryba'],
    ['Aloha', 'sandala', 'sarkan', 'slnecneOkuliare', 'slnecnik', 'slnko', 'snehoveGule', 'Splash!'],
    ['Aloha', 'stolicka', 'stopa', 'vedro', 'vlna', 'Wipeout', 'zachranneKoleso', 'zralociaPlutva'],
    ['drink', 'klobuk', 'lietajuciTanier', 'morskyJez', 'odtlacokMusle', 'plavky', 'sandala', 'stolicka'],
    ['drink', 'koral', 'majak', 'mraznicka', 'pelikan', 'rukavnik', 'Splash!', 'zralociaPlutva'],
    ['drink', 'kormidlo', 'melon', 'naramok', 'opalovaciKrem', 'potapacskeOkuliare', 'snehoveGule', 'zachranneKoleso'],
    ['drink', 'kosatka', 'morskaPanna', 'motyka', 'pistol', 'plutva', 'slnko', 'vedro'],
    ['drink', 'kotva', 'lopta', 'nanuk', 'osuska', 'ryba', 'slnecnik', 'stopa'],
    ['drink', 'krab', 'meduza', 'morskyKon', 'plachetnica', 'raketa', 'slnecneOkuliare', 'Wipeout'],
    ['drink', 'lehatko', 'more', 'musla', 'palma', 'ponorka', 'sarkan', 'vlna'],
    ['fakla', 'klobuk', 'morskaPanna', 'nanuk', 'pelikan', 'potapacskeOkuliare', 'slnecneOkuliare', 'vlna'],
    ['fakla', 'koral', 'lopta', 'morskyKon', 'opalovaciKrem', 'plutva', 'sarkan', 'stolicka'],
    ['fakla', 'kormidlo', 'meduza', 'musla', 'pistol', 'ryba', 'sandala', 'zralociaPlutva'],
    ['fakla', 'kosatka', 'more', 'morskyJez', 'osuska', 'raketa', 'Splash!', 'zachranneKoleso'],
    ['fakla', 'kotva', 'lietajuciTanier', 'mraznicka', 'plachetnica', 'ponorka', 'snehoveGule', 'vedro'],
    ['fakla', 'krab', 'majak', 'naramok', 'palma', 'plavky', 'slnko', 'stopa'],
    ['fakla', 'lehatko', 'melon', 'motyka', 'odtlacokMusle', 'rukavnik', 'slnecnik', 'Wipeout'],
    ['fotoaparat', 'klobuk', 'more', 'mraznicka', 'opalovaciKrem', 'ryba', 'slnko', 'Wipeout'],
    ['fotoaparat', 'koral', 'lietajuciTanier', 'naramok', 'pistol', 'raketa', 'slnecnik', 'vlna'],
    ['fotoaparat', 'kormidlo', 'majak', 'motyka', 'osuska', 'ponorka', 'slnecneOkuliare', 'stolicka'],
    ['fotoaparat', 'kosatka', 'melon', 'nanuk', 'plachetnica', 'plavky', 'sarkan', 'zralociaPlutva'],
    ['fotoaparat', 'kotva', 'morskaPanna', 'morskyKon', 'palma', 'rukavnik', 'sandala', 'zachranneKoleso'],
    ['fotoaparat', 'krab', 'lopta', 'musla', 'odtlacokMusle', 'potapacskeOkuliare', 'Splash!', 'vedro'],
    ['fotoaparat', 'lehatko', 'meduza', 'morskyJez', 'pelikan', 'plutva', 'snehoveGule', 'stopa'],
    ['harpuna', 'klobuk', 'melon', 'morskyKon', 'pistol', 'ponorka', 'Splash!', 'stopa'],
    ['harpuna', 'koral', 'morskaPanna', 'musla', 'osuska', 'plavky', 'snehoveGule', 'Wipeout'],
    ['harpuna', 'kormidlo', 'lopta', 'morskyJez', 'plachetnica', 'rukavnik', 'slnko', 'vlna'],
    ['harpuna', 'kosatka', 'meduza', 'mraznicka', 'palma', 'potapacskeOkuliare', 'slnecnik', 'stolicka'],
    ['harpuna', 'kotva', 'more', 'naramok', 'odtlacokMusle', 'plutva', 'slnecneOkuliare', 'zralociaPlutva'],
    ['harpuna', 'krab', 'lietajuciTanier', 'motyka', 'pelikan', 'ryba', 'sarkan', 'zachranneKoleso'],
    ['harpuna', 'lehatko', 'majak', 'nanuk', 'opalovaciKrem', 'raketa', 'sandala', 'vedro'],
    ['hrad', 'klobuk', 'meduza', 'naramok', 'osuska', 'rukavnik', 'sarkan', 'vedro'],
    ['hrad', 'koral', 'more', 'motyka', 'plachetnica', 'potapacskeOkuliare', 'sandala', 'stopa'],
    ['hrad', 'kormidlo', 'lietajuciTanier', 'nanuk', 'palma', 'plutva', 'Splash!', 'Wipeout'],
    ['hrad', 'kosatka', 'majak', 'morskyKon', 'odtlacokMusle', 'ryba', 'snehoveGule', 'vlna'],
    ['hrad', 'kotva', 'melon', 'musla', 'pelikan', 'raketa', 'slnko', 'stolicka'],
    ['hrad', 'krab', 'morskaPanna', 'morskyJez', 'opalovaciKrem', 'ponorka', 'slnecnik', 'zralociaPlutva'],
    ['hrad', 'lehatko', 'lopta', 'mraznicka', 'pistol', 'plavky', 'slnecneOkuliare', 'zachranneKoleso'],
    ['kalamar', 'klobuk', 'majak', 'musla', 'plachetnica', 'plutva', 'slnecnik', 'zachranneKoleso'],
    ['kalamar', 'koral', 'melon', 'morskyJez', 'palma', 'ryba', 'slnecneOkuliare', 'vedro'],
    ['kalamar', 'kormidlo', 'morskaPanna', 'mraznicka', 'odtlacokMusle', 'raketa', 'sarkan', 'stopa'],
    ['kalamar', 'kosatka', 'lopta', 'naramok', 'pelikan', 'ponorka', 'sandala', 'Wipeout'],
    ['kalamar', 'kotva', 'meduza', 'motyka', 'opalovaciKrem', 'plavky', 'Splash!', 'vlna'],
    ['kalamar', 'krab', 'more', 'nanuk', 'pistol', 'rukavnik', 'snehoveGule', 'stolicka'],
    ['kalamar', 'lehatko', 'lietajuciTanier', 'morskyKon', 'osuska', 'potapacskeOkuliare', 'slnko', 'zralociaPlutva'],
    ['kamene', 'klobuk', 'lopta', 'motyka', 'palma', 'raketa', 'snehoveGule', 'zralociaPlutva'],
    ['kamene', 'koral', 'meduza', 'nanuk', 'odtlacokMusle', 'ponorka', 'slnko', 'zachranneKoleso'],
    ['kamene', 'kormidlo', 'more', 'morskyKon', 'pelikan', 'plavky', 'slnecnik', 'vedro'],
    ['kamene', 'kosatka', 'lietajuciTanier', 'musla', 'opalovaciKrem', 'rukavnik', 'slnecneOkuliare', 'stopa'],
    ['kamene', 'kotva', 'majak', 'morskyJez', 'pistol', 'potapacskeOkuliare', 'sarkan', 'Wipeout'],
    ['kamene', 'krab', 'melon', 'mraznicka', 'osuska', 'plutva', 'sandala', 'vlna'],
    ['kamene', 'lehatko', 'morskaPanna', 'naramok', 'plachetnica', 'ryba', 'Splash!', 'stolicka']
]

rawDescription: Python - Spot it! Cards

description: Python - Spot it! Cards


code:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'app_name.path.MyPermissionClass',
    )
}

rawDescription: How to authenticate connected application with key? Django, Python

description: Authenticate connected application with key? Django, Python


code:
('Bob', 'GreenWood')
('Bob', 'Pearson')
('Tom', 'GreenWood')
('Tom', 'Pearson')

rawDescription: How to make unique combinations of the following list of tuples

description: Make unique combinations of the following list of tuples


code:
class DocumentForm(ModelForm):

    def __init__(self, post_data, files_data):
        self.image_main_file = files_data.get('image_main', None)
        return super(DocumentForm, self).__init__(post_data, files_data)

    def save(self, force_insert=False, force_update=False, commit=True):
        instance = super(DocumentForm, self).save(commit=False)
        # do your image magic here, e.g.
        # instance.image_thumbsize_big = field_file_name + slug + key + '.png'

        # you can access your main file with: self.image_main_file
        if commit:
            instance.save()
        return instance

rawDescription: Prevent Django imageField from uploading / saving image


code:
import pandas as pd

df = pd.DataFrame({'Data': ['http://python.org']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Don't convert url-like strings to urls.
writer.book.strings_to_urls = False

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

rawDescription: Export Pandas data frame with text column containg utf-8 text and URLs to Excel


code:
from collections import defaultdict
tup = [('x',1),('y',2),('z',1)]
numbered = defaultdict(list)
for i in tup:
    numbered[i[1]].append(i)

numbered
numbered[1]
numbered[2]

rawDescription: Splitting a list of tuples by 2nd element - python


code: 'def func(): #comment myfunc():'.partition(':')[0]

rawDescription: Making Python code Pythonic

description: Making Python code Pythonic


code:
import re

def python_scanf(my_str, pattern):
    D = ('%d',      '(\d+?)')
    F = ('%f', '(\d+\.\d+?)')
    S = ('%s',       '(.+?)')
    re_pattern = pattern.replace(*D).replace(*F).replace(*S)
    match = re.match(re_pattern, my_str)
    if match:
        return match.groups()
    raise ValueError("String doesn't match pattern")

rawDescription: Parsing from format in Python

description: Parsing from format in Python


code:
import collections

dict_all = collections.defaultdict(list)
for t in bundle.obj.facilities.filter(foo_type = i.foo_type):
    for field in get_translatable_fields(t.foo_type.__class__):
        for translation in t.foo_type.translations.all():
            value = getattr(translation, field)
            dict_all[translation.language_code].append(value)

rawDescription: Differentiate lists according to translations


code:
# You have to set the secret key for sessions to work
# Make sure you keep this secret
app.secret_key = 'something simple for now'

from flask import flash, session

def login_required(function_to_protect):
    @wraps(function_to_protect)
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id')
        if user_id:
            user = database.get(user_id)
            if user:
                # Success!
                return function_to_protect(*args, **kwargs)
            else:
                flash("Session exists, but user does not exist (anymore)")
                return redirect(url_for('login'))
        else:
            flash("Please log in")
            return redirect(url_for('login'))

rawDescription: Python Flask: keeping track of user sessions? How to get Session Cookie ID?


rawDescription: Python - Returning max number in an array. Errors


code: offset = int(tz.utcoffset(dt).total_seconds() / 3600.0)

rawDescription: Get the offset for a specific time and timezone in python


rawDescription: Combining objects in a list. Python

description: Combining objects in a list. Python


rawDescription: Using Agg to find most frequent user per day


code:
import re
string = "abcdefghijklmno(adfa adfds("
m = re.search(r'.{6}(.*?)\(', string)
m.group(1)

rawDescription: Python Extracting a substring of variable length


code: f = open("pup.log", "a+")

rawDescription: Trying to run a python script with crontab every hour, but one section of the python code does not execute


rawDescription: Django: Accessing method on child different child classes through common name


code: vars(type(d))

rawDescription: Get all methods of a class, but not those of superclasses


code:
tmp = pd.DataFrame(np.hstack((df['labels'].values.reshape(-1, 1), df['values'].values.reshape(-1, 1))))
df.loc[:, 'values'] = tmp.groupby(0).transform(lambda x: x/x.sum()).values.reshape(df['values'].shape)

rawDescription: groupby and normalize over two arrays

description: Groupby and normalize over two arrays


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(loc=.5,scale=.2,size=(1000, 4)), columns=['a', 'b', 'c', 'd'])

df1 = pd.DataFrame(df[df.a> 0.5].a)
df2 = pd.DataFrame(df[df.a<= 0.5].a)

dfjoined = df1.join(df2, lsuffix='_gt', rsuffix='_lt', how='outer')

rawDescription: Split single column via a condition creating a new pandas DataFrame with two columns


code:
def transform(line):
    return line.replace('"apple"', '"orange"')

rawDescription: Most Logical Way (in Python) to Edit JSON file on disk


code:
# bp.py
from flask import Blueprint
from flask.ext.autoindex import AutoIndexBlueprint
auto_bp = Blueprint('auto_bp', __name__)
AutoIndexBlueprint(auto_bp, browse_root='/tmp')

rawDescription: Binding Flask AutoIndex to a different URL other than http://localhost?


code:
a = np.arange(50)[::-1]

b = np.random.randint(0,50,1E3)

np.allclose([np.where(a<=x)[0][0] for x in b],np.digitize(b,a))
Out[55]: True

rawDescription: Comparing two numpy arrays of different length


code:
import openpyxl
wb = openpyxl.load_workbook('C:/test.xlsx')
ws = wb.active
i = 0
cell_val = ''
# Finds which row is blank first
while cell_val != '':
    cell_val = ws['A' + i].value
    i += 1
# Modify Sheet, Starting With Row i
wb.save('C:/test.xlsx')

rawDescription: Python- how do I write user input to an Excel file?


code:
s = "abcde"

s[:1] # prefix
s[1:4] # part to be reversed
s[4:] # suffix

rawDescription: Reverse a substring of a given string

description: Reverse a substring of a given string


code:
from pickle import dump

credentials = {
    'John': 1234,
    'James': 4321,
    'Julie': 6789
}

dump(credentials, open("credentials.p", "wb"))

rawDescription: Searching and sorting in text files

description: Searching and sorting in text files


rawDescription: specifying "skip NA" when calculating mean of the column in a data frame created by Pandas

description: Specifying "skip NA" when calculating mean of the column in a data frame created by Pandas


code:
from django.core.cache import cache
from UserDict import DictMixin

class LazyCachedDict(DictMixin):
    def __init__(self, key_prefix):
        self.key_prefix = key_prefix

    def __getitem__(self, name):
        return cache.get('%s:%s' % (self.key_prefix, name))

    def __setitem__(self, name, value):
        return cache.set('%s:%s' % (self.key_prefix, name), value)

    def __delitem__(self, name):
        return cache.delete('%s:%s' % (self.key_prefix, name))

    def has_key(self, name):
        return cache.has_key(name)

    def keys():
        ## Just fill the gap, as the cache object doesn't provide
        ## a method to list cache keys..
        return []

rawDescription: Loading dictionary object causing memory spike


code:
# binary search for list with desending values
def binary_search(li, targetValue):
    low, high = 0, len(li) - 1  # min & max index
    while low <= high:          # loop til high & low switch
        mid = (high + low) / 2  # midpoint (rounds down)
        if li[mid] > targetValue: low = mid + 1     # confine to upper half
        elif li[mid] < targetValue: high = mid - 1  # confine to lower half
        elif li[mid] == targetValue: return mid     # found it!
    return None  # nothing to return (low/high switched, so it wasn't found)

rawDescription: Not printing output ? python

description: Not printing output ? python


code:
def outer():
    string = ""
    def inner():
        nonlocal string
        string = "String was changed by a nested function!"
    inner()
    return string

rawDescription: Python overwriting variables in nested functions


code:
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import io

temp=u"""tweetcricscore,51,high active
tweetcricscore,46,event based
tweetcricscore,12,event based
tweetcricscore,46,event based
tweetcricscore,1,viewers
tweetcricscore,178,viewers
tweetcricscore,46,situational
tweetcricscore,23,situational
tweetcricscore,1,situational
tweetcricscore,8,situational
tweetcricscore,56,situational"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), names=['keyword','freq','class'])

rawDescription: Pandas Seaborn Swarmplot doesn't plot

description: Pandas Seaborn Swarmplot doesn't plot


rawDescription: Invoking top-level function by name in Python


rawDescription: Product code looks like abcd2343, what to split by letters and numbers


code:
class profilePictures(models.Model):
    userName = models.CharField(max_length=30, primary_key=True)
    picture = models.ImageField(upload_to='ProfilePictures', blank = True)

rawDescription: Django Python During Restart Data Loss

description: Django Python During Restart Data Loss


code:
def id_generator(dict):
      for k, v in dict.items():
            if k == "id":
                 yield v
            elif isinstance(v, dict):
                 for id_val in id_generator(v):
                       yield id_val

rawDescription: recursive iteration through nested json for specific key in python

description: Recursive iteration through nested json for specific key in python


code:
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

rawDescription: What is a "slug" in Django?

description: What is a "slug" in Django


code:
filtered = [ myList[i] for i in range(len(myList))
            if set(myList[i]) not in [ frozenset(x) for x in myList ][:i] ]

rawDescription: Removing Python List Items that Contain 2 of the Same Elements


code:
"Black",0
"Brown, J",0

rawDescription: A single CSV column includes commas - Python


code: list(map(print, iterable))

rawDescription: Python Java forEach equivalent

description: Python Java forEach equivalent


code:
for l in cbar.ax.yaxis.get_ticklabels():
    l.set_weight("bold")
    l.set_fontsize(16)

rawDescription: matplotlib colorbar tick label formatting

description: Matplotlib colorbar tick label formatting


rawDescription: Regular Expression with python

description: Regular Expression with python


code: ax.plot(x, data2, ...)

rawDescription: Matplotlib: move graph to the right

description: Matplotlib: move graph to the right


code:
from traits.api import HasTraits, Instance, Str
from traitsui.api import View, Item, CheckListEditor

class Bclass(object):
    options = {'one': 1, 'two': 2}

class Aclass(HasTraits):
    bclass = Instance(Bclass)
    abc = Str

    def default_traits_view(self):
        options = self.bclass.options.keys()
        view = View(
            Item(name='abc', editor=CheckListEditor(values=options)),
        )
        return view

rawDescription: enthought traits UI, add values dynamically to 'values' trait of CheckListEditor

description: Enthought traits UI, add values dynamically to 'values' trait of CheckListEditor


code: y

rawDescription: How to convert JavaScript dictionary into Python syntax

description: Convert JavaScript dictionary into Python syntax


code:
import ctypes
libc = ctypes.CDLL('libc.dylib')
def zomg():
    for i in xrange(5):
        libc.printf('libc stdout: %d\n', i)
        time.sleep(1)

redirected_printed_output(zomg)

rawDescription: Capture c++ shared library log entries with ctypes


code:
letters = "asdfHRbySFss"
uppers = [l for l in letters if l.isupper()]

rawDescription: how can i check if a letter in a string is capialized using python?

description: Check if a letter in a string is capialized using python


code:
split_list = lambda lst: (lst[0], lst[1:])
head, rest = split_list(my_func())

rawDescription: Pattern matching of lists in Python

description: Pattern matching of lists in Python


code: columns.loc[mask, [0,1]] = columns.loc[mask, [1,0]].values

rawDescription: Pandas read multiindexed csv with blanks


code:
'special'
'a'
'b'
'c'

rawDescription: Special use for __iter__ and __next__

description: Special use for __iter__ and __next__