code:
def __getattr__(self, x):
    r = getattr(self.int, x)
    if callable(r):
        def f(*args, **kwargs):
            if args and isinstance(args[0], u32):
                args = (args[0].int, ) + args[1:]
            ret = r(*args, **kwargs)
            if ret is NotImplemented:
                return ret
            if x in ['__str__', '__repr__', '__cmp__', '__index__']:
                return ret
            ret %= MODULO
            return u32(ret)
        return f
    return r

rawDescription: How to implement C-like unsigned int 32 in Python with no external dependencies?

description: Implement C-like unsigned int 32 in Python with no external dependencies


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

fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(
    patches.Rectangle(
        (2, 3),   # (x,y)
        3,          # width
        4,          # height
    )
)
ax1.axis([0, 10, 0, 10])
fig1.savefig('rect1.png', dpi=90, bbox_inches='tight')

rawDescription: Matplotlib - draw rectangle outside of unit square


code:
data = [1,10,100]
itertools.chain(*((x,log10(x)) for x in data))

rawDescription: creating a list with 2 entries for each element of an iterator

description: Creating a list with 2 entries for each element of an iterator


code:
if item not in someSet:
    someSet.add(item)
    doStuff()
else:
    doOtherStuff()

rawDescription: Pythonic way to add to a set and care about if it worked?


code:
foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
    if obj == foo:
        if index > 0:
            previous = objects[index - 1]
        if index < (l - 1):
            next_ = objects[index + 1]

rawDescription: Python - Previous and next values inside a loop


code:
import xml.dom.minidom

xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()

rawDescription: Pretty printing XML in Python

description: Pretty printing XML in Python


code:
mask_first_nonnull = dlret.notnull() & (dlret.notnull().cumsum()==1)
ret[mask_first_nonnull]=dlret[mask_first_nonnull]

rawDescription: How to change values in a dataframe efficiently

description: Change values in a dataframe efficiently


code:
animals = (Dog, Cat, Pig)
the_chosen_one = random.choice(animals)
new_animal = the_chosen_one()

rawDescription: Selecting random class in Python

description: Selecting random class in Python


code:
import requests

url = "https://sample.com"
auth = "sampleauthtoken"

headers = {
    'authorization': "Bearer " + auth,  # -> "Bearer sampleauthtoken"
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, headers=headers)

print(response.text)

rawDescription: variable in python dictionary for http header construction

description: Variable in python dictionary for http header construction


code:
class objectA(object):
    def __init__(self,somevar):
        ...

    @property
    def summed_array(self):
        return sum(b.array for b in self.list_of_Bs)

rawDescription: Best way to set sum over other objects properties

description: Set sum over other objects properties


code:
jinja2.FileSystemLoader(os.path.join(self.root_path,
                                     self.template_folder))

rawDescription: Flask - Jinja environment magic in a Blueprint


code:
import matplotlib.pyplot as plt
import matplotlib.dates as mdate

import numpy as np

import datetime as dt

# Generate some random data.
N = 40
now = 1398432160
raw = np.array([now + i*1000 for i in range(N)])
vals = np.sin(np.linspace(0,10,N))

# Convert to the correct format for matplotlib.
# mdate.epoch2num converts epoch timestamps to the right format for matplotlib
secs = mdate.epoch2num(raw)

fig, ax = plt.subplots()

# Plot the date using plot_date rather than plot
ax.plot_date(secs, vals)

# Choose your xtick format string
date_fmt = '%d-%m-%y %H:%M:%S'

# Use a DateFormatter to set the data to the correct format.
date_formatter = mdate.DateFormatter(date_fmt)
ax.xaxis.set_major_formatter(date_formatter)

# Sets the tick labels diagonal so they fit easier.
fig.autofmt_xdate()

plt.show()

rawDescription: Plotting chart with epoch time x axis using matplotlib


code:
import glob, os, shutil

#root directory
start_dir = 'C:\\'

def copy_to_remote(local_folders, remote_path):
    if os.path.exists(remote_path):
        for source in local_folders:
            # source currently has start_dir at start. Strip it and add remote path
            dest = os.path.join(remote_path, source.lstrip(start_dir))
            try:
                shutil.copytree(source, dest)
                print ('Congratulations!  Copy was successfully completed!')
            except FileExistsError as fe_err:
                print(fe_err)
            except PermissionError as pe_err:
                print(pe_err)
    else:
        print('{} - does not exist'.format(remote_path))

# Find all directories that start start_dir\Test_ and have subdirectory Pass
dir_list = glob.glob(os.path.join(start_dir, 'Test_*\\Pass'))
if dir_list:
    copy_to_remote(dir_list, '\\\\Share\\' )

rawDescription: How do I iteratively copy logs from the local drive to a network share?

description: Iteratively copy logs from the local drive to a network share


code:
amount, unit = input('Enter amount with units: ').split()[:2]
converted_data = int(amount) * {'in': 2.54, 'cm': 0.39}[unit]

rawDescription: Unit conversion using Python

description: Unit conversion using Python


code: numbers = [ int(x) for x in numbers ]

rawDescription: Call int() function on every list element in Python


code:
def show_cheapest_item(self):
    """ (ShoppingCart) -> int
    Return the cheapest item in the cart, or -1 if no items are in the cart
    """
    if len(self.cart) == 0:
        return -1
    cheapest_item = self.cart[0]
    for item in self.cart[1:]:
        if item.price < cheapest_item.price:
            cheapest_item = item
    return cheapest_item

rawDescription: Finding the lowest value within an instance variable


code:
for e in soup.find_all(text='123'):
    print(e.parent['class'])

rawDescription: Find attribute name by value in BeautifulSoup (not reverse)


code:
b = Button(...)
b.image = c_black
print(b.image.cget('file'))

rawDescription: cget('image') method returning pyimage1 instead of the image name

description: Cget('image') method returning pyimage1 instead of the image name


code:
import matplotlib
matplotlib.rcParams

rawDescription: Pylab - what font is currently being used?


code:
while True:
    line1 = f.readline()
    line2 = f.readline()
    if not line2: break  # EOF
    ...

rawDescription: How do I read two lines from a file at a time using python

description: Read two lines from a file at a time using python


rawDescription: How to set event handler functions in kivy templates?

description: Set event handler functions in kivy templates


code:
secret_word = "python"
correct_word = "yo"
count = 0

while count < len(secret_word):
    print(secret_word[count] if secret_word[count] in correct_word else '_', end=" ")
    count += 1

rawDescription: using a while loop instead of for loop

description: Using a while loop instead of for loop


code:
stop_event = threading.Event()
...
stop_event.wait(1.)
if stop_event.isSet():
    return
...

rawDescription: Equivalent of setInterval in python

description: Equivalent of setInterval in python


code:
def keyPressEvent(self, event):
        if event.key() in [16777235, 16777237, 16777234, 16777236, 16777220]: # Up, down, left, right, return.
            event.ignore()
        else:
            super(MyTextEdit, self).keyPressEvent(event)

rawDescription: PyQt / PySide keyPressEvent default behaviour


code:
mystring = "a1234f"
data = list(mystring)

rawDescription: Reading bytes from Python String

description: Reading bytes from Python String


code:
a = [1,2,3,4,5]
b = [1,4,9,16,25]
d = open("plotly.py","w")
d.write("from pylab import *\nx = %s\ny=%s\nplot(x,y)\nshow()"%(a,b))
d.close()

rawDescription: Open/Save as matplotlib own format?

description: Open/Save as matplotlib own format


rawDescription: How do you do an os.path.join with an array in python?

description: Do an os.path.join with an array in python


code:
db.data.aggregate([{
  "$sort": {
    "_id": 1
  }
}, {
  "$group": {
    "_id": "$key",
    "first": {
      "$first": "$$ROOT"
    }
  }
}, {
  "$project": {
    "_id": 0,
    "id":"$first.id",
    "key":"$first.key",
    "name":"$first.name",
    "country":"$first.country"
  }
}])

rawDescription: Mongo Distinct Query with full row object


code: query.filter("strftime('%w', access_date) = :dow").params(dow=0).all()

rawDescription: Way to query database with SQLAlchemy where a date is a particular day of the week?


code: unique_together = (('content_type', 'object_id', 'key', 'user', 'ip_address'))

rawDescription: How do i test django ratings in my application?

description: Test django ratings in my application


code:
def decorator_noarg(f):
    def wrapper(*args, **kwargs):
        print("Inside decorator-function, WITHOUT arg.")
        return f(*args, **kwargs)
    return wrapper

def decorator_witharg(dec_arg):
    def real_decorator(f):
        def wrapper(*args, **kwargs):
            print("Inside decorator-function, WITH arg: %s" % (dec_arg))
            return f(*args, **kwargs)
        return wrapper
    return real_decorator

class decoratorclass_noarg(object):
    f = None
    def __init__(self, f):
        def host_wrapper(*arg, **kwargs):
            print("Inside decorator-class, WITHOUT arg.")

            # We lose the original instance of the object.
            return f(test_class(), *arg, **kwargs)

        self.f = host_wrapper

    def __call__(self, *args, **kargs):
        return self.f(*args, **kargs)

class decoratorclass_witharg(object):
    f = None
    def __init__(self, dec_arg):
        def decorator(host_method):
            def host_wrapper(host_obj, *arg, **kwargs):
                print("Inside decorator-class, WITH arg: %s" % (dec_arg))
                return host_method(host_obj, *arg, **kwargs)
            return host_wrapper
        self.f = decorator

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

class decorator_on_function_noarg(object):
    f = None

    def __init__(self, f):
        self.f = f
        pass

    def __call__(self):
        print("Inside decorator-on-function class, without arg.")
        return self.f()

class decorator_on_function_witharg(object):
    f = None

    def __init__(self, dec_arg):
        def decorator(host_method):
            def host_wrapper(*arg, **kwargs):
                print("Inside decorator-on-function class, with arg: %s" % (dec_arg))
                return host_method(*arg, **kwargs)
            return host_wrapper
        self.f = decorator

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

def decorator_function_on_method_noarg(f):
    print("Inside decorator-function on method, without arg.")
    return f

def decorator_function_on_method_witharg(dec_arg):
    def wrapper(f):
        print("Inside decorator-function on method, with arg: %s" % (dec_arg))
        return f

# Testing calls.

class test_class(object):
    #@decorator_witharg(44)
    #@decorator_noarg
    #@decoratorclass_witharg(1)
    #@decoratorclass_noarg
    #@decorator_function_on_method_noarg
    #@decorator_function_on_method_witharg(33)
    def test_func(self, arg1, arg2):
        print("Inside: %s, %s" % (arg1, arg2))
        return 123

#@decorator_on_function_noarg
#@decorator_on_function_witharg(22)
def test_func():
    print("Inside test_func.")

#test_class().test_func(33, 44)
#test_func()

rawDescription: Variations of function decorators in Python


rawDescription: Select rows from a DataFrame based on multiple values in a column in pandas


code:
data1 = [
    {'Id': 1},
    {'Id': 2}
]
data2 = [
    {'Id': 1, 'score': 100, 'testdata': 333},
    {'Id': 2, 'score': 200, 'testdata': 555},
    {'Id': 3, 'score': 300, 'testdata': 444}
]

def get_score(list_of_dict, id_value):

    for dict_ in list_of_dict:
        if dict_["Id"] == id_value:
            return {"score": dict_["score"]}

res = data1.copy()

for dict_ in res:
    dict_.update(get_score(data2, dict_["Id"]))

print(res)
# [{'score': 100, 'Id': 1}, {'score': 200, 'Id': 2}]

rawDescription: Merge two list of dictionaries based on specific key


code:
d = 90
distance = d * 0.014472
#1 mile = 0.014472 degrees

r1 = -0.1198244
r2 = 51.5112139

# load long[1], lat[0] into shapely
center_point = Point(r1, r2)
# 'POINT (-0.1198244000000000 51.5112138999999871)'

wkb_element = from_shape(center_point)

users = DBSession.query(User).\
    filter(func.ST_DFullyWithin(User.location,  wkb_element, distance)).all()

rawDescription: Geoalchemy2 query all users within X meteres


code:
class Main(object):

    def run(self, alist, thread_id):
        while alist:
            t = alist.pop(0)
            print(thread_id, t)
            sleep(1)

    def method_a(self):
        print('method_a start')
        tlist = list(range(10))
        ps = [Thread(target=self.run, args=(tlist, i)) for i in range(4)]
        for p in ps:
            p.start()
        for p in ps:
            p.join()
        print('method_a finish')

rawDescription: Should I put a threading class in or out of a class method


code:
def get_file_tree(self, path):
    """
    return a natural sorted file tree and the index of your original file

    :param path:
    :return:
    """
    if not os.path.exists(path):
        return None
    filename = os.path.basename(path)
    basepath = os.path.abspath(os.path.dirname(path))
    for _ in xrange(self.depth):
        path = os.path.abspath(os.path.join(basepath, os.pardir))

    # list all files
    configfiles = [os.path.join(dirpath, f)
                   for dirpath, dirnames, files in os.walk(path)
                   for f in fnmatch.filter(files, '*')]
    # use natural sort for the tree
    configfiles = self.natural_sort(configfiles)
    original_path = os.path.join(basepath, filename)
    original_index = configfiles.index(original_path)
    return configfiles, original_index

def backward(self, path="", ghost=False):
    """
    get the next file of our current or defined path

    :param path:
    :param ghost:
    :return:
    """
    if path == "":
        path = self.image_path
    path = os.path.abspath(path)

    configfiles, original_index = self.get_file_tree(path)
    # if file was non existant or the index was 0 return None
    if original_index is None or original_index == 0:
        return None
    new_path = configfiles[original_index - 1]
    if new_path.count("\\") > path.count("\\"):
        return None
    if not ghost:
        self.image_path = new_path
    return new_path

def forward(self, path="", ghost=False):
    """
    get the next file of our current or defined path

    :param path:
    :param ghost:
    :return:
    """
    if path == "":
        path = self.image_path
    path = os.path.abspath(path)

    configfiles, original_index = self.get_file_tree(path)
    # if file was non existant or was the last file, return None
    if original_index is None or len(configfiles) <= original_index + 1:
        return None
    new_path = configfiles[original_index + 1]
    if not ghost:
        self.image_path = new_path
    return new_path

rawDescription: Python find next file by natural sort

description: Python find next file by natural sort


code:
import PyQt4.QtGui as gui
import PyQt4.QtCore as core

dat = { 'A':
            { '1':
                {'1.1': ['1.1.1', '1.1.2'],
                 '1.2': ['1.2.1', '1.2.2']
                 },
             '2':
                {'2.1': ['2.1.1','2.1.2']}
            }
     }

def add(p,ch):
    if isinstance(ch,dict):
        for k,v in ch.iteritems():
            item = gui.QTreeWidgetItem(p)
            item.setText(0, k)
            item.setCheckState(0,core.Qt.Unchecked)
            item.setFlags(core.Qt.ItemIsUserCheckable | core.Qt.ItemIsEnabled)
            add(item,v)
            #p.addChild(item)
    else:
        for txt in ch:
            item = gui.QTreeWidgetItem(p)
            item.setText(0, txt)
            item.setCheckState(0,core.Qt.Unchecked)
            item.setFlags(core.Qt.ItemIsUserCheckable | core.Qt.ItemIsEnabled)
            #p.addChild(item)

app = gui.QApplication([])
tw = gui.QTreeWidget()

add(tw,dat)

tw.show()

app.exec_()

rawDescription: How to create a treeview of checkboxes?

description: Create a treeview of checkboxes


code:
from tkinter import *
from tkinter.ttk import *

class MainPanel(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)

        # first setup two StringVars. They will be linked to a Label and an Entry widget.
        # we should keep a reference to these two StringVars, because we will call their method
        # to read/write widget content.
        self.msg2show = StringVar()
        self.text_input = StringVar()

        # this is a fixed Label widget whose display will no change.
        # No need to keep a reference(meaning to assign it to a variable).
        Label(self, text='If you click the button, the text in the entry widget will show above.').pack()

        # this is a variable Label widget whose display is decided by the linked variable `self.msg2show`
        Label(self, textvariable=self.msg2show).pack()

        # this is a variable Entry widget whose content is saved into `self.text_input`
        Entry(self, textvariable=self.text_input).pack()

        # this is the button who will trigger `self.set_msg` on click.
        Button(self, text='Set message', command=self.set_msg).pack()

    def set_msg(self):
        # get out what in the Entry widget through calling the `get()` method of `self.text_input`
        text_in_entry_widget = self.text_input.get()
        # and print it into console, for checking.
        print(text_in_entry_widget)

        # then we set that text into self.msg2show, and since it is linked with the variable Label widget
        # the display of that Label will then be set to text_in_entry_widget.
        self.msg2show.set(text_in_entry_widget)

        # You can see here I print the `text_in_entry_widget` to console as well as to a Label.
        # You can do it in the same way.

if __name__ == '__main__':
    root = Tk()
    MainPanel(root).pack()
    root.mainloop()

rawDescription: Py 3: tkinter frames, coding inside or outside of frame classes


code:
def quicksort(a, i, j):
    if j <= i: return

    swap(a, i, j)
    p = partition(a, i, j)

    quicksort(a, i, p-1)
    quicksort(a, p+1, j)

rawDescription: implementing quicksort and getting a bug I don't understand

description: Implementing quicksort and getting a bug I don't understand


code:
import copy_reg
import types

def reduce_method(m):
    return (getattr, (m.__self__, m.__func__.__name__))

copy_reg.pickle(types.MethodType, reduce_method)

rawDescription: Overcoming Python's limitations regarding instance methods


code: writer.writerow([key] + value)

rawDescription: Writing key:value pairs to a tab-delimited file with variable #s of values


code:
from http.server import HTTPServer, SimpleHTTPRequestHandler

class HeaderDumper(SimpleHTTPRequestHandler):
    def do_GET(self):
        try:
            return super().do_GET()
        finally:
            print(self.headers)

server = HTTPServer(("", 8123), HeaderDumper)
server.serve_forever()

rawDescription: How to check Proxy headers to check anonymity?

description: Check Proxy headers to check anonymity


code:
obs
from scipy.stats.contingency import expected_freq
expected_freq(obs)

rawDescription: Get the expected array with SciPy's Fisher exact test?


code:
class CollectionMember(models.Model):
    """
    Allows collections to be assigned to multiple external
    objects using a generic foreign key
    """
    collection = models.ForeignKey(Collection)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

rawDescription: Using GenericTabularInline in the Django Admin to find existing collections


rawDescription: return a sliced string to the orginal string

description: Return a sliced string to the orginal string


code:
A = []
with open("test2.xls") as w:
    w.next()  # skip over header row
    for row in w:
        (date, time, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t,
         u, LZA, SZA, LAM) = row.split("\t")  # split columns into fields

        A.append([(float(a) + float(b) + float(c))/3,
         (float(d) + float(e) + float(f))/3,
         (float(g) + float(h) + float(i))/3,
         (float(j) + float(k) + float(l))/3,
         (float(m) + float(n) + float(o))/3,
         (float(p) + float(q) + float(r))/3,
         (float(s) + float(t) + float(u))/3])

rawDescription: separating rows of output in python by commas and staying in float

description: Separating rows of output in python by commas and staying in float


code:
for t in range(tmax):
    for i in range(t):
        nodeExecute(gx[i])

rawDescription: Stepping through a sequence of grouped logic gates


code:
import subprocess
subprocess.call("powercfg -change -monitor-timeout-ac 666")

rawDescription: Use Python to Edit Windows 8 Power Options


code:
child_processes = []
for work, filename in worklist:
    with io.open(filename, mode='wb') as out:
        p = subprocess.Popen(work, stdout=out, stderr=out)
        child_processes.append(p)    # start this one, and immediately return to start another

# now you can join them together
for cp in child_processes:
    p.wait()                         # this will block on each child process until it exits

rawDescription: run subprocesses in parallel

description: Run subprocesses in parallel


code:
def fib(n):
    return n if n in (0, 1) else globals()['fib'](n-1) + globals()['fib'](n-2)

rawDescription: Why does this memoizer work on recursive functions?


code:
import operator, logging
import numpy as np
def ribs(loadings):
  '''
  Convert a list of n loading matrices [A_{fi}, B_{fj}, C_{fk}, ...] into ribs
  [A_{fi11...}, B_{f1j1...}, C_{f11k...}, ...]. These ribs can be multiplied
  with numpy broadcasting to fill a tensor with data.
  '''
  loadings = [np.atleast_2d(l) for l in loadings]
  nfactors = loadings[0].shape[0]
  assert np.alltrue([l.ndim == 2 and l.shape[0] == nfactors for l in loadings])
  ribs = []
  for mi in range(len(loadings)):
    shape = [nfactors] + [-1 if fi == mi else 1 for fi in range(len(loadings))]
    ribs.append(loadings[mi].reshape(shape))
  return ribs

def para_compose(ribs):
  return np.sum(reduce(operator.mul, ribs), axis=0)

def parafac_base(x, nfactors, max_iter):
  '''
  PARAFAC is a multi-way tensor decomposition method. Given a tensor X, and a
  number of factors nfactors, PARAFAC decomposes the X in n factors for each
  dimension in X using alternating least squares:

  X_{ijk} = \sum_{f} a_{fi} b_{fj} c_{fk} + e_{ijk}

  PARAFAC can be seen as a generalization of PCA to higher order arrays [1].
  Return a ([a, b, c, ...], mse)

  [1] Rasmus Bro. PARAFAC. Tutorial and applications. Chemometrics and
  Intelligent Laboratory Systems, 38(2):149-171, 1997.
  '''
  log = logging.getLogger('psychic.parafac')
  loadings = [np.random.rand(nfactors, n) for n in x.shape]

  last_mse = np.inf
  for i in range(max_iter):
    # 1) forward (predict x)
    xhat = para_compose(ribs(loadings))

    # 2) stopping?
    mse = np.mean((xhat - x) ** 2)
    if last_mse - mse < 1e-10 or mse < 1e-20:
      break
    last_mse = mse

    for mode in range(len(loadings)):
      log.debug('iter: %d, dir: %d' % (i, mode))
      # a) Re-compose using other factors
      Z = ribs([l for li, l in enumerate(loadings) if li != mode])
      Z = reduce(operator.mul, Z)

      # b) Isolate mode
      Z = Z.reshape(nfactors, -1).T # Z = [long x fact]
      Y = np.rollaxis(x, mode)
      Y = Y.reshape(Y.shape[0], -1).T # Y = [mode x long]

      # c) least squares estimation: x = np.lstsq(Z, Y) -> Z x = Y
      new_fact, _, _, _ = np.linalg.lstsq(Z, Y)
      loadings[mode] = new_fact
  if not i < max_iter - 1:
    log.warning('parafac did not converge in %d iterations (mse=%.2g)' %
      (max_iter, mse))
  return loadings, mse

rawDescription: How to use scikit-tensor in python

description: Use scikit-tensor in python


code:
with file('patch1.bin', 'rb') as fh:
    patch1 = fh.read()

with file('patch2.bin', 'rb') as fh:
    patch2 = fh.read()

with file('file.bin', 'r+b') as fh:
    # apply patch1
    fh.seek(0xc0010)
    fh.write(patch1)
    fh.seek(0x7c0010)
    fh.write(patch1)
    # apply patch2
    fh.seek(0x040000)
    fh.write(patch2)

rawDescription: Modifying binary file with Python

description: Modifying binary file with Python


code:
from sympy import init_printing, Symbol, expand
init_printing()
a = Symbol('a')
b = Symbol('b')
e = (a + b)**5
e
e.expand()

rawDescription: Generate formula for (a+b)^2 in python

description: Generate formula for (a+b)^2 in python


code:
import os
directory = "/Users/user.name/foldername"
if not os.path.exists(directory): os.makedirs(directory)
os.system("mount_smbfs //user.name:password@server/servershare ~/foldername")

rawDescription: Mount Windows smb shares on a Mac using Python


code:
df
pd.melt(df, id_vars=['county','region'], var_name='year', value_name='sum')

rawDescription: Pandas dataframe: turn date in column into value in row


code:
import sys, clr
sys.path.append(r'C:\Program Files (x86)\WPF Toolkit\v3.5.50211.1')
clr.AddReference("WPFToolkit")

rawDescription: How do I reference the WPF Toolkit in Visual Studio 2010?

description: Reference the WPF Toolkit in Visual Studio 2010


code:
@receiver(some_signal)
def do_it_all(sender, **kwargs):
    do_something_for_table_one(sender, **kwargs)
    do_something_for_table_two(sender, **kwargs)
    do_something_for_table_three(sender, **kwargs)

rawDescription: Django receivers best practice

description: Django receivers best practice


code:
def foo():
    x = 5
    def bar():
        return x
    return bar

bar = foo()
import dis
dis.dis(bar)

rawDescription: Python __closure__ variables and cells

description: Python __closure__ variables and cells


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

fig, ax = plt.subplots()
ax.scatter(x1,y1,c='b',edgecolors='none')
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.patch.set_facecolor("none")
ax.patch.set_edgecolor("none")
fig.canvas.draw()

w, h = fig.canvas.get_width_height()
img = np.frombuffer(fig.canvas.buffer_rgba(), np.uint8).reshape(h, w, -1).copy()

ax.clear()
ax.scatter(x2,y2,c='r',edgecolors='none')
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.patch.set_facecolor("none")
ax.patch.set_edgecolor("none")
fig.canvas.draw()

img2 = np.frombuffer(fig.canvas.buffer_rgba(), np.uint8).reshape(h, w, -1).copy()

img[img[:, :, -1] == 0] = 0
img2[img2[:, :, -1] == 0] = 0

fig.clf()

plt.imshow(np.maximum(img, img2))
plt.subplots_adjust(0, 0, 1, 1)
plt.axis("off")
plt.show()

rawDescription: Is it possible to do additive blending with matplotlib?


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

x = np.arange(4)
y2 = np.array([23, 32, 24, 28])
y1 = 4.2 * y2

y2max = np.max(y2) * 1.1

fig = plt.figure(1, figsize=(6,6))

ax = fig.add_subplot(111)
ax.bar(x, y2)
ax.set_ylabel('Consumption in $m^3$')
ax2 = ax.twinx()

ax2.set_ylabel('Consumption in EUR')

ax.set_ylim(ymax=y2max)
ax2.set_ylim(ymax=4.2*y2max)

rawDescription: Matplotlib.pyplot: How to set up a second y-axis for an existing plot


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

rawDescription: prevent matplotlib from rebasing my axes at zero

description: Prevent matplotlib from rebasing my axes at zero


code:
element = driver.find_element_by_id("sbi_file_upload")
element.send_keys('/Path/to/file.jpeg')
driver.find_element_by_css_selector('div#sbi_sb_ipt span[name=go]').click()

rawDescription: Selenium file upload leaves file selector window open (OS/X and Python)


code: soup = BS(response.text)

rawDescription: Correct Library Usage: requests w/ bs4.BeautifulSoup?


code:
var = "/some/file/path/"
pipe = subprocess.Popen(["perl", "./uireplace.pl", var], stdin=subprocess.PIPE)
pipe.stdin.write(var)
pipe.stdin.close()

rawDescription: Call Perl script from Python

description: Call Perl script from Python


rawDescription: Finding the last item in a list

description: Finding the last item in a list


rawDescription: Formating numpy float values

description: Formating numpy float values


code:
# if there are more columns than this, you'll see a summarized view
pd.options.display.max_columns = 40 # default is 20

rawDescription: Join on dataframe without a key

description: Join on dataframe without a key


code:
import csv

with open('TAB.csv','rb') as input_file:
    reader = csv.reader(input_file)
    output_file = open('output.csv','w')
    next(reader, None)

    for row in reader:
        row_str = row[3]
        output_file.write(row_str + '\n')

    output_file.close()

rawDescription: How to read a column without header from csv and save the output in a txt file using Python?

description: Read a column without header from csv and save the output in a txt file using Python


code:
arrays = {}
n = input(': ')
arrays['Array%s' % n] = []

rawDescription: Python - Define new arrays or variables without having to Predefine them


code:
def update_the_widgets():
    the_label.configure(background="red")

a_button = tk.Button(..., command=update_the_widgets)
the_label = tk.Label(..., background="green")

rawDescription: Redraw widgets with update

description: Redraw widgets with update


rawDescription: Convert backward slash to forward slash in python


code: project_name = raw_input("Please give the name of your project.\n")

rawDescription: New line after a raw_input

description: New line after a raw_input


code:
#!/usr/bin/env python
"""
sms.py - Used to send txt messages.
"""
import serial
import time

class TextMessage:
    def __init__(self, recipient="0123456789", message="TextMessage.content not set."):
        self.recipient = recipient
        self.content = message

    def setRecipient(self, number):
        self.recipient = number

    def setContent(self, message):
        self.content = message

    def connectPhone(self):
        self.ser = serial.Serial('/dev/ttyACM0', 460800, timeout=5)
        time.sleep(1)

    def sendMessage(self):
        self.ser.write('ATZ\r')
        time.sleep(1)
        self.ser.write('AT+CMGF=1\r')
        time.sleep(1)
        self.ser.write('''AT+CMGS="''' + self.recipient + '''"\r''')
        time.sleep(1)
        self.ser.write(self.content + "\r")
        time.sleep(1)
        self.ser.write(chr(26))
        time.sleep(1)

    def disconnectPhone(self):
        self.ser.close()

rawDescription: How to send and receive SMS from python using usb modem?

description: Send and receive SMS from python using usb modem


code:
def get_initial(self):
    if request.GET.get('codereview-get'):
        initial = {'stream_name': 'TROI'}
    else:
        initial = {}
    return initial

rawDescription: Django Bounded forms in Class based views - CreateView class


code:
jpeg.read(2)
b = jpeg.read(1)
try:
    while (b and ord(b) != 0xDA):
        while (ord(b) != 0xFF): b = jpeg.read(1)
        while (ord(b) == 0xFF): b = jpeg.read(1)
        if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
            jpeg.read(3)
            h, w = struct.unpack(">HH", jpeg.read(4))
            break
        else:
            jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
        b = jpeg.read(1)
    width = int(w)
    height = int(h)
except struct.error:
    pass
except ValueError:
    pass

rawDescription: Python3 - parsing jpeg dimension info

description: Python3 - parsing jpeg dimension info


rawDescription: How do I convert unicode code to string in Python?

description: Convert unicode code to string in Python


code:
if not remove in stack:
    stack.append(remove)

rawDescription: Append to list if not repeated

description: Append to list if not repeated


rawDescription: Generate a waveform image from an audio file


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until( #10 second timeout.
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()
    # OR
    #driver.execute_script("window.stop();")

rawDescription: Telling selenium to stop blocking after expected condition


code:
def generator():
  n = 1
  while n:
    yield n
    n += 1

items = generator()
for item in itertools.islice(items, 100):
  print ('first', item)
for item in itertools.islice(items, 100):
  print ('second', item)

rawDescription: Control the iteration range of the generator?


code:
import pandas

df = pandas.read_csv("data.csv")
dff = df.resample("S", fill_method='pad')

rawDescription: Python EMA with Pandas over inconsistent timeseries


rawDescription: Changing labels in matplotlib polar plot


code:
from Tkinter import Tk, Canvas, PhotoImage, mainloop
from math import sin

WIDTH, HEIGHT = 640, 480

window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000")
canvas.pack()
img = PhotoImage(width=WIDTH, height=HEIGHT)
canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")

for x in range(4 * WIDTH):
    y = int(HEIGHT/2 + HEIGHT/4 * sin(x/80.0))
    img.put("#ffffff", (x//4,y))

mainloop()

rawDescription: python tkinter: how to work with pixels?

description: Python tkinter: how to work with pixels


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.config import Config
from kivy.clock import Clock
from kivy.properties import StringProperty, NumericProperty

kv = '''ScrollView:
  scroll_x: 1
  Label:
    canvas.before:
      Color:
        rgba:1,0,0,1
      Rectangle:
        pos: self.parent.pos
        size: self.size
    id:maindisplay
    text:"2"
    font_size:"50sp"
    text_size: None, self.height
    size_hint_x: None
    width:  max(self.texture_size[0], self.parent.width)
    halign: 'right'
    valign: 'middle'
    on_text: app.txt_cb(*args)
'''

class QApp(App):
    txt = StringProperty("1")
    num = NumericProperty(0)

    def add_string(self, dt=0):
        self.num += 1
        self.txt += "%i" % self.num
        self.root.ids.maindisplay.text = self.txt

    def txt_cb(self, obj, text):
        obj.text_size = (None, obj.height)
        obj.texture_update()
        obj.text_size = (max(obj._label.content_width, obj.parent.width), obj.height)

    def build(self):
        Clock.schedule_once(lambda dt:self.txt_cb(self.root.ids.maindisplay, ""), 0)
        Clock.schedule_interval(self.add_string, .5)
        return Builder.load_string(kv)

if __name__ == '__main__':
    QApp().run()

rawDescription: Align text to edge of Label in ScrollView in kivy


code:
namespace = {"your_application_object": some_object}

options = {
    # for some reason, these must
    # all exist, even if None
    'namespace'  : namespace,
    'passwd'     : 'users.txt',
    'sshPort'    : None,
    'telnetPort' : '4040',
}

rawDescription: twisted manhole: how to access servers in application?

description: Twisted manhole: how to access servers in application


code:
import os

folder = input('please enter the folder:')

file = input('enter the filename:')

print('C'+os.path.join(os.sep, folder, file))

rawDescription: New to Python 3.4+ Scripting and writing JSON text files and saving them


code:
from django.contrib.auth.models import User
del User.get_absolute_url

rawDescription: Django: Remove "view on site" button in the admin User change form


code:
axTopDict = {}
for leftSpec in LeftSpecList:
    fig = mplt.figure(str(leftSpec))
    axTop = fig.add_subplot( PageGrid[:5, :] )
    axTop.plot(eval(leftSpec),'ro')
    axTopDict[leftSpec] = axTop # associate this axis with this figure name

axBottomDict = {}
for rightSpec in RightSpecList:
    fig = mplt.figure(str(rightSpec))
    axBottom = fig.add_subplot( PageGrid[6:, :] )
    axBottom.plot(eval(rightSpec),'b*')
    axBottomDict[rightSpec] = axBottom # associate this axis with this figure name

LeftSpecListNew = ['Spec1', 'Spec2']

RightSpecListNew = ['Spec2', 'Spec3']

for leftSpec in LeftSpecList:
    fig = mplt.figure(str(leftSpec))
    axTop = axTopDict[leftSpec] # get the top axis associated with this figure name
    axTop.plot(eval(leftSpec),'m')

for rightSpec in RightSpecList:
    fig = mplt.figure(str(rightSpec))
    axBottom = axBottomDict[rightSpec] # get the bottom axis associated with this figure name
    axBottom.plot(eval(leftSpec),'g')

mplt.show()

rawDescription: Return to previously generated axis in matplotlib


code:
import os

for root, _, files in os.walk('/path/to/master'):
    if 'filename' in files:
        print(os.path.split(root)[1])
        break

rawDescription: Search for file name in full directory python


code:
out_file = open(outp, "w")
sub = subprocess.call(['sed', 's/\"//g', inp], stdout=out_file )

rawDescription: Python - using subprocess to call sed?

description: Python - using subprocess to call sed


code:
w = numpy.array([1, -2, 5])
x = numpy.array([0, 3, 2])

y = w+x
z = w-x

rawDescription: Most elegant/efficient/Pythonic way to calculate multiple parallel arrays?


code:
import tempfile
import os
dirname, basename = os.path.split(filename)
temp = tempfile.NamedTemporaryFile(prefix=basename, dir=dirname)
print(temp.name)

rawDescription: In python, make a tempfile in the same directory as another file?


code:
class ProductSerializer(serializers.ModelSerializer):
    sizes = SizeSerializer(many=True) # nested objects

    class Meta:
        model = Product
        fields = ('id', 'name', 'price', 'sizes')
        read_only_fields = ('id',)

class ProductCreateUpdateSerializer(serializers.ModelSerializer):
    # no nested objects, it accepts only size ids
    class Meta:
        model = Product
        fields = ('id', 'name', 'price', 'sizes')
        read_only_fields = ('id',)

rawDescription: django-rest-framework ManyToManyField create and update

description: Django-rest-framework ManyToManyField create and update


code:
_f = lambda x: cluster_df['set_size'][cluster_df['index'] == x].values[0]
all_sets_df['set_size'] = all_sets_df['cluster'].map(_f)
all_sets_df = all_sets_df.drop('cluster', axis=1)

rawDescription: Remap kmeans labels_ based on sorted cluster_centers_


rawDescription: python: difference of two timedate strings

description: Python: difference of two timedate strings


code: new_dict = {key:(value[:1] if len(value) > 1 else value) for key,value in old_dict.iteritems()}

rawDescription: Slicing strings in a comprehension

description: Slicing strings in a comprehension


code:
import Polygon, numpy

# Here I extracted and combined some contours and created a convex hull from it.
# Now I wanna check whether a contour acquired differently intersects with this hull or not.

for contour in contours:  # The result of cv2.findContours is a list of contours
    contour1 = contour.flatten()
    contour1 = numpy.reshape(contour1, (int(contour1.shape[0]/2),-1))
    poly1 = Polygon.Polygon(contour1)

    hull = hull.flatten()  # This is the hull is previously constructued
    hull = numpy.reshape(hull, (int(hull.shape[0]/2),-1))
    poly2 = Polygon.Polygon(hull)

    if (poly1 & poly2).area()<= some_max_val:
        some_operations

rawDescription: Intersection of 2D numpy ndarrays

description: Intersection of 2D numpy ndarrays


code:
with open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP', 'r+') as f:
    lines = f.readlines()
    #... Perform whatever replacement you'd like on lines
    f.seek(0)
    f.writelines(lines)

rawDescription: Update strings in a text file at a specific location


code:
def setup_nt_stdin(self):
    global msvcrt
    import msvcrt

rawDescription: python import statement fails in function

description: Python import statement fails in function


code:
import wx

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Vertical center")
        self.text = wx.StaticText(self, label=("This should be centered both"
                                   " vertically and horizontally"))
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_h = wx.BoxSizer(wx.HORIZONTAL)
        sizer_h.Add(self.text, 1, wx.CENTER)
        sizer_v.Add(sizer_h, 1, wx.CENTER)
        self.SetSizer(sizer_v)

        self.Show()

app = wx.App()
Frame()
app.MainLoop()

rawDescription: wx.BoxSizer both VERTICAL and HORIZONTAL centered

description: Wx.BoxSizer both VERTICAL and HORIZONTAL centered


code:
import numpy as np
from matplotlib.pyplot import *

def layer(y,height):
    neg=0.0;pos=0.0
    if y>0:
        if y-height>=0:
            pos=height
            y-= pos
        else :
            pos = y
    elif y<0:
        if y+height<=0:
            neg=height
            y += neg
        else :
            neg = -y
    return pos,neg

def horizonPlot(x,y,height=50.0,colors=['CornflowerBlue','DarkGreen']):
    alpha = .10
    vlayer = np.vectorize(layer)
    while (y != 0).any():
        l = vlayer(y,height)
        y -= l[0];y += l[1]
        fill_between(x,0,l[0],color=colors[0], alpha=alpha)
        fill_between(x,height-l[1],height,color=colors[1], alpha=alpha)

def main():
    x = np.linspace(0, np.pi*4, 137)
    y = (2*np.random.normal(size=137) + x**2)
    xx = np.hstack([-1*x[::-1], x])
    yy = np.hstack([-1*y[::-1], y])
    horizonPlot(xx,yy)
    show()

rawDescription: Implementing horizon charts in matplotlib


code: formatted_string = re.sub("[\t ]{2,}", " ", formatted_string)

rawDescription: Remove double space/tab combinations using Re in Python


code:
zipped = urllib.urlopen('www.abc.com/xyz.zip')
buf = cStringIO.StringIO(zipped.read())
zipped.close()
unzipped = zipfile.ZipFile(buf, 'r')
for f_info in unzipped.infolist():
   logfile = unzipped.open(f_info)
   # Here's where we buffer:
   logbuffer = cStringIO.StringIO(logfile.read())
   logfile.close()

   for handler in [handler1, handler2]:
      handler(logbuffer)
      # StringIO objects support seek():
      logbuffer.seek(0)

   unzipped.extract(f_info)

rawDescription: Reading the same file multiple times in Python


code:
import simpy

def user(machine):
    m = yield machine.get()
    print(m)
    yield machine.put(m)

    m = yield machine.get(lambda m: m['id'] == 1)
    print(m)
    yield machine.put(m)

    m = yield machine.get(lambda m: m['health'] > 98)
    print(m)
    yield machine.put(m)

env = simpy.Environment()
machine = simpy.FilterStore(env, 3)
machine.put({'id': 0, 'health': 100})
machine.put({'id': 1, 'health': 95})
machine.put({'id': 2, 'health': 97.2})

env.process(user(machine))

env.run()

rawDescription: SimPy Resource of 3 where each has different characteristics


code:
for a in soup.find_all('a', {'class':'pl-video-title-link'}):
    video_links.append(hostname + a['href'])

rawDescription: In Beautiful Soup, how do I dynamically search through a table to find a specific element?


code:
def move_mouse(m, maze, pos):
    if m == 'down':
        # check the maze
        pos = pos[0], pos[1] + 1
    return pos

maze = [[0 for x in range(8)] for x in range(8)]
pos = (4,4)

pos = move_mouse('down', maze, pos)

rawDescription: Passing a multidimensional array to a function in python


code:
from numpy import linspace, meshgrid, pi
u = linspace(0, pi, 3)
v = linspace(0, 10, 3)
uu, vv = meshgrid(u, v)
uu
vv
z = uu + 1j * vv
z

rawDescription: plotting complex function from one set to another

description: Plotting complex function from one set to another


code: from flask_pymongo import Pymongo

rawDescription: Failed to import PyMongo in Pycharm

description: Failed to import PyMongo in Pycharm


rawDescription: Multiplying NumPy arrays by scalars

description: Multiplying NumPy arrays by scalars


code:
kmers = []
def findKmersSet(k, stuff):
    for line in data:
        line_list = []
        for i in range(0,int(len(line)-k+1)):
            line_list.append(line[i:i+k])
        kmers.append(line_list)

findKmersSet(3, data)

rawDescription: Putting a list into a list at each new line


code:
import win32file
win32file.GetVolumeNameForVolumeMountPoint("C:\\")
win32file.GetVolumeNameForVolumeMountPoint("K:\\")

rawDescription: How to get a list of local drives without SUBST'ituted ones in Python / Windows?

description: Get a list of local drives without SUBST'ituted ones in Python / Windows


code:
class PhotoQuerySet(QuerySet):
    def delete(self):
        for x in self:
            x.delete()

class PhotoManager(models.Manager):
    def get_query_set(self):
        return PhotoQuerySet(self.model)

class Photo(models.Model):
    name = models.CharField(max_length=256, unique=True)
    slug = models.SlugField(unique=True)
    image = models.ImageField(upload_to='photos/')

    objects = PhotoManager()

    def delete(self):
        os.remove(self.get_thumbnail_name())
        os.remove(self.get_medium_name())
        super(Photo, self).delete()

rawDescription: Override delete-function on multi-delete


code:
while True:
    try:
        os.mkdir(r"z:\my_lock")
        return
    except OSError as e:
        if e.errno != 21: # Double check that errno will be the same on Windows
            raise
        time.sleep(5)

rawDescription: Implementing distributed lock using files


code: T = [L[i] for i in Idx]

rawDescription: In Python, how do I index a list with another list?


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

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)

plt.show()

rawDescription: Matplotlib 2 Subplots, 1 Colorbar

description: Matplotlib 2 Subplots, 1 Colorbar


code:
with open('text.txt') as f:
        data = f.read()

split = [x for x in data.split()]

rawDescription: Python: efficient way to read text file with varying delimiters (spaces)


code:
first_values = []
for val in D.values():
    first_values.append(int(val[0]))
print(max(first_values))

rawDescription: python: max value in a dictionary with 2 keys

description: Python: max value in a dictionary with 2 keys


code:
logging.Formatter('%(levelname)-8s %(asctime)s %(qthreadname)-15s %(message)s')
...
extras = {'qthreadname': get_qthreadname()}
logging.warning(message, extra=extras)

rawDescription: How to set the name of a QThread in pyqt?

description: Set the name of a QThread in pyqt


code:
from itertools import combinations, izip

data = db.collection.find()
a = list(data)

user_ids = [{user['id'] for user in i['users']} if 'users' in i else set()
            for i in a]

with open("edges.csv", "wb") as f:
    edges = csv.writer(f)
    for (i, i_ids), (q, q_ids) in combinations(izip(a, user_ids), 2):
        weight = len(i_ids & q_ids)
        if weight > 0:
            edges.writerow([i['id'], q['id'], weight])
            edges.writerow([q['id'], i['id'], weight])

with open("nodes.csv", "wb") as f:
    nodes = csv.writer(f)
    for i in a:
        nodes.writerow([
            i['id'],
            i['name'],
            i['latitude'],
            i['longitude'],
            len(i['users']),
            sum(len(p['photos']) for p in i['users']), # total number of photos
        ])

rawDescription: Optimize loops with big datasets Python

description: Optimize loops with big datasets Python


rawDescription: How to search a multiple-word-string (exact match) in a string?

description: Search a multiple-word-string (exact match) in a string


code:
def contains_multiple(string, substrings):
    count = 0

    for substring in substrings:
        if substring in string:
            count += 1
            if count > 1:
                return True

    return False

for line in data:
    if contains_multiple(line, my_list):
        ...

rawDescription: Find number of occurrences of a list in a string using Python


code:
def subsets(S):
    results = [[]]
    for x in S:
        results.extend([item + [x] for item in results])
    return results

rawDescription: Union sets of lists/sets in Python

description: Union sets of lists/sets in Python


code:
from bisect import bisect_left, bisect_right

def find_range(timeline, start, end):
    l = bisect_left(timeline, start)
    r = bisect_right(timeline, end)
    for i in xrange(l, r):
        yield timeline[i]

rawDescription: Pythonic way to extract elements from heapq


code:
from itertools import chain
a, b = [list(chain.from_iterable(x)) for x in zip(*my_list)]
a
b

rawDescription: Process list into separate lists

description: Process list into separate lists


code: extra_environ = {'HTTP_X_REQUESTED_WITH' : 'XMLHttpRequest'}

rawDescription: Testing AJAX post in TestApp and Pyramid


code:
from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')

rawDescription: flask - how do you get a query string from flask

description: Flask - how do you get a query string from flask


code:
self.add_bt.connect("clicked", self.on_add_bt_clicked)

def on_add_bt_clicked(self, button):
    dlg = Gtk.FileChooserDialog()
    dlg.show()

rawDescription: Adding browse function to button -Python


code:
class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for field in mylist:
            self.fields[field] = forms.CharField(max_length=100)

rawDescription: django create a form from list

description: Django create a form from list


code:
import re
s = "Sun, Jun 24, 2012 12:00 AMEngland  vs  West Indies"
match = re.search(r"\b[AP]M", s)
s[0:match.end()]
s[match.end():]

rawDescription: Formatting scraped data from a Website (BeautifulSoup)


code:
LL.insert(0,LL.pop([x for x, y in enumerate(LL) if y[1] == 'c'][0]))
LL

rawDescription: finding and moving a tuple in a list of tuples

description: Finding and moving a tuple in a list of tuples


code:
class Person(object):
    def __init__(self, fn, ln, address):
        self.uid    = Id_Class.new_id("Person")
        self.f_name = fn
        self.l_name = ln
        self.address = address

class Address(object):
    def __init__(self, st, sub):
        self.uid    = Id_Class.new_id("Address")
        self.street = st
        self.suburb = sub

hm = Address('Queen St.', 'Sydney')

s = Person('John', 'Doe', hm)

rawDescription: Python - how to reference one object to another


code:
def improve(solution):
    solution = list(reversed(solution))
    for i, num in enumerate(solution):
        if i >= 2:
            average = sum(solution[:i]) / i
            if average.is_integer():
                for x in range(i):
                    solution[x] = int(average)
                break
    return solution

def find_numbers(number, division, common_number):
    extra_number = number - common_number * division
    numbers_in_solution = [common_number] * division
    if extra_number < min_bound and \
    extra_number + common_number <= max_bound:
        numbers_in_solution[-1] += extra_number
    elif extra_number < min_bound or extra_number > max_bound:
        return None
    else:
        numbers_in_solution.append(extra_number)
    solution = improve(numbers_in_solution)
    return solution

def tst(number):
    try:
        solution = None
        for division in range(number//max_bound, number//min_bound + 1):  # Reverse the order of this for numbers as close in value to each other as possible.
            if round (number / division) in range(min_bound, max_bound + 1):
                solution = find_numbers(number, division, round(number / division))
            elif (number // division) in range(min_bound, max_bound + 1):  # Rarely required but catches edge cases
                solution = find_numbers(number, division, number // division)
            if solution:
                print(sum(solution), solution)
                break
    except ZeroDivisionError:
        print("Solution is 1, your input is less than the max_bound")

tst(number)
for x in range(1,100):
    tst(x)

rawDescription: split a value into values in max, min range

description: Split a value into values in max, min range


code:
import re

value = float(re.sub(r"[^\d.]", "", post.text))
print("value: %s" % value)

rawDescription: Python selenium string to int

description: Python selenium string to int


code:
from math import atan2
coorinput.sort(key=lambda c:atan2(c[0], c[1]))

rawDescription: Sort the points/coordinates of a circle into a logical sequence


code:
def mod_string(s):
    final = s # we need to add the original string initially.
    i = 0
    while len(final) % 6 != 0:
        final += s[i] # keep adding char at alternate indexes
        if i == len(s)-1: # if we are at the end of the string, reset
            i = 0
        else:
            i += 1 # else move to next char
    return final
In [28]: mod_string("1234")
Out[28]: '123412'
In [29]: mod_string("1234567")
Out[29]: '123456712345'
In [30]: mod_string("1")
Out[30]: '111111'
In [31]: mod_string("12345")
Out[31]: '123451'

rawDescription: Make string length divisible by 6 in Python


code:
reverseDict = {v:k for k,v in dictionary.iteritems()}

In [14]: reverseDict['AAAAAAA']
Out[14]: 'H576'

rawDescription: dictionary returns none when there should be a value python

description: Dictionary returns none when there should be a value python


code:
import xml.etree.ElementTree
doc = xml.etree.ElementTree.fromstring(content)
doc.findtext('creator/version')

rawDescription: Is there a quick way to get an XML element from a path?


code:
import re
file = open("ploop.txt")
text = file.read()
file.close()

proteins = text.split("\n\n")[1:]
proteinsMatching = []
toWrite = ""

for protein in proteins:
    if re.search(r"[AG].{4}GK[ST]", protein):
        proteinsMatching.append(protein)

for protein in proteinsMatching:
    accensionCode = re.findall(r">sp\|(.{6})", protein)[0]
    organism = re.findall(r"\n.+?\[(.+?)\]", protein)[0]
    print(accensionCode, organism)
    toWrite += accensionCode + " " + organism + "\n"

f = open("results.txt", "w+")
f.write(toWrite)
f.close()

# Q6GZX2 Frog virus 3 (isolate Goorha) (FV-3)
# Q6GZX1 Frog virus 3 (isolate Goorha) (FV-3)
# Q6GZW0 Frog virus 3 (isolate Goorha) (FV-3)
# P32234 Drosophila melanogaster (Fruit fly)

rawDescription: How to check if a list element contains a regex in Python?

description: Check if a list element contains a regex in Python


code:
allstatuses = []
for player in users:
    statuses = api.GetUserTimeline(screen_name=player, count=10)
    for s in statuses:
        allstatuses.append({'timestamp': s.created_at, 'username': s.user.name, 'status': s.text})

print(json.dumps(allstatuses))

rawDescription: adding new dict to json output python

description: Adding new dict to json output python


code:
url(r'^/someapp/(?P<page_id>\d+)/$', paginas),

def paginas(request, **kwargs):
    id = kwargs.pop('page_id')
    page = get_object_or_404(Page, id=id)
    # etcetera

class Page(models.Model):
    # regular stuff
    def get_absolute_url(self):
        return "/someapp/%d/" % self.id

rawDescription: Loading page in Django based on its ID

description: Loading page in Django based on its ID


code:
import datetime
queryset = MyModel.objects.filter(\
     time_created__lt=(datetime.now()-datetime.timedelta(minutes=3)))

rawDescription: Django/Python: how can i filter with Model's custom method?? Is this possible?


code:
host = request.host
host = host.split(':', 1)[0] # Strip off optional ':##' port number
username = None
if host.endswith('.yourdomain.com'):
    username = host.split('.', 1)[0]

rawDescription: how to map url with usernames prefixed?

description: Map url with usernames prefixed


code:
fig1,ax1=plt.subplots()
fig2,ax2=plt.subplots()
ax1.pie(...)
ax2.pie(...)
fig1.savefig(...)
fig2.savefig(...)

rawDescription: matplotlib pie charts leave labels from previous pie chart

description: Matplotlib pie charts leave labels from previous pie chart


code: assertTrue(var == 'a' or var2 == 'a')

rawDescription: Python unittest conditional assert

description: Python unittest conditional assert


code:
import numpy as np
import Image

dirname = '...'
[np.asarray(Image.open(os.path.join(dirname, fn))) for fn in os.listdir(dirname)]

rawDescription: Python - How to read a set of images and put it in a matrix?


code:
def get_readonly_fields(self, request, obj=None):
    if obj is None:
        return ['headline ']
    return []

rawDescription: make django model field read only or disable in admin while saving the object first time

description: Make django model field read only or disable in admin while saving the object first time


code:
from os.path import expanduser, join

path_to_file1 = join(expanduser('~/Dropbox/'), 'a')
path_to_file2 = join(expanduser('~'), 'a')
fout = open(path_to_file2, "w")
FILE = open(path_to_file1, "w")

rawDescription: Saving Files In New Directory (python)

description: Saving Files In New Directory (python)


code:
max_sec = 90000

ts.plot(x_compat=True, figsize=(20,10), xticks=arange(0, max_sec, 3600))

ts.plot(x_compat=True, figsize=(20,10), xticks=arange(0, max_sec, 7200))

rawDescription: Modifying number of ticks on Pandas hourly time axis


code:
import tkinter

tickets = 0

def ticket():
    tickets = 1
    print(tickets)

def twotickets():
    tickets = 2
    print(tickets)

def threetickets():
    tickets = 3
    print(tickets)

window = tkinter.Tk()

label = tkinter.Label(window, text="How many tickets would you like?")
button = tkinter.Button(window, text="One ticket", command=ticket)
button2 = tkinter.Button(window, text="Two tickets", command=twotickets)
button3 = tkinter.Button(window, text="Three tickets", command=threetickets)

label.pack()
button.pack()
button2.pack()
button3.pack()
window.mainloop()

rawDescription: Tkinter: How do I make a button assign a variable a number


code:
import numpy as np

A = np.array([[1,4],[2,5],[3,6]])
B = np.array([[1,4],[3,6],[7,8]])

nrows, ncols = A.shape
dtype={'names':['f{}'.format(i) for i in range(ncols)],
       'formats':ncols * [A.dtype]}

C = np.intersect1d(A.view(dtype), B.view(dtype))

# This last bit is optional if you're okay with "C" being a structured array...
C = C.view(A.dtype).reshape(-1, ncols)

rawDescription: Get intersecting rows across two 2D numpy arrays


code:
import itertools
import operator

def valid(cols_so_far):
    for i, col1 in enumerate(cols_so_far):
        for col2 in cols_so_far[i + 1:]:
            if any(map(operator.eq, col1, col2)):
                return False
    return True

def enum(letters, k, cols_so_far=None):
    if cols_so_far is None:
        cols_so_far = (tuple(letters),)
    if not valid(cols_so_far):
        pass
    elif len(cols_so_far) == k:
        yield tuple(zip(*cols_so_far))  # transpose
    else:
        for perm in itertools.permutations(letters):
            yield from enum(letters, k, cols_so_far + (perm,))

rawDescription: python: find all Latin Squares of a set (or partial square with fewer columns)

description: Python: find all Latin Squares of a set (or partial square with fewer columns)


code:
from types import SimpleNamespace

obj = SimpleNamespace(**{'hello': 'world'})

rawDescription: Is there an inverse of `vars(object)`

description: Is there an inverse of `vars(object)`


code:
commands = {
    'py': 'python {0}',
    'md': 'markdown "{0}" > "{0}.html"; gnome-open "{0}.html"',
}
commands['md'].format('file.md')

rawDescription: Pass parameter one time, but use more times


code: genres = [value_from_key(wb, 'Genre (%s)'%(i), n) for i in range(1,4)]

rawDescription: DRY version of a list

description: DRY version of a list


code: firsts, last = l[:-1], l[-1]

rawDescription: Python star operator in assignments

description: Python star operator in assignments


code:
from emails.template import JinjaTemplate as T

message = emails.html(subject=T('Payment Receipt No.{{ billno }}'),
                      html=T('<p>Dear {{ name }}! This is a receipt...'),
                      mail_from=('ABC', 'robot@mycompany.com'))

message.send(to=('John Brown', 'jbrown@gmail.com'),
             render={'name': 'John Brown', 'billno': '141051906163'})

rawDescription: HTML emails using python

description: HTML emails using python


code:
from itertools import combinations
list(combinations(range(3), 2))

rawDescription: Two nested for loops

description: Two nested for loops


code: print(sum(1 / i for i in range(7, 10)))

rawDescription: How can I sum the result of number values?

description: Sum the result of number values


code:
from StringIO import StringIO

from lxml import etree

dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>"""))
root = etree.XML("<foo/>")
print(dtd.validate(root))
# True

root = etree.XML("<foo>bar</foo>")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content

rawDescription: How do I validate xml against a DTD file in Python

description: Validate xml against a DTD file in Python


code:
k,j = np.meshgrid(np.arange(a.shape[1]),np.arange(a.shape[0]))
k
j
a[j,k,getters]

rawDescription: numpy array slicing, get one from each third dimension

description: Numpy array slicing, get one from each third dimension


code:
import datetime

d = datetime.datetime(year=2010,day=5,month=12)

d
datetime.datetime(2010, 12, 5, 0, 0)

rawDescription: Is there a library in Python that can convert user-dates to timestamp?


rawDescription: Python Decimal to Binary Array

description: Python Decimal to Binary Array


code:
def hamiltPath(graph):
    """This partitions a bipartite graph into a set of components with each
    component consisting of a hamiltonian path."""
    # The maximum degree
    maxDegree = 2

    # Get all the nodes.  We will process each of these.
    remaining = graph.vertices()
    # Create a new empty graph to which we will add pairs of nodes.
    newGraph = Graph()
    # Loop while there's a remaining vertex.
    while len(remaining) > 0:
        # Get the next arbitrary vertex.
        node = remaining.pop()
        # Now get its neighbors that are in the remaining set.
        neighbors = [n for n in graph.neighbors(node) if n in remaining]
        # If this list of neighbors is non empty, then add (node, neighbors[0])
        # to the new graph.
        if len(neighbors) > 0:
            # If this is not an optimal algorithm, I suspect the selection
            # a vertex in this indexing step is the crux.  Improve this
            # selection and the algorthim might be optimized, if it isn't
            # already (optimized in result not time or space complexity).
            neighbor = neighbors[0]
            newGraph.addEdge(node, neighbor)
            # "node" has already been removed from the remaining vertices.
            # We need to remove "neighbor" if its degree is too high.
            if len(newGraph.neighbors(neighbor)) >= maxDegree:
                remaining.remove(neighbor)

    return newGraph

class Graph:
    """A graph that is represented by pairs of vertices.  This was created
    For conciseness, not efficiency"""

    def __init__(self):
        self.graph = set()

    def addEdge(self, a, b):
        """Adds the vertex (a, b) to the graph"""
        self.graph = self.graph.union({(a, b)})

    def neighbors(self, node):
        """Returns all of the neighbors of a as a set. This is safe to
        modify."""
        return (set(a[0] for a in self.graph if a[1] == node).
                union(
                set(a[1] for a in self.graph if a[0] == node)
                ))

    def vertices(self):
        """Returns a set of all of the vertices. This is safe to modify."""
        return (set(a[1] for a in self.graph).
                union(
                set(a[0] for a in self.graph)
                ))

    def __repr__(self):
        result = "\n"
        for (a, b) in self.graph:
            result += str(a) + "," + str(b) + "\n"
        # Remove the leading and trailing white space.
        result = result[1:-1]
        return result

graph = Graph()
graph.addEdge("0", "4")
graph.addEdge("1", "8")
graph.addEdge("2", "8")
graph.addEdge("3", "5")
graph.addEdge("3", "6")
graph.addEdge("3", "7")
graph.addEdge("3", "8")
graph.addEdge("3", "9")
graph.addEdge("3", "10")
graph.addEdge("3", "11")

print(graph)
print()
print(hamiltPath(graph))
# Result of this is:
# 10,3
# 1,8
# 2,8
# 11,3
# 0,4

rawDescription: delete random edges of a node till degree = 1 networkx

description: Delete random edges of a node till degree = 1 networkx


code:
def main():
    myList = [[70, 80, 90], [30, 40, 50]]

    print(print_student_average(myList))
    print_exam_average(myList)

def print_student_average(myList):

    return [sum(row)/len(row) for row in myList]

def print_exam_average(myList):

    col_totals = [ sum(x)/len(myList) for x in zip(*myList) ]

for col in col_totals:
    print("the average of the exam is: ", col)

main()

rawDescription: How to get the average of a row in a 2D list in python?

description: Get the average of a row in a 2D list in python


code: b = [[] for _ in range(rang)]

rawDescription: how can I simpify expression?(PEP requirements)

description: Simpify expression?(PEP requirements)


code:
d = {'firstname' : 'Foo', 'lastname' : 'Bar'}
d = {unicode(k):unicode(v) for k,v in d.items() }

rawDescription: convert dictionary key and value to unicode

description: Convert dictionary key and value to unicode


code:
import gtk

test_data = [
    { 'column0' : 'test00', 'column1' : 'test01', 'f': '#000000', 'b': '#FF00FF' },
    { 'column0' : 'test10', 'column1' : 'test11', 'f': '#FF0000', 'b': '#C9C9C9' },
    { 'column0' : 'test20', 'column1' : 'test21', 'f': '#00FF00', 'b': '#FF0000' }]

class TestWindow(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)

        # create list storage
        store = gtk.ListStore(str, str, str, str)
        for i in test_data:
            store.append([i['column0'], i['column1'], i['f'], i['b']])
        treeview = gtk.TreeView(store)

        # define columns
        column0 = gtk.TreeViewColumn("Column 0", gtk.CellRendererText(), text=1, foreground=2, background=3)
        treeview.append_column(column0)
        column1 = gtk.TreeViewColumn("Column 1", gtk.CellRendererText(), text=1, foreground=2, background=3)
        treeview.append_column(column1)

        self.connect("destroy", lambda w: gtk.main_quit())
        self.connect("delete_event", lambda w, e: gtk.main_quit())

        self.add(treeview)
        self.show_all()

if __name__ == "__main__":
    TestWindow()
    gtk.main()

rawDescription: How to set the color of a single cell in a pygtk treeview?

description: Set the color of a single cell in a pygtk treeview


rawDescription: Negative axis in a log plot

description: Negative axis in a log plot


code:
import subprocess
processes = [subprocess.Popen(command) for command in commands]
while True:
    nproc = sum(p.poll() is None for p in processes)
    if not nproc:
        break
    print("%d processes running..." % nproc)
    sleep(0.1)

rawDescription: Monitor the number of processes spawned by subprocess in python


code:
from math import pi
# use raw input (raw_input()) for the inputs... input() is essentially eval(input())
# this is how i would ask for input for a simple problem like this
x = (raw_input("Do you have a [r]ectangle or a [c]ircle? ")) # Answer with r or c
# use .lower() to allow upper or lowercase
if x.lower() == "r":
    l = (int(raw_input("What is the length of your rectangle? ")))
    w = (int(raw_input("What is the width of your rectangle? ")))
    print( l * w )
elif x.lower() == "c":
    r = (int(raw_input("What is the radius of your circle? ")))
    print( r ** 2 * pi)
else:
    print("You didn't enter r or c.")

rawDescription: if-statement depending on input

description: If-statement depending on input


code:
def file_to_set(filename):
    """Opens a file and returns a set containing each line of the file."""
    with open(filename) as f:
        return set(f.read().splitlines(True))

def set_to_file(s, filename):
    """Writes a set to file."""
    with open(filename, 'w') as f:
        f.writelines(s)

def compare_files(ref_filename, *files):
    """Compares a reference file to two or more files."""
    if len(files) < 2:
        raise TypeError("compare_files expected at least 2 files, got %s" %
                        len(files))

    ref = file_to_set(ref_filename)
    file_data = [file_to_set(f) for f in files]

    all = file_data[0].union(*file_data[1:])
    common = ref.intersection(*file_data)
    partial = ref.intersection(all).difference(common)
    absent = ref.difference(all)

    set_to_file(common, 'common.csv')
    set_to_file(partial, 'partial.csv')
    set_to_file(absent, 'absent.csv')

compare_files('reference.csv', 'file1.csv', 'file2.csv', 'file3.csv')

rawDescription: Comparing data between 4 csv files and writing them to separate output files


code:
def inplaceeditform_path():
    import inplaceeditform
    return os.path.abspath(os.path.join(os.path.dirname(inplaceeditform.__file__),'media'))

STATICFILES_DIRS = (
   ('site/inplaceeditform' ,inplaceeditform_path()),
)

rawDescription: Is there a statics finder for django that will find statics in eggs?


code:
from PIL import Image
import StringIO
import binascii

# In your case, 's' will be the string from the field
# in the database.
s = open("chenchi.txt").read()

# chop off the '0x' at the front.
s = s[2:]

# Decode it to binary.
binary = binascii.unhexlify(s)

# Wrap the bytes in a memory stream that can be read like a file.
bytes = StringIO.StringIO(binary)

# Use pillow to read the memory stream into an image (it autodetects the format).
im = Image.open(bytes)

# And show it. Or you could .save() it.
im.show()

rawDescription: How to convert image data type from windows sql server to image using python?

description: Convert image data type from windows sql server to image using python


code:
value_regex = re.compile("(?<=Value=)(?P<value>.*?)(?=&)")
match = value_regex.search(strJunk)
match.group('value')
value_regex.sub("six", strJunk)

rawDescription: Python finding substring between certain characters using regex and replace()


code:
import urllib
urllib.quote("08/15/2013 14:23", safe='')

rawDescription: convert date to 08%2F15%2F2013%2014%3A23 in python

description: Convert date to 08%2F15%2F2013%2014%3A23 in python


code:
re.sub(
    '<status>(?P<id>\d+)',
    lambda m: status.get(int(m.group('id'))),
    'Tom ran: from <status>1 to <status>23')

rawDescription: Regex replace in Python: Convert named group to integer


code:
@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()

    if form.validate_on_submit():
        # do stuff with valid form
        # then redirect to "end" the form
        return redirect(url_for('register'))

    # initial get or form didn't validate
    return render_template('register.html', form=form)

rawDescription: Clear valid form after it is submitted

description: Clear valid form after it is submitted


code: svg_string = svg_string.replace(u'svg:', u'').replace(u'xmlns:svg', u'xmlns')

rawDescription: rdkit svg flavors and rendering inline svg on django dev server

description: Rdkit svg flavors and rendering inline svg on django dev server


code:
g = lambda x: pd.Series(f_polyfit(x.y1, x.y2, x.y3, x.y5, x.y5, degree=1))
df[['slope', 'R2']] = df.apply(g, axis=1)

rawDescription: Create multiple columns from multiple return value of lambda function in python DataFrame


code: zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+')

rawDescription: ZipFile complains, is there a way around using the zipfile module?


code:
import inspect
import example
inspect.getmembers(example, inspect.isroutine)

rawDescription: How do I get a list of function instances for a python source file?

description: Get a list of function instances for a python source file


code:
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseBadRequest
from django.utils import simplejson

def ajax_login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        if username and password:
            # Test username/password combination
            user = authenticate(username=username, password=password)
            # Found a match
            if user is not None:
                # User is active
                if user.is_active:
                    # Officially log the user in
                    login(self.request, user)
                    data = {'success': True}
                else:
                    data = {'success': False, 'error': 'User is not active'}
            else:
                data = {'success': False, 'error': 'Wrong username and/or password'}

            return HttpResponse(simplejson.dumps(data), mimetype='application/json')

    # Request method is not POST or one of username or password is missing
    return HttpResponseBadRequest()

rawDescription: setting up a user login in python / django using json and have no idea where to start

description: Setting up a user login in python / django using json and have no idea where to start


code:
from math import sqrt

def primes_n(n):
    primes = [2]
    for i in range(3, n+1, 2):
        for p in primes:
            if p > int(sqrt(i)):
                primes.append(i)
                break
            if i % k == 0:
                break
    return primes

rawDescription: Why is this prime-detection program so slow?


rawDescription: How to change smothing method of Naive Bayes classifier in NLTK？

description: Change smothing method of Naive Bayes classifier in NLTK？


code:
#! /usr/bin/python3.2

import json

class Jsonable:
    def __init__ (self, *args):
        self.fields = args

    def __call__ (self, cls):
        cls._jsonFields = self.fields
        def toDict (self):
            d = {}
            for f in self.__class__._jsonFields:
                v = self.__getattribute__ (f)
                if isinstance (v, list):
                    d [f] = [e.jsonDict if hasattr (e.__class__, '_jsonFields') else e for e in v]
                    continue
                d [f] = v.jsonDict if hasattr (v.__class__, '_jsonFields') else v
            return d
        cls.toDict = toDict

        oGetter = cls.__getattribute__
        def getter (self, key):
            if key == 'jsonDict': return self.toDict ()
            return oGetter (self, key)
        cls.__getattribute__ = getter

        return cls

@Jsonable ('professor', 'students', 'primitiveList')
class Course:
    def __init__ (self, professor, students):
        self.professor = professor
        self.students = students
        self.toBeIgnored = 5
        self.primitiveList = [0, 1, 1, 2, 3, 5]

@Jsonable ('firstname', 'lastname')
class Student:
    def __init__ (self, firstname, lastname, score = 42):
        self.firstname = firstname
        self.lastname = lastname
        self.score = score

@Jsonable ('title', 'name')
class Professor:
    def __init__ (self, name, title):
        self.title = title
        self.name = name

p = Professor ('Ordóñez', 'Dra')
s1 = Student ('Juan', 'Pérez')
s2 = Student ('Juana', 'López')
s3 = Student ('Luis', 'Jerez')
s4 = Student ('Luisa', 'Gómez')
c = Course (p, [s1, s2, s3, s4] )

print (json.dumps (c.jsonDict) )

rawDescription: Encoding custom objects with decorators - Python


code:
import os
from multiprocessing import Process, Queue

class TestProcess( Process ):
    def __init__( self, foo ):
        super( TestProcess, self ).__init__()
        self.foo = foo
        self.bar = None
        self.que = Queue()
    def run( self ):
        from time import sleep
        sleep( 1 )
        self.bar = self.foo
        print( "pid2=%s, p.bar=%s" % (os.getpid(), self.bar ))
        self.que.put(self.bar)

p = TestProcess( 5 )
p.start()
p.join()
print( "pid1=%s, p.bar=%s" % (os.getpid(), p.bar ))
print(p.que.get())

rawDescription: Storing objects on a Process in python

description: Storing objects on a Process in python


rawDescription: python dictionary- two keys to each value

description: Python dictionary- two keys to each value


code:
td_al_center = soup.find_all('td', {'align': 'center', 'valign': None})
td_al_center

rawDescription: beautiful soup extracting exact td tags

description: Beautiful soup extracting exact td tags


code:
import os

asps = []
for root, dirs, files in os.walk(r'C:\web'):
    for file in files:
    	if file.endswith('.asp'):
    		asps.append(file)

rawDescription: How can I create a list of files in the current directory and its subdirectories with a given extension?

description: Create a list of files in the current directory and its subdirectories with a given extension


code:
def isItBinary(myString):
    return all(x in ('0', '1') for x in myString)

rawDescription: How to see if a string only contains certain characters, and if they do, return True, else return False: Python

description: See if a string only contains certain characters, and if they do, return True, else return False: Python


code:
# assuming Python3
import tkinter as tk
import subprocess as sub

WINDOW_SIZE = "600x400"

root = tk.Tk()
root.geometry(WINDOW_SIZE)

tk.Button(root, text="Push me!", command=lambda: sub.call('path/to/script')).pack()

rawDescription: run a shell script from Python GUI

description: Run a shell script from Python GUI


code:
def calculate(matrix, list):
    out_matrix = np.empty_like(matrix)
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            out_matrix[i, j] = matrix[i, j] - list[i * matrix.shape[1] + j]

    return out_matrix

rawDescription: Iterate through list and array

description: Iterate through list and array


code:
import re
strs = "Hello (Test1 test2) (Hello1 hello2) other_stuff"
[", ".join(x.split()) for x in re.split(r'[()]',strs) if x.strip()]

rawDescription: Python splitting unknown string by spaces and parentheses


code:
class WriteReview(CreateView):
    model = Review
    success_url = reverse_lazy('restaurant_list')
    fields = ['restaurant','review']

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(WriteReview, self).form_valid(form)

rawDescription: How do I save the current logged in username in the CreateView submit action in Django?

description: Save the current logged in username in the CreateView submit action in Django


code:
results = []
database = []
for line in open("database/db.hdb"):
    line = line.split(':')
    #You could then manage database in chunks?
    database.append(line)
    if len(database) > MAX:
        #dosomething with database list so far to get result
        results.append(process_database(database))
        database = []
#do something now with individual results to make one result
combine_results(results)

rawDescription: How do I decrease the memory used by a large list in python

description: Decrease the memory used by a large list in python


code:
def evaluate(node):
  if node.payload.isOperation():
    return node.payload.compute(evaluate(node.left), evaluate(node.right))
  else:  # it's a constant
    return node.payload.asNumber()

rawDescription: Evaluating a parse tree in python

description: Evaluating a parse tree in python


rawDescription: Converting an array into a single string


code:
def get_records(history, start_date, end_date):
    for date, entry in history.iteritems():
        if start_date <= date <= end_date:
             yield date, entry

rawDescription: Select a range of dates in Python dictionary


code:
timer = QTimer()
timer.timeout.connect(your_function)
timer.start(100)

rawDescription: How can I repeat a function in python3 without using a while loop?

description: Repeat a function in python3 without using a while loop


code:
import numpy as np
arraylist = [np.array([1,2,3,4]), np.array([1,2,3,4]), np.array([1,3,2,4])]
L = {array.tostring(): array for array in arraylist}
L.values() # [array([1, 3, 2, 4]), array([1, 2, 3, 4])]

rawDescription: Removing duplicates from a list of numPy arrays


code: status, msg_data = server.fetch(some_id, '(UID BODY[TEXT])')

rawDescription: fetch only content of email

description: Fetch only content of email


rawDescription: Pandas interpolate within a groupby

description: Pandas interpolate within a groupby


code:
plt.imshow(grid1,
    extent=(x1.min(), x1.max(), y1.min(), y1.max()),
    origin='lower', vmin=-5, vmax=5, aspect='auto',
    interpolation='nearest', cmap=cm.gist_rainbow)

rawDescription: How can I rescale the range of variables in a 2D plot?

description: Rescale the range of variables in a 2D plot


code:
def mask_z_level(xi, yi, msk_img, x0=-14.3887, y0=5.564):
    im = plt.imread(msk_img)
    msk = np.zeros(xi.shape, dtype='bool')

    pxmm = np.zeros((3, 2))
    p = 0

    for row in range(im.shape[0]):
        for col in range(im.shape[1]):
            if tuple(im[row, col]) == (1., 0., 0.):
                pxmm[p] = (row, col)
                p += 1

    pxx = pxmm[1, 1] / 5.5
    pxy = pxmm[2, 0] / 6.5
    print(pxx, pxy)

    for j in range(xi.shape[1]):
        for i in range(xi.shape[0]):
            x, y = xi[i, j], yi[i, j]
            dx, dy = x - x0, y - y0
            dpx = np.round(dx * pxx).astype('int')
            dpy = -np.round(dy * pxy).astype('int')

            if tuple(im[dpy, dpx]) == (1., 1., 1.):
                msk[i, j] = True

    return msk

rawDescription: Finding edge from 2d points Python

description: Finding edge from 2d points Python


code:
from copy import deepcopy

class Foo(object):
    def __init__(self, bar):
        self.bar = bar
        self.spam = expression + that * generates - ham   # calculated

    def __copy__(self):
        # self.spam is to be ignored, it is calculated anew for the copy
        # create a new copy of ourselves *reusing* self.bar
        return type(self)(self.bar)

    def __deepcopy__(self, memo):
        # self.spam is to be ignored, it is calculated anew for the copy
        # create a new copy of ourselves with a deep copy of self.bar
        # pass on the memo mapping to recursive calls to copy.deepcopy
        return type(self)(deepcopy(self.bar, memo))

rawDescription: Python: Implementation of shallow and deep copy constructors


code:
import psychopy.iohub as iohub

io = iohub.launchHubServer(experiment_code="exp_sess_1")

# your experiment code here ....
# ...

io.quit()

rawDescription: How to dynamically rename the hdf5 file from psychopy's iohub

description: Dynamically rename the hdf5 file from psychopy's iohub


code:
import numpy as np
arr = np.array([1, 3, 2, 4, 5])
arr.argsort()[-3:][::-1]

rawDescription: How to get indices of N maximum values in a numpy array?

description: Get indices of N maximum values in a numpy array


code:
from sklearn.preprocessing import Imputer
imp = Imputer(strategy="mean")
a = np.random.random((5,5))
a[(1,4,0,3),(2,4,2,0)] = np.nan
a
a = imp.fit_transform(a)
a

rawDescription: filling gaps on an image using numpy and scipy

description: Filling gaps on an image using numpy and scipy


code:
import django.db.models
class Entry(models.Model):
    color=models.CharField(max_length="50")
    def save(self,create_children=True,**kwargs):
        if create_children and not self.pk:
            result = super(Entry,self).save(**kwargs)
            Entry(color=self.color).save(create_children=False)
            Entry(color=self.color).save(create_children=False)
        else:
            result = super(Entry,self).save(**kwargs)
        return result

rawDescription: How can I avoid recursion during saving of django model

description: Avoid recursion during saving of django model


code:
...
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
                  queue='task_queue',
                  no_ack=False)
...

rawDescription: Rabbitmq with python works unexpected

description: Rabbitmq with python works unexpected


code: guess = int(raw_input("Enter a number: "))

rawDescription: Loop until entry matches a predetermined value


code: [[n[0] for n in l]] + [u[1:] for u in l]

rawDescription: Python nested list slicing

description: Python nested list slicing


code:
s = 'bacdefaxyza'
idx = 6
s[:idx]+s[idx+1:]

rawDescription: Delete a repeated character from only one specific position and not from all places of the string in python


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pickle

with open('draw', 'rb') as pickle_file:
    xydict = pickle.load(pickle_file)

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(0, len(xydict))
Y = np.arange(0, len(xydict[0]))
X, Y = np.meshgrid(X, Y)
Z = np.array(xydict).T

ax.plot_surface(X[:,:-2], Y[:,:-2], Z[:,:-2], rstride=100, cstride=1, cmap=plt.cm.hot)
# ax.contourf(X, Y, Z, zdir='z', offset=0, cmap=plt.cm.hot)
ax.set_zlim(0,1)
plt.show()

rawDescription: matplotlib 3D plot, plot_surface black

description: Matplotlib 3D plot, plot_surface black


rawDescription: python datetime help

description: Python datetime help


code:
class myName:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name
b = myName('John')
type(b)
print(b)

rawDescription: Create a new type in python

description: Create a new type in python


code:
def display_player_image(canvas, player):

    canvas.create_rectangle(50, 50, 250, 100)
    tkImage = ImageTk.PhotoImage(Image.open(player.playerImg))
    canvas.create_image(100, 100, image = tkImage, anchor = NE)
    player.playerImg = tkImage #Reference

rawDescription: Adding JPEG Image to Tkinter Canvas

description: Adding JPEG Image to Tkinter Canvas


code: {{json | safe}}

rawDescription: Passing MySQL data from flask to JavaScript for Google Charts


rawDescription: Mongodb regex assistance

description: Mongodb regex assistance


rawDescription: Sum 2 columns of pandas DataFrame with a row condition


code:
W = tf.get_variable("W", shape=[784, 256],
           initializer=tf.contrib.layers.xavier_initializer())

rawDescription: How to do Xavier initialization on TensorFlow

description: Do Xavier initialization on TensorFlow


code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
# plot your data here ...

ax.set_xlabel(r'$\rho/\rho_{ref}\;\rightarrow$', color='red')
ax.set_ylabel(r'$\Delta \Theta / \omega \longrightarrow$')

plt.show()

rawDescription: how can I put an arrow near my x/ylabel?

description: Put an arrow near my x/ylabel


code:
class Example():

    def __iter__(self):
        lst = [1,2,3]
        for i in reversed(lst):
            yield i
        yield "one last time"

rawDescription: Return from an iterator and then throw StopIteration


code:
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
    'od.__setitem__(i, y) <==> od[i]=y'
    # Setting a new item creates a new link at the end of the linked list,
    # and the inherited dictionary is updated with the new key/value pair.
    if key not in self:
        root = self.__root
        last = root[0]
        last[1] = root[0] = self.__map[key] = [last, root, key]
    return dict_setitem(self, key, value)

rawDescription: Why is OrderedDict() ~10x slower than dict() and list()?


code:
from tkinter import *
#import tkFont
import random
from time import sleep
root = Tk()

class App:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.scale = Scale(frame, from_=0, to=1000)
        self.scale.grid(row=0)
        self.wrap = Canvas(root, width=200, height=140)
        self.wrap.pack()
        self.update()

    def update(self):

        #Importing the images. They are named a1.gif, a2.gif...a7.gif
        frame=[]
        for i in range(1,10):
            fname="CORE\\a"+str(i)+".gif"
            frame+=[PhotoImage(file=fname)]

        def do_animation(currentframe):

            def do_image():

                self.wrap.create_image(100,70,image=frame[currentframe], tag='ani')
            # Delete the current picture if one exists
            self.wrap.delete('ani')
            try:
                do_image()
            except IndexError:
                # End of image list reached, start over at the first image
                #- works for an arbitrary number of images
                currentframe = 0
                do_image()
            self.wrap.update_idletasks() #Force redraw
            currentframe = currentframe + 1
            # Call myself again to keep the animation running in a loop
            root.after(self.scale.get(), do_animation, currentframe)
        # Start the animation loop just after the Tkinter loop begins
        root.after(100, do_animation, 0)

app = App(root)
#app.geometry("800x480")
root.mainloop()

rawDescription: Python tkinter Slider control

description: Python tkinter Slider control


code:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

rawDescription: How to add persistent headers in requests calls?

description: Add persistent headers in requests calls


code:
from sklearn.preprocessing import normalize
rng = np.random.RandomState(42)
x = rng.randn(2, 5)
x
normalize(x)
x / np.linalg.norm(x, axis=1).reshape(-1, 1)
np.linalg.norm(normalize(x), axis=1)

rawDescription: Unexpected behavior in scitkit-learn's normalizer


rawDescription: Python RegEx match results are too minimal, please advise


code:
# Note this is for Python 2.x.
def func(lst):
    return map(range, xrange(len(lst)+1))
L = range(5)
func(L)

rawDescription: Creating sequential sublists from a list


code:
def neighbors(point):
    x, y = point

rawDescription: Giving a pair of numbers as a parameter in Python


code:
@app.errorhandler(404)
def page_not_found(e):
    # your processing here
    return result

rawDescription: Flask URL Route: Route All other URLs to some function


rawDescription: Numpy array, how to select indices satisfying multiple conditions?


code: for k in range(len(d) - x) : data.popitem(last = False)

rawDescription: Trim an ordered dict to the last x items


code:
# settings.py
SORTS = {SORT_BY_PRICE: 'price'}
DEFAULT_SORT = 'last_visited'

# whatever.py
sort_field = settings.SORTS.get(sort_by, settings.DEFAULT_SORT)

stops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)

rawDescription: Most efficient way to sort a Django QuerySet based on a form value


code:
import string

def long_enough(pw):
    'Password must be at least 6 characters'
    return len(pw) >= 6

def short_enough(pw):
    'Password cannot be more than 12 characters'
    return len(pw) <= 12

def has_lowercase(pw):
    'Password must contain a lowercase letter'
    return len(set(string.ascii_lowercase).intersection(pw)) > 0

def has_uppercase(pw):
    'Password must contain an uppercase letter'
    return len(set(string.ascii_uppercase).intersection(pw)) > 0

def has_numeric(pw):
    'Password must contain a digit'
    return len(set(string.digits).intersection(pw)) > 0

def has_special(pw):
    'Password must contain a special character'
    return len(set(string.punctuation).intersection(pw)) > 0

def test_password(pw, tests=[long_enough, short_enough, has_lowercase, has_uppercase, has_numeric, has_special]):
    for test in tests:
        if not test(pw):
            print(test.__doc__)
            return False
    return True

def main():
    pw = input('Please enter a test password:')
    if test_password(pw):
        print('That is a good password!')

if __name__=="__main__":
    main()

rawDescription: Python - Checking an input for numbers, uppercase, lowercase letters and special characters


code:
# Fork a second child and exit immediately to prevent zombies.  This
# causes the second child process to be orphaned, making the init
# process responsible for its cleanup.  And, since the first child is
# a session leader without a controlling terminal, it's possible for
# it to acquire one by opening a terminal in the future (System V-
# based systems).  This second fork guarantees that the child is no
# longer a session leader, preventing the daemon from ever acquiring
# a controlling terminal.

rawDescription: What is the reason for performing a double fork when creating a daemon?


code:
class ImageUrl(models.Model):
    file = models.ImageField(upload_to="%Y/%m/%d")
    createdAt = models.DateTimeField(default=datetime.now, editable=False)
    modifiedAt = models.DateTimeField(default=datetime.now)
    width = models.PositiveIntegerField(editable=False, default=0)
    height = models.PositiveIntegerField(editable=False, default=0)
    description = models.TextField(blank=True, default="")

    class Meta:
        ordering = ('createdAt',)

    def save(self, *args, **kwargs):
        if not self.id:
            #time_format = "%a %b %d %H:%M:%S %Y"
            self.createdAt = datetime.today()
            pil_image = PIL.Image.open(self.file)
            width, height = pil_image.size
            self.width = width
            self.height = height
        # If the obj already exists update its modifiedAt attr only
        self.modifiedAt = datetime.today()
        super(ImageUrl, self).save(*args, **kwargs)

rawDescription: Django Rest Framework returns null id when overriding ListSerializer create method


code:
import csv

def filter_time(filename, mintime, maxtime):
    timecol = 3
    reader = csv.reader(open(filename))
    next(reader)
    return [line for line in reader if mintime <= line[timecol] <= maxtime]

rawDescription: efficient way to extract few lines of data from a large csv data file in python

description: Efficient way to extract few lines of data from a large csv data file in python


code:
import httplib2

http = httplib2.Http()
http.follow_redirects = False

rawDescription: How can I disable automatically following redirects using python's httplib2?

description: Disable automatically following redirects using python's httplib2


code:
import os
import subprocess

with open(os.devnull, 'w') as devnull:
    output = subprocess.check_output("netstat -nptl".split(), stderr=devnull)

rawDescription: Suppress stderr within subprocess.check_output()


code: bar = copy.deepcopy(foo)

rawDescription: copies of classes in python

description: Copies of classes in python


code:
from lxml import etree as ET

def filter_by_itemid(doc, idlist):
    rowset = doc.xpath("/api/result/rowset[@name='assets']")[0]
    for elem in rowset.getchildren():
        if int(elem.get("itemID")) not in idlist:
            rowset.remove(elem)
    return doc

doc = ET.parse("test.xml")
filter_by_itemid(doc, [1004072840841])

print(ET.tostring(doc))

rawDescription: Python XML Remove Some Elements and Their Children but Keep Specific Elements and Their Children


code:
arr1inds = arr1.argsort()
sorted_arr1 = arr1[arr1inds[::-1]]
sorted_arr2 = arr2[arr1inds[::-1]]

rawDescription: Sort Array rows by another array in python


code:
import numpy as np
from scipy import ndimage

value = np.array([[0, 0, 1, 1, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [1, 1, 0, 0, 1, 0],
                  [0, 0, 0, 1, 0, 0]])

# label contiguous regions of non-zero elements
labels, nfeatures = ndimage.label(value)

# sizes of each region
sizes = (labels == (np.arange(nfeatures) + 1)[:, None, None]).sum((1, 2))

biggest = sizes.max()   # number of non-zero elements in largest contiguous region

print(biggest)
# 3

rawDescription: How to sum contiguous nonzero elements within a numpy array

description: Sum contiguous nonzero elements within a numpy array


code:
from collections import Counter
d = {'a':3, 'b':9, 'c':88, 'd': 3}
Counter(d.values()).most_common()

rawDescription: Calculating frequency of values in dictionary


code:
for thread in threading.enumerate():
    if isinstance(thread, threading._Timer):  # In Py2.7 at least, Timer is a function wrapping the class _Timer
        thread.cancel()

rawDescription: Obtain reference to thread I forgot to keep a reference for


code:
table = (entry.split() for entry in some_list)
raw_dates = (row[1] for row in table if len(row) >= 3)
# Uniquify while keeping order. http://stackoverflow.com/a/17016257
dates = list(collections.OrderedDict.fromkeys(raw_dates))

rawDescription: Python List Iteration into One-Liner

description: Python List Iteration into One-Liner


code:
import shlex
shlex.split("3 45 5.5 a bc")
shlex.split("3 45 5.5 \"This is a sentence.\" bc")
shlex.split("3 45 5.5 \"\\\"Yes\\\\No?\\\" it said.\" bc")

rawDescription: best pythonic way to parse param string?

description: Best pythonic way to parse param string


code:
df = pd.DataFrame({'insampleStart':[], 'insampleEnd':[], 'outsampleStart':[], 'outsampleEnd':[]})
df = df.append({'insampleStart':[1,2], 'insampleEnd':[5,6], 'outsampleStart':[6,7], 'outsampleEnd':[8,9]}, ignore_index=True)

rawDescription: append a row to a dataframe

description: Append a row to a dataframe


code:
import numpy as np
from scipy.interpolate import interp1d

def interpn(*args, **kw):
    """Interpolation on N-D.

    ai = interpn(x, y, z, ..., a, xi, yi, zi, ...)
    where the arrays x, y, z, ... define a rectangular grid
    and a.shape == (len(x), len(y), len(z), ...)
    """
    method = kw.pop('method', 'cubic')
    if kw:
        raise ValueError("Unknown arguments: " % kw.keys())
    nd = (len(args)-1)//2
    if len(args) != 2*nd+1:
        raise ValueError("Wrong number of arguments")
    q = args[:nd]
    qi = args[nd+1:]
    a = args[nd]
    for j in range(nd):
        a = interp1d(q[j], a, axis=j, kind=method)(qi[j])
    return a

import matplotlib.pyplot as plt

x = np.linspace(0, 1, 6)
y = np.linspace(0, 1, 7)
k = np.array([0, 1])
z = np.cos(2*x[:,None,None] + k[None,None,:]) * np.sin(3*y[None,:,None])

xi = np.linspace(0, 1, 60)
yi = np.linspace(0, 1, 70)
zi = interpn(x, y, z, xi, yi, method='linear')

plt.subplot(221)
plt.imshow(z[:,:,0].T, interpolation='nearest')

plt.subplot(222)
plt.imshow(zi[:,:,0].T, interpolation='nearest')

plt.subplot(223)
plt.imshow(z[:,:,1].T, interpolation='nearest')

plt.subplot(224)
plt.imshow(zi[:,:,1].T, interpolation='nearest')

plt.show()

rawDescription: Vector/array output from `scipy.ndimage.map_coordinates`


code:
import random
with open("infile.txt") as f:
    lines = f.readlines()
random.shuffle(lines)
with open("outfile.txt", "w") as f:
    f.writelines(lines)

rawDescription: Randomly mix the order of lines in a file