code:
from itertools import izip

import numpy as np
import cv2
from matplotlib import pyplot as plt
from PIL import Image

def take_and_save_picture(im_save):
  """Take a picture and save it

  Args:
    im_save: filepath where the image should be stored
  """
  camera_port = 0
  ramp_frames = 30
  cap = cv2.VideoCapture(camera_port)
  def get_image():
   retval, im = cap.read()
   return im

  for i in xrange(ramp_frames):
   temp = get_image()

  print("Taking image...")
  # Take the actual image we want to keep
  camera_capture = get_image()

  im_save_tmp = im_save + '.tmp'

  # A nice feature of the imwrite method is that it will automatically choose the
  # correct format based on the file extension you provide. Convenient!
  cv2.imwrite(im_save_tmp, camera_capture)

  # You'll want to release the camera, otherwise you won't be able to create a new
  # capture object until your script exits
  del(cap)

  img1 = cv2.imread(im_save_tmp, 0)

  edges = cv2.Canny(img1, 100, 200)
  cv2.imwrite(im_save, edges)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

def compute_edges_diff(im1, im2):
  """Compute edges diff between to image files.

  Args:
    im1: filepath to the first image
    im2: filepath to the second image

  Returns:
    float: percentage of difference between images
  """

  i1 = Image.open(im1)
  i2 = Image.open(im2)
  assert i1.mode == i2.mode, "Different kinds of images."
  assert i1.size == i2.size, "Different sizes."

  pairs = izip(i1.getdata(), i2.getdata())
  if len(i1.getbands()) == 1:
      # for gray-scale jpegs
      dif = sum(abs(p1-p2) for p1,p2 in pairs)
  else:
      dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))

  ncomponents = i1.size[0] * i1.size[1] * 3
  diff = (dif / 255.0 * 100) / ncomponents
  return diff

def main():
  capture_img = 'path_to_the_future_captured_img.jpg'
  img_to_compare = 'the_image_used_for_scoring.jpg'
  take_and_save_picture(capture_img)
  diff = compute_edges_diff(im1, im2)
  print "Difference (percentage):", diff

if __name__ == '__main__':
  main()

rawDescription: Itegration of two programs in python

description: Itegration of two programs in python


code:
def lt_dec(func):
    def _lt_lower(**kwargs):
        print 'type(kwargs)=', type(kwargs)
        print 'kwargs=', kwargs
        kwargs['lane_type'] = kwargs['lane_type'].lower()
        return func(**kwargs)
    return _lt_lower
@lt_dec
def test1(lane_type):
    print lane_type
test1(lane_type='Solid')

rawDescription: Decorator for functions with positional arguments, with commonly named argument


rawDescription: Arrays in loops

description: Arrays in loops


code:
import itertools, operator
from timeit import timeit

def drum(n):
    out = []
    for a in range(n):
        for b in range(n):
            for c in range(n):
                for d in range(n):
                    if a + b + c + d == n:
                        out.append((a, b, c, d))
    return out

def Stefan(n):
    combinations = (map(operator.sub, cuts + (n,), (0,) + cuts)
                    for cuts in itertools.combinations_with_replacement(range(n+1), 3))
    return [c for c in combinations if max(c) < n]

def Mijamo(n):
    combinations = itertools.product(range(n), repeat=4)
    return [tuple for tuple in combinations if sum(tuple) == n]

for func in drum, Stefan, Mijamo:
    print '%6s: %6.3f seconds' % (func.__name__, timeit(lambda: func(100), number=1))

rawDescription: Find all combination that sum to N with multiple lists


code: print '  -- Checking connectivity from {} to {}'.format(':'.join(map(str, env.hosts)), ':'.join(map(str, dbHostList)))

rawDescription: How can I print each list item, in a single line of code?

description: Print each list item, in a single line of code


code: print [(k,) + my_dict[k] for k in sorted(my_dict)]

rawDescription: How to convert this dictionary into a list of tuples?

description: Convert this dictionary into a list of tuples


rawDescription: efficient algorithm instead of looping

description: Efficient algorithm instead of looping


code:
import csv

with open('inputfile', 'rb') as inputfile:
    reader = csv.reader(inputfile, delimiter='|')
    for row in reader:
        if len(row) > 5 and row[5].lower().startswith('command'):
            print row[1], row[5]

rawDescription: python extracting second number in a line if meets a criteria

description: Python extracting second number in a line if meets a criteria


code:
@receiver(post_save, sender=Pizza)
def pizza_listener(sender, instance, created, **kwargs):
    instance.created = created

@receiver(m2m_changed, sender=Pizza.toppings.through)
def topping_listener(sender, instance, action, **kwargs):
    if action != 'post_add':
        # as example, only handle post_add action here
        return
    if getattr(instance, 'created', False):
        print 'toppings added to freshly created Pizza'
    else:
        print 'toppings added to modified Pizza'
    instance.created = False

rawDescription: Prevent m2m_changed from firing when creating an object


code:
#!/usr/bin/python

def load_module(name):
    return __import__(name)

def what_score(module_name, sc):
    return getattr(module_name, 'score')(sc)

if __name__ == '__main__':
    print "Input team name: ",
    team_name = raw_input().strip()
    module_name = load_module(team_name)
    print what_score(module_name, 5)

rawDescription: How to import many modules to main and execute

description: Import many modules to main and execute


code:
print 'this on screen'

with Logger("/tmp/1/main.log", "w") as sys.stdout:
     print 'this on screen an in main.log'

     with Logger("/tmp/1/sub.log", "w") as sys.stdout:
          print 'this on screen, in man.log and in sub.log'

print 'only on screen again'

rawDescription: Store all stdout to file while still displaying it on screen


code:
data="""a
b
line 3"""
# this will print each character (as in your code)
for line in data: print line

# split into lines instead
for line in data.split('\n'): print line

rawDescription: Python Reportlab multiple lines

description: Python Reportlab multiple lines


code:
import bisect

listofdicts = [
  {'dt': '2009-%2.2d-%2.2dT12:00:00' % (m,d) }
  for m in range(4,9) for d in range(1,30)
  ]

class Indexer(object):
  def __init__(self, lod, key):
    self.lod = lod
    self.key = key
  def __len__(self):
    return len(self.lod)
  def __getitem__(self, idx):
    return self.lod[idx][self.key]

lookfor = listofdicts[len(listofdicts)//2]['dt']

def mid(res=listofdicts, target=lookfor):
    keys = [r['dt'] for r in res]
    return res[bisect.bisect_left(keys, target)]

def midi(res=listofdicts, target=lookfor):
    wrap = Indexer(res, 'dt')
    return res[bisect.bisect_left(wrap, target)]

if __name__ == '__main__':
  print '%d dicts on the list' % len(listofdicts)
  print 'Looking for', lookfor
  print mid(), midi()
assert mid() == midi()

rawDescription: Finding closest match in collection of strings representing numbers


code:
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DECIMAL_DIGITS = "0123456789"

def is_alpha(a_string):
    if not a_string:
        return False
    for c in a_string:
        if not (c in ASCII_LOWERCASE or c in ASCII_UPPERCASE):
            return False
    return True

print is_alpha('')
print is_alpha('ABCabc')
print is_alpha('ABC123')

rawDescription: Defining Function Python

description: Defining Function Python


code:
reader = index.reader()
for x in r.expand_prefix('title', 'pop'):
  print x

rawDescription: Generating search term suggestions with Whoosh?


code:
from BeautifulSoup import BeautifulStoneSoup as Soup

xml = """
<TrdCaptRpt RptID="10000001" TransTyp="0">
    <RptSide Side="1" Txt1="XXXXX">
        <Pty ID="XXXXX" R="1"/>
    </RptSide>
</TrdCaptRpt>
"""

soup = Soup(xml)
rpt_side = soup.trdcaptrpt.rptside
rpt_side['txt1'] = 'Updated'
rpt_side.pty['id'] = 'Updated'

print soup

rawDescription: Updating XML Elements and Attribute values using Python etree


code:
lst = [[], [{'ceph_pk': 8L, 'deleted': False, 'user_key': u'landesk522_8', 'ceph_detail_id': 8L, 'account_title': u'logger test'}], [{'ceph_pk': 7L, 'deleted': True, 'user_key': u'landesk522_7', 'ceph_detail_id': 7L, 'account_title': u'test new'}]]

def compare_list(l1, l2):
    if l2 is None or len(l2) == 0:
        return 1
    if l1 is None or len(l1) == 0:
        return -1
    return cmp(l1[0].get('deleted', False), l2[0].get('deleted', False))

lst.sort(cmp=compare_list)
print lst

rawDescription: Python: sorting a list of dictionaries

description: Python: sorting a list of dictionaries


code:
import sys
for line in sys.stdin:
    s = str(line.strip())
    print len(s),

rawDescription: Print length of strings from each line of stdin in python


code:
import function

if __name__ == "__main__":
    ans = function.func(2, 3)
    print ans

rawDescription: how to link multiple python scripts

description: Link multiple python scripts


code:
from urllib import unquote

print unquote("EC%2d2EC7")

rawDescription: Converting url encoded string(utf-8) to string in python?


code:
import ctypes
lib = ctypes.CDLL('lib.so')

# let ctypes know the argument types
lib.rotatePoint.argtypes = [ctypes.POINTER(ctypes.c_double),ctypes.c_double]

# let ctypes know the return type
lib.rotatePoint.restype = ctypes.POINTER(ctypes.c_double)

def c_rotate_point(p,angle):

    # convert arguments to appropriate ctypes type
    p = (ctypes.c_double*2)(*p)
    angle = ctypes.c_double(angle)

    # call the function
    retval = lib.rotatePoint(p,angle)

    # here, retval has type LP_c_double object
    # indexing this will dereference the underlying pointer giving the results
    print retval[0],retval[1]

if __name__ == "__main__":
    c_rotate_point((0.2,0.3),0.4)

rawDescription: Ctypes: Parse Arguments and Return Results


code:
b = ['b','e','f','d','c','g','a']
f = 'check this'

def m(i):
    print i, b, f
    return None

b = sorted(b, key= m)
print b

rawDescription: Python accessing the list while being sorted


code:
import test

print test.vec()
print len(test.vec())
print test.vec()[0]
print test.vec().readonly
test.vec()[0]='z'
print test.vec()[0]

print "This should fail:"
test.cvec()[0] = 0

rawDescription: Expose a vector as a memoryview using SWIG


code:
class CatChannel(channel.SSHChannel):
    name = 'session'

    def openFailed(self, reason):
        print 'echo failed', reason

    def channelOpen(self, ignoredData):
        self.data = ''
        d = self.conn.sendRequest(self, 'exec', common.NS('cat'), wantReply = 1)
        d.addCallback(self._cbRequest)

    def _cbRequest(self, ignored):
        self.write('hello conch\n')
        self.conn.sendEOF(self)

    def dataReceived(self, data):
        self.data += data

    def closed(self):
        print 'got data from cat: %s' % repr(self.data)
        self.loseConnection()
        reactor.stop()

rawDescription: sound way to feed commands to twisted ssh after reactor.run()

description: Sound way to feed commands to twisted ssh after reactor.run()


code:
from Tkinter import *

def callbackfunc(*args, **kwargs):
    print args, kwargs
    print "Hello World!"

class App(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        optionvalue = IntVar(master)
        optionvalue.set(2)
        optionvalue.trace("w", callbackfunc)
        self.optionmenu = OptionMenu(master, optionvalue, 1, 2, 3, 4)
        self.optionmenu.pack()

root = Tk()
app = App(root)
root.mainloop()

rawDescription: What are the limitations of callback functions associated with Tkinter traces?


code:
def polly(cracker, wants):
    if wants:
       print 'polly wants a', cracker
f = polly
t = ('cracker', True)

rawDescription: passing a dictionary by reference instead of using eval / how to pass a variable number of arguments

description: Passing a dictionary by reference instead of using eval / how to pass a variable number of arguments


code:
from random import randint
from math import log10
from time import clock
from itertools import chain

def splitmerge0 (ls, digit): ## python (pure!)

    seq = map (lambda n: ((n // 10 ** digit) % 10, n), ls)
    buf = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[]}

    return reduce (lambda acc, key: acc.extend(buf[key]) or acc,
        reduce (lambda _, (d,n): buf[d].append (n) or buf, seq, buf), [])

def splitmerge1 (ls, digit): ## python (readable!)
    buf = [[] for i in range(10)]
    divisor = 10 ** digit
    for n in ls:
        buf[(n//divisor)%10].append(n)
    return chain(*buf)

def radixsort (ls, fn = splitmerge1):
    return list(reduce (fn, xrange (int (log10 (max(abs(val) for val in ls)) + 1)), ls))

###############################################################################
# quick sort
###############################################################################

def partition (ls, start, end, pivot_index):

    lower = start
    upper = end - 1

    pivot = ls[pivot_index]
    ls[pivot_index] = ls[end]

    while True:

        while lower <= upper and ls[lower] <  pivot: lower += 1
        while lower <= upper and ls[upper] >= pivot: upper -= 1
        if lower > upper: break

        ls[lower], ls[upper] = ls[upper], ls[lower]

    ls[end] = ls[lower]
    ls[lower] = pivot

    return lower

def qsort_range (ls, start, end):

    if end - start + 1 < 32:
        insertion_sort(ls, start, end)
    else:
        pivot_index = partition (ls, start, end, randint (start, end))
        qsort_range (ls, start, pivot_index - 1)
        qsort_range (ls, pivot_index + 1, end)

    return ls

def insertion_sort (ls, start, end):

    for idx in xrange (start, end + 1):
        el = ls[idx]
        for jdx in reversed (xrange(0, idx)):
            if ls[jdx] <= el:
                ls[jdx + 1] = el
                break
            ls[jdx + 1] = ls[jdx]
        else:
            ls[0] = el

    return ls

def quicksort (ls):

    return qsort_range (ls, 0, len (ls) - 1)

if __name__=='__main__':
    for value in 1000, 10000, 100000, 1000000, 10000000:
        ls = [randint (1, value) for _ in range(value)]
        ls2 = list(ls)
        last = -1
        start = clock()
        ls = radixsort(ls)
        end = clock()
        for i in ls:
            assert last <= i
            last = i
        print("rs %d: %0.2fs" % (value, end-start))
        tdiff = end-start
        start = clock()
        ls2 = quicksort(ls2)
        end = clock()
        last = -1
        for i in ls2:
            assert last <= i
            last = i
        print("qs %d: %0.2fs %0.2f%%" % (value, end-start, ((end-start)/tdiff*100)))

rawDescription: Why is my radix sort python implementation slower than quick sort?


code:
pattern = r'([^\(]+)(\(([^,]*),(.*)\))?'
df = s.str.extract(pattern, expand=True).iloc[:, [0, 2, 3]]

# Formatting to get it how you wanted
df.columns = ['Data Type', 'Precision', 'Scale']
df.index.name = None
print df

rawDescription: Python parse dataframe element

description: Python parse dataframe element


code:
startTime = time.time()
newTime = time.time()
j=0
for i in range(num):
    j = (((j+10)**0.5)**2)**0.5
    if i % 50 == 0:  # Only check every 50th iteration
        if time.time() - newTime > 0.5:
            newTime = time.time()
            print i, newTime
print time.time() - startTime
# 45 seconds (the original version took 42 on my system)

rawDescription: What is the best/most efficient way to output value every x seconds during a loop


code:
class Square(object):
    def __init__(self, ul, ll, ur, lr):
        self.ul = ul
        self.ll = ll
        self.ur = ur
        self.lr = lr

def main():
    s1 = Square(Point(1, 2), Point(1, 1), Point(2, 2), Point(2, 1))
    s2 = Square(Point(3, 3), Point(3, 2), Point(4, 3), Point(4, 2))
    print s1.ul.x # 1
    print s1.lr.y # 2

rawDescription: Constructor overwrites previous values of already created object


rawDescription: How to flat and merge values in a dictionary using python?

description: Flat and merge values in a dictionary using python


code: print "The piece is moved to {}{}.".format(col,row)

rawDescription: What am I doing wrong? and/or in Python

description: What am I doing wrong? and/or in Python


code:
from bs4 import BeautifulSoup as bsoup
import requests as rq

url = "http://auctionresults.fcc.gov/Auction_66/Results/xml/round/66_115_database_round.xml"
r = rq.get(url)

soup = bsoup(r.content, "lxml")
print soup

rawDescription: BeautifulSoup XML parsing not working

description: BeautifulSoup XML parsing not working


code:
import csv

def read_input(filename):
    f = open(filename)
    return csv.DictReader(f, delimiter = ',')

def search_filter(src, term):
    term = term.lower()
    for s in src:
        if term in map(str.lower, s.values()):
            yield s

def query(src, terms):
    terms = terms.split()
    for t in terms:
        src = search_filter(src, t)
    return src

def print_query(q):
    for row in q:
        print row

rawDescription: Finding a small list of strings in a large list of strings (Python)


code:
for a in the_list:
    if {'/', ';', 'e'} <= set(a) and {'@', 'k'}.isdisjoint(a) and len(a) <= 80:
        print a

rawDescription: Python: multiple criteria in a ‘if’ statement (‘and’ & ‘or’?)


code:
from __future__ import division

from numpy import *

Radius=10
N=1024
dx=2*Radius/N
dy=dx
x=r_[-Radius:Radius:dx]
y=r_[-Radius:Radius:dy]
X, Y = meshgrid(x,y)
R = sqrt(X**2+Y**2)
PHI = arctan2(Y,X)

ringthing = R < Radius
ring = zeros((2,N,N),dtype=complex)
ring[0] = ringthing
ring[1] = ringthing*exp(1j*PHI)

print ring[1][-1, 0], angle(ring[1][-1, 0])
print ring[1][0, -1], angle(ring[1][0, -1])

rawDescription: Strange complex phase displayed

description: Strange complex phase displayed


code:
from pattern.en import parse
print parse('I eat pizza with a fork.')

rawDescription: Identify all Substantives in a Text

description: Identify all Substantives in a Text


code:
import Tkinter as tk
class Omenu2(object):

    def __init__(self, app):
        self.app = app
        self.master = tk.Toplevel(app)
        self.master.title('test1')
        self.OpMenu2()

    def OpMenu2(self):
        self.op2 = tk.StringVar()
        self.opt2 =['2', '3']
        self.men2 = tk.OptionMenu(self.master, self.op2, *self.opt2, command=self.test)
        self.men2.pack()

    def test(self, num):
       print self.op2.get()
       print num

rawDescription: OptionMenu on multiple windows with single mainloop


code:
xml = '''<root>
                  <zoo>
                      <some_tag/>
                      <some_diff/>
                      <dog/>
                      <dog/>
                      <cat/>
                      <cat/>
                      <cat/>
                  </zoo>

                  <zoo>
                      <b/>
                      <o/>
                      <dog/>
                      <dog/>
                      <cat></cat>
                      <cat></cat>
                  </zoo>
            </root>'''

from lxml import etree as et

root = et.fromstring(xml)

# The below 3 lines have the same effect, use whichever you like
node = root.findall('./zoo')
node = list( root.getchildren() )
node = root.getchildren()

dogs_flag = False
cats_flag = False

for zoo in node:

    # Resetting the flags in each iteration, otherwise, you will
    # have all the cats and dogs inside one zoo element ... try it yourself
    dogs_flag = False
    cats_flag = False

    for animal in zoo:

        if 'dog' == animal.tag:
            if not dogs_flag:
                dogs = et.SubElement(zoo,'dogs')
                dogs_flag = True    # I think this is a better place to set your flag

            dogs.append(animal)

        if 'cat' == animal.tag:
            if not cats_flag:
                cats = et.SubElement(zoo,'cats')
                cats_flag = True

            cats.append(animal)

print et.tostring(root, pretty_print = True)

rawDescription: Parsing xml with lxml in python 3

description: Parsing xml with lxml in python 3


code:
import inspect
def printargs(*args):
    print args
a = (1,2,3)
f = lambda x: printargs(*x)
f(a)
inspect.isfunction(f)

rawDescription: <method-wrapper '__call__' of functools.partial object at 0x1356e10> is not a Python function


code: print ' '.join(['%-2s' % (i,) for i in l])

rawDescription: python print in format way unknow list length

description: Python print in format way unknow list length


code:
from Queue import Queue
from threading import Thread

import urllib2
import re

# Work queue where you push the URLs onto - size 100
url_queue = Queue(10)
pattern = re.compile('">(.+?)

')

def worker():
    '''Gets the next url from the queue and processes it'''
    while True:
        url = url_queue.get()
        print url
        html = urllib2.urlopen(url).read()
        print html[:10]
        links = pattern.findall(html)
        if len(links) > 0:
            print links
        url_queue.task_done()

# Start a pool of 20 workers
for i in xrange(20):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

# Change this to read your links and queue them for processing
for url in xrange(100):
    url_queue.put("http://www.ravn.co.uk")

# Block until everything is finished.
url_queue.join()

rawDescription: Scrape 160.000 pages - too slow

description: Scrape 160.000 pages - too slow


code:
input = '\n jack ryan \n policeman and pony enthusiast \n german \n john anderson \n fisherman \n swedish \n barack putin \n french \n programmer'

# Split on '\n':
lines = input.splitlines()

# Remove the first empty line:
lines = lines[1:]

output = ''
step_size = 3
for i in range(0, len(lines), step_size):
    output += '//'.join(lines[i:i + step_size]) + '\n'

print output

rawDescription: Replace every nth '\n' in a string

description: Replace every nth '\n' in a string


code:
import xml.dom.minidom

data = """<root>
Some bad text that I do not want to keep.
</root>"""

dom = xml.dom.minidom.parseString(data)
a = dom.getElementsByTagName('a')[0]
for child in a.childNodes:
    if getattr(child, 'tagName', '') in ('u', 'b'):
        a.removeChild(child)

print dom.toxml()

rawDescription: Removing an element, but not the text after it


code:
import pandas as pd
import numpy as np
arr = np.array([[1, 2], [3, 4]])
df = pd.DataFrame(arr, columns=['f', 's'])
print df['f']

rawDescription: Referencing columns by assigned name in numpy array


code:
empty = {'151': {'1': 'empty', '0': 'empty', '2': '2.30', '8': ['empty', 'empty', 5, {"foo2": "bar2", "1": "empty"}]}}
full = {'151': {'1': 3.4, '0': 3.6, '2': 2, '8': ['foo', 'bar', 'baz', {"foo3": "bar3", "1": "2"}]}}

def repl(a, b):
    if isinstance(a, dict) and isinstance(b, dict):
        clean = {}
        for k, v in a.items():
            # This is the case where we want to replace what we have in b if we have something.  Just in case, use the dict.get method and provide a default.
            if v == 'empty':
                clean[k] = b.get(k, 'Not there')
            # If the value is another dict, then call this function with the value, and put the return as the value for our current key
            elif isinstance(v, dict):
                v_clean = repl(v, b.get(k, {}))
                clean[k] = v_clean
            # The value isn't equal to 'empty', and it isn't another dict, so just keep the current value.
            elif isinstance(v, list):
                v_clean = repl(v, b.get(k, []))
                clean[k] = v_clean
            else:
                clean[k] = v
        # Finally, return the cleaned up dictionary.
    elif isinstance(a, list) and isinstance(b, list):
        clean = []
        for item_a, item_b in zip(a, b):
            if item_a == 'empty':
                clean.append(item_b)
            elif isinstance(item_a, dict):
                clean_a = repl(item_a, item_b)
                clean.append(clean_a)
            else:
                clean.append(item_a)
    return clean

print repl(empty, full)

rawDescription: Modifying nested dictionaries

description: Modifying nested dictionaries


code:
import time

def format_date_range(etime):
    input_date_strs = etime.split(' to ')

    # use a list comprehension and tuple expansion
    # typically 'i' is used for numbers, use of s hints at the items being strs
    start, end = [time.strptime(s, "%Y-%m-%d") for s in input_date_strs]

    # if both in the same year, omit it from start date
    start_fmt = "%B %d" if start.tm_year == end.tm_year else "%B %d %Y"

    # if both in the same month and year, omit month from end date
    end_fmt = "%d, %Y" if (start.tm_mon, start.tm_year) == (end.tm_mon, end.tm_year) else "%B %d %Y"

    return time.strftime(start_fmt, start)+ '-' + time.strftime(end_fmt, end)

TEST_TIMES = [
    '2014-10-21 to 2014-10-23',
    '2014-10-21 to 2015-10-23',
    '2014-10-21 to 2014-11-23',
    '2014-10-21 to 2015-10-23',
    ]

for etime in TEST_TIMES:
    print format_date_range(etime)

rawDescription: A better way of converting a string into a range of dates (and back again)?


code:
def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

rawDescription: python multi-processing zombie processes

description: Python multi-processing zombie processes


code:
#!/usr/bin/python

import os,sys
import cgi
import cgitb; cgitb.enable()

os.environ[ 'HOME' ] = '/tmp/'

import matplotlib
matplotlib.use( 'Agg' )
import pylab
form = cgi.FieldStorage()
pylab.plot([1,2,3])

print "Content-Type: image/png\n"
pylab.savefig( sys.stdout, format='png')

rawDescription: Change permissions to allow PHP script in browser to execute matplotlib operations in a python script


code:
def findAccount(la, view):
    if view.getClass() == 'android.widget.TextView':
        text = view.getText()
        if re.match(re.compile('.*@yahoo.com'), text):
            la.append(text)

list_accounts = []
listview_id = vc.findViewByIdOrRaise('android:id/list')
vc.traverse(root=listview_id, transform=lambda v: findAccount(list_accounts, v))
for item in list_accounts:
    print "account:", item

rawDescription: How to use viewclient traverse method in AndroidViewClient

description: Use viewclient traverse method in AndroidViewClient


code:
import random

def chkValidInput (userInput):
    chkNumber = False

    for amtChar in range(0, len( userInput ) ):
        for aNumber in range(0, 10):
            if userInput[amtChar] == str(aNumber):
                chkNumber = True
                break
            elif userInput[amtChar] != str(aNumber):
                chkNumber = False
        if chkNumber == False:
            return False

    return True

def evaluateBet(choice):

    randNum = 0

    randNum = random.randrange(1,14)

    print "The random number is: " + str(randNum)

    if choice == "high" and randNum > 7:
        print "You Win!"
        return True
    elif choice == "low" and randNum < 7:
        print "You Win!"
        return True
    else:
        print "You Lose!"
        return False

def main():

    wins = 0
    losses = 0

    print "Commencing HiLo.py...\n"

    random.seed(None)

    points = 1000
    wager = 0
    userInput = None
    programLoop = True
    validInput = False

    while programLoop == True:

        print "Wins: " + str(wins)
        print "Losses: " + str(losses)

        print "Points remaining: " + str( points )

        wager = 0
        userInput = None
        validInput = False

        while validInput == False:
            userInput = raw_input("\nMake a wager: ")

            validInput = chkValidInput(userInput)

            if validInput == False:
                print "Invalid Input. It must be a positive Number. Try Again."

            elif validInput == True:
                if int( userInput ) > points:
                    validInput = False
                    print "You don't have enough points to make that wager. Try Again."
                elif int( userInput ) == 0:
                    validInput = False
                    print "Your wager must be greater than 0. Try Again."

        wager = int (userInput)
        points = points - wager

        print "Points remaining: " + str( points )
        print "Wager: " + str( wager )

        validInput = False

        while validInput == False:
            userInput = raw_input("\nPlace a bet: Either type 'High' or 'Low': ")
            userInput = userInput.lower()
            if userInput == "high" or userInput == "low":
                validInput = True
            else:
                 print "You may only choose to type from the options 'high' or 'low' "

        if evaluateBet(userInput) == True:
            points = ( points + (wager * 2) )
            wager = 0
            wins += 1
        else:
            losses += 1

        print "Points remaining: " + str( points )

        validInput = False

        if points <= 0:
            print "You do not have anymore points; game over."
            programLoop = False
        else:
            while validInput == False:
                userInput = raw_input("\nWould you like to play again?: Type 'yes' or 'no': ")
                userInput = userInput.lower()

                if userInput == "yes" or userInput == "no":
                    validInput = True
                else:
                    print "You may only choose to type from the options 'yes' or 'no' "

            if userInput == "yes":
                programLoop = True
            elif userInput == "no":
                print "Final wins and losses"
                print "Wins: " + str(wins)
                print "Losses: " + str(losses)
                programLoop = False

main()

rawDescription: How do I make a score counter for my game in python?

description: Make a score counter for my game in python


code:
import redis

redis_instance = redis.Redis()
pubsub = redis_instance.pubsub()
pubsub.subscribe('process log')

while True:
    for message in pubsub.listen():
        print message  #  or use websockets to comunicate with a browser

rawDescription: Stream results in celery

description: Stream results in celery


code: print zip.__doc__

rawDescription: List comprehension and logical indexing

description: List comprehension and logical indexing


rawDescription: python split string into strings with same language characters

description: Python split string into strings with same language characters


code:
fn1, fn2='/tmp/1.csv', '/tmp/2.csv'

import csv
from itertools import izip

with open(fn1) as f1, open(fn2) as f2:
    r1=csv.reader(f1)
    r2=csv.reader(f2)
    for v1, v2 in izip(r1, r2):
        print v1, v2

rawDescription: Processing two CSV files in parallel

description: Processing two CSV files in parallel


code:
import itertools
l = [['a', 'b'], 'c', ['d', 'e'], ['f', 'g'], 'h']
for i in itertools.product(*l): print list(i)

rawDescription: Recursive "all paths" through a list of lists - Python


code:
""" Linop( A ): .matvec .rmatvec( sparse vecs )
http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.LinearOperator.html
http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.lsmr.html
"""

from __future__ import division
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import LinearOperator  # $scipy/sparse/linalg/interface.py

__version__ = "2015-12-24 dec  denis + safe_sparse_dot"

#...............................................................................
class Linop( LinearOperator ):  # subclass ?
    """ Aop = Linop( scipy sparse matrix A )
        ->  Aop.matvec(x) = A dot x, x ndarray or sparse
            Aop.rmatvec(x) = A.T dot x
        for scipy.sparse.linalg solvers like lsmr
    """

    def __init__( self, A ):
        self.A = A

    def matvec( self, x ):
        return safe_sparse_dot( self.A, x )

    def rmatvec( self, y ):
        return safe_sparse_dot( self.A.T, y )

        # LinearOperator subclass should implement at least one of _matvec and _matmat.
    def _matvec( self, b ):
        raise NotImplementedError( "_matvec" )

        # not _matvec only:
        # $scipy/sparse/linalg/interface.py
        # def matvec(self, x):
        #     x = np.asanyarray(x)  <-- kills sparse x, should raise an error

    def _rmatvec( self, b ):
        raise NotImplementedError( "_rmatvec" )

    @property
    def shape( self ):
        return self.A.shape

def safe_sparse_dot( a, b ):
    """ -> a * b or np.dot(a, b) """
        # from sklearn
    if sparse.issparse(a) or sparse.issparse(b):
        try:
            return a * b
        except ValueError:  # dimension mismatch: print shapes
            print "error: %s %s  *  %s %s" % (
                    type(a).__name__, a.shape,
                    type(b).__name__, b.shape )
            raise
    else:
        return np.dot(a, b)

#...........................................................................
if __name__ == "__main__":
    import sys
    from lsmr import lsmr  # patched $scipy/sparse/linalg/lsmr.py

    np.set_printoptions( threshold=20, edgeitems=10, linewidth=100, suppress=True,
        formatter = dict( float = lambda x: "%.2g" % x ))

        # test sparse.rand A m n, x n 1, b m 1
    m = 10
    n = 100
    density = .1
    bdense = 0
    seed = 0
    damp = 1

        # to change these params in sh or ipython, run this.py  a=1  b=None  c=[3] ...
    for arg in sys.argv[1:]:
        exec( arg )

    np.random.seed(seed)

    print "\n", 80 * "-"
    paramstr = "%s  m %d  n %d  density %g  bdense %d  seed %d  damp %g " % (
            __file__, m, n, density, bdense, seed, damp )
    print paramstr

    A = sparse.rand( m, n, density, format="csr", random_state=seed )
    x = sparse.rand( n, 1, density, format="csr", random_state=seed )
    b = sparse.rand( m, 1, density, format="csr", random_state=seed )
    if bdense:
        b = b.toarray().squeeze()  # matrix (m,1) -> ndarray (m,)

    #...........................................................................
    Aop = Linop( A )
        # aslinearoperator( A ): not for sparse x

        # check Aop matvec rmatvec --
    Ax = Aop.matvec( x )
    bA = Aop.rmatvec( b )
    for nm in "A Aop x b Ax bA ".split():
        x = eval(nm)
        print "%s: %s %s " % (nm, x.shape, type(x))
    print ""

    print "lsmr( Aop, b )"

    #...........................................................................
    xetc = lsmr( Aop, b, damp=damp, show=1 )
    #...........................................................................

    x, istop, niter, normr, normar, norma, conda, normx = xetc
    x = getattr( x, "A", x ) .squeeze()
    print "x:", x.shape, x

    #     print "lsmr( A, b ) -- Valueerror in $scipy/sparse/linalg/interface.py"
    #     xetc = lsmr( A, b, damp=damp, show=1 )  # Valueerror

    safe_sparse_dot( A, b.T )  # ValueError: dimension mismatch

rawDescription: SciPy.sparse iterative solvers: No sparse right hand side support?


code:
while True:
   print ser.read(1000)

rawDescription: pySerial: port only works the first I use it after I power it on

description: PySerial: port only works the first I use it after I power it on


rawDescription: Replacing a character with a new line in a string in a list in python


code:
#!/usr/bin/env python

data = [
    'a/bc/this',
    'a/bc/is',
    'a/bc/a',
    'a/bc/short',
    'a/bc/test',
    'a/bc/123',
    'a/bc/24',
    'a/bc/5',
]

#Simple sequence printer
def show(seq):
    for row in seq:
        print row
    print

#Get maximum length of the string after the last slash in each data string
maxlen = max(len(s.rsplit('/', 1)[1]) for s in data)

#Key function that pads the string after the last slash
key = lambda s: s.rsplit('/', 1)[1].rjust(maxlen, '0')

#Test the key function
show([(s, key(s)) for s in data])

new_data = sorted(data, key=key)
show(new_data)

rawDescription: How to sort by padded string attribute in python using key functions

description: Sort by padded string attribute in python using key functions


code:
dic = {'list1': range(1, 4), 'list2':range(1, 3), 'list3':range(1, 5)}
for k, v in dic.items():
    if len(v) == 4:
        print k

rawDescription: Print a name of a list within a list

description: Print a name of a list within a list


code:
import pandas as pd
Dxz = pd.DataFrame({"x": [False,False,True], "z": [0,2,0], "p": [0.4,0.2,1]})
Dxz.set_index(["x","z"], inplace=True)
print Dxz.reindex(pd.MultiIndex.from_tuples([(False, 0), (False, 1), (False, 100), (True, 23)]), method="ffill")

rawDescription: Interpolate on the fly to get previous valid entry from pandas DataFrame


code:
import types
class Foo(object):
    def __init__(self):
        self.a = "A"
def bar(self):
    print self.a
f = Foo()
f.bar = types.MethodType(bar, f, Foo)
f.bar()

rawDescription: how to add a new function for a class which is created previous?

description: Add a new function for a class which is created previous


code:
from scipy.optimize import minimize_scalar

def f(x):
    return (1 - log_norm_obj.cdf(x)) / log_norm_obj.pdf(x) - x

result = minimize_scalar(f)
print result.x
# this would print your result

rawDescription: How do I solve for x with a known function in equation using numpy/scipy?

description: Solve for x with a known function in equation using numpy/scipy


code:
from PyQt4 import QtCore, QtGui

class CustomQTableWidget(QtGui.QTableWidget):
    def __init__(self, *args, **kwargs):
        QtGui.QTableWidget.__init__(self, *args, **kwargs)
        #Fill Qtable
        self.insertColumn (0)
        self.insertColumn (1)
        self.insertColumn (2)
        self.insertColumn (3)
        self.insertRow (0)
        self.insertRow (1)
        self.insertRow (2)
        self.insertRow (3)
        self.insertRow (4)
        self.insertRow (5)
        self.insertRow (6)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton: #Release event only if done with left button, you can remove if necessary

            #Your code should go here
            indexSelection = []

            for item in self.selectedIndexes():
                indexSelection.append( str(item.row())+ "-" + str(item.column()) )

            print indexSelection

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        self.tableWidget = CustomQTableWidget() #Create a custom QtableWidget
        hbox = QtGui.QHBoxLayout() #Put stuff in a layout...
        hbox.addWidget(self.tableWidget) #...
        self.setLayout(hbox) #...

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = MyDialog()
    w.show()
    sys.exit(app.exec_())

rawDescription: Row and Column numbers of selected cells


code:
def escape(s):
    ch = (ord(c) for c in s)
    return ''.join(('\\x%02x' % c) if c <= 255 else ('\\u%04x' % c) for c in ch)

for text in (u'\u2018\u2019hello there\u201c\u201d', 'hello there'):
    esc = escape(text)
    print esc

    # code below is to verify by round-tripping
    import ast
    assert text == ast.literal_eval('u"' + esc + '"')

rawDescription: Converting characters to their python escape sequences


code:
import xlrd
print xlrd.colname(56)
# BE

rawDescription: Python xlwt - Convert column integer into excel cell references. Eg (3,6) to C6


code:
user_timeline=twitter.getUserTimeline(screen_name="dksbhj", count=50)
for tweet in user_timeline:
    print tweet['text'] + "\n"

rawDescription: Fetching maximum tweets from twitter using Twython


code:
for k,g in it.groupby(sorted(trees,key=op.itemgetter(0)),key=op.itemgetter(0)):
  tempg = list(g)
  print k, sum(i[1] for i in tempg), sum(i[2] for i in tempg)

rawDescription: How to subdivide a nested list (used as a matrix) into lists based on the string in the 0th column

description: Subdivide a nested list (used as a matrix) into lists based on the string in the 0th column


code:
def missing_function():
    print 'missing'
execfile('faulty.py',  {'missing_function' : missing_function})

rawDescription: How can I execute a bunch of Python commands before a script is run when using the Python interpreter?

description: Execute a bunch of Python commands before a script is run when using the Python interpreter


code:
#!/usr/bin/env python

import fileinput
for line in fileinput.input():
  print line

rawDescription: argument type of fileinput.input() in python

description: Argument type of fileinput.input() in python


code:
lines = [line.strip() for line in open('file.txt')]
nlines=[]
for line in lines:
    if 3 not in map(int,line.split()) and 4 not in map(int,line.split()): nlines.append(line)
for x in nlines:
    y=x.split()
    y=y[1::2]
    print ' '.join(y)

rawDescription: Removing rows that contain certain value and removing odd numbered columns


code:
def find_all(password, File_Path):
    password = password.lower()
    with open (File_Path, 'r') as o:
        for line in o:
            if password in line.lower():
                print line[:line.find(' ')]

rawDescription: Display 'word' results on seperate line and print first word of sentences which contain the word (Python)


code:
for vals in value_lists:
    #reverse depending if you want top 3 or bottom
    label_inds_vals = sorted([thing for thing in enumerate(vals)], key=lambda x: x[1], reverse = True)
    print label_inds_vals[:3]

rawDescription: How can you get the order back after using argsort?

description: Get the order back after using argsort


code:
import ast
from math import sqrt

# same a previous recursion function but with looking for 'id' not 'name' attribute
def recursive_parse(node,substitutions):
    if hasattr(node.left,"id"):
        if node.left.id in substitutions.keys():
            node.left = substitutions[node.left.id]
    else:
        recursive_parse(node.left,substitutions)

    if hasattr(node.right,"id"):
        if node.right.id in substitutions.keys():
            node.right = substitutions[node.right.id]
    else:
        recursive_parse(node.right,substitutions)

def main(input):

    substitutions = {
        "r":"sqrt(x**2+y**2)"
        }

    for key,value in substitutions.items():
        substitutions[key] = ast.parse(substitutions[key], mode='eval').body

    # As this is an assignment operation, mode must be set to exec
    module = ast.parse(input, mode='exec')

    print "Input:        ",ast.dump(module)

    recursive_parse(module.body[0].value,substitutions)

    print "Substituted:  ",ast.dump(module)

    # give some values for the equation
    x = 3
    y = 2
    p = 1
    code = compile(module,filename='<string>',mode='exec')
    exec(code)

    print input
    print "t =",t

if __name__ == "__main__":
    input = "t = r*p"
    main(input)

rawDescription: Parsing an equation with sub-formulas in python


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

row = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
grouped = grouper(3, row)

for i, row in enumerate(grouped):
    for j, column in enumerate(row):
        if i < j:
            print column

rawDescription: Python - permutation and percentage

description: Python - permutation and percentage


code:
import sys

def process(file):
    for line in file:
        arr = line.split()
        if not arr:
            continue
        last = arr.pop()
        n = len(arr)
        if n == 4:
            first, middle = ' '.join(arr[:2]), ' '.join(arr[2:])
        elif n == 3:
            if arr[0] in ('M', 'Shk', 'BS'):
                first, middle = ' '.join(arr[:2]), arr[-1]
            else:
                first, middle = arr[0], ' '.join(arr[1:])
        elif n == 2:
            first, middle = arr
        else:
            continue
        print 'First: %r' % first
        print 'Middle: %r' % middle
        print 'Last: %r' % last

if __name__ == '__main__':
    process(sys.stdin)

rawDescription: Separate first, middle and last names (Python)


rawDescription: How to assign '\'(-inf-24.5]\'' to a python string?

description: Assign '\'(-inf-24.5]\'' to a python string


code:
class GradeBook(dict):
    def __getitem__(self,key):
        return dict.__getitem__(self,key//10)

    def __missing__(self,key):
        if key > 9:
            return 'A'
        elif key < 5:
            return 'F'

d = GradeBook(zip(range(5,10),'FDCBA'))
print d[100]
print d[45]
print d[120]
print d[45.2]
print d[72.8]

rawDescription: Dictionary help in Python

description: Dictionary help in Python


code:
import nltk
grammar = nltk.parse_cfg("""
S -> NP VP
PP -> P NP
NP -> Det N | Det N PP | N
VP -> V NP | VP PP
N -> 'Kim' | 'Dana' | 'everyone'
V -> 'arrived' | 'left' |'cheered'
P -> 'or' | 'and'
""")
sent = "Kim arrived".split()
parser = nltk.ChartParser(grammar)
print parser.nbest_parse(sent)

sent = "Kim arrived or".split()
parser = nltk.ChartParser(grammar)
print parser.nbest_parse(sent)

rawDescription: Python and NLTK: How to analyze sentence grammar?


code:
from BeautifulSoup import BeautifulSoup

doc = ['<title>Page title</title>',
       '
This is paragraph one.',
       '
This is paragraph two.',
       '']
soup = BeautifulSoup(''.join(doc))

for tag in soup.findAll('script'):
    # Use extract to remove the tag
    tag.extract()
    # use simple insert
    soup.body.insert(len(soup.body.contents), tag)

print soup.prettify()

rawDescription: Extract all <script> tags in an HTML page and append to the bottom of the document


code:
from functools import wraps
from time import time

def timed(f):
  @wraps(f)
  def wrapper(*args, **kwds):
    start = time()
    result = f(*args, **kwds)
    elapsed = time() - start
    print "%s took %d time to finish" % (f.__name__, elapsed)
    return result
  return wrapper

rawDescription: how to measure execution time of functions (automatically) in Python

description: Measure execution time of functions (automatically) in Python


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class Model(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items = ['Item_A000','Item_B001','Item_A002','Item_B003','Item_B004']
        self.numbers=[20,10,30,50,40]
        self.added=0
    def rowCount(self, parent=QModelIndex()):
        return len(self.items)
    def columnCount(self, parent=QModelIndex()):
        return 2

    def data(self, index, role):
        if not index.isValid(): return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()

        row=index.row()
        column=index.column()

        if column==0:
            if row<len(self.items):
                return QVariant(self.items[row])
        elif column==1:
            if row<len(self.numbers):
                return QVariant( self.numbers[row] )
        else:
            return QVariant()

    def removeRows(self, position, rows=1, index=QModelIndex()):
        print "\n\t\t ...removeRows() Starting position: '%s'"%position, 'with the total rows to be deleted: ', rows
        self.beginRemoveRows(QModelIndex(), position, position + rows - 1)
        self.items = self.items[:position] + self.items[position + rows:]
        self.endRemoveRows()

        return True

    def insertRows(self, position, rows=1, index=QModelIndex()):
        print "\n\t\t ...insertRows() Starting position: '%s'"%position, 'with the total rows to be inserted: ', rows
        indexSelected=self.index(position, 0)
        itemSelected=indexSelected.data().toPyObject()

        self.beginInsertRows(QModelIndex(), position, position + rows - 1)
        for row in range(rows):
            self.items.insert(position + row,  "%s_%s"% (itemSelected, self.added))
            self.added+=1
        self.endInsertRows()
        return True

class Proxy(QSortFilterProxyModel):
    def __init__(self):
        super(Proxy, self).__init__()

    def filterAcceptsRow(self, rowProc, parentProc):
        modelIndex=self.sourceModel().index(rowProc, 0, parentProc)
        item=self.sourceModel().data(modelIndex, Qt.DisplayRole).toPyObject()

        if item and 'B' in item:
            return True
        else: return False

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        vLayout=QVBoxLayout(self)
        self.setLayout(vLayout)

        hLayout=QHBoxLayout()
        vLayout.insertLayout(0, hLayout)

        tableModel=Model(self)

        proxyB=Proxy()
        proxyB.setSourceModel(tableModel)

        self.ViewA=QTableView(self)
        self.ViewA.setModel(tableModel)
        self.ViewA.clicked.connect(self.viewClicked)

        self.ViewB=QTableView(self)
        self.ViewB.setModel(proxyB)
        self.ViewB.clicked.connect(self.viewClicked)
        self.ViewB.setSortingEnabled(True)
        self.ViewB.sortByColumn(0, Qt.AscendingOrder)
        self.ViewB.setSelectionBehavior(QTableView.SelectRows)

        hLayout.addWidget(self.ViewA)
        hLayout.addWidget(self.ViewB)

        insertButton=QPushButton('Insert Row Above Selection')
        insertButton.setObjectName('insertButton')
        insertButton.clicked.connect(self.buttonClicked)
        removeButton=QPushButton('Remove Selected Item')
        removeButton.setObjectName('removeButton')
        removeButton.clicked.connect(self.buttonClicked)

        vLayout.addWidget(insertButton)
        vLayout.addWidget(removeButton)

    def getZeroColumnSelectedIndexes(self, tableView=None):
        if not tableView: return
        selectedIndexes=tableView.selectedIndexes()
        if not selectedIndexes: return
        return [index for index in selectedIndexes if not index.column()]

    def viewClicked(self, indexClicked):
        print 'indexClicked() row: %s  column: %s'%(indexClicked.row(), indexClicked.column() )
        proxy=indexClicked.model()

    def buttonClicked(self):
        button=self.sender()
        if not button: return

        tableView=None
        if self.ViewA.hasFocus(): tableView=self.ViewA
        elif self.ViewB.hasFocus(): tableView=self.ViewB
        if not tableView: print 'buttonClicked(): not tableView'; return

        zeroColumnSelectedIndexes=self.getZeroColumnSelectedIndexes(tableView)
        if not zeroColumnSelectedIndexes: print 'not zeroColumnSelectedIndexes'; return

        firstZeroColumnSelectedIndex=zeroColumnSelectedIndexes[0]
        if not firstZeroColumnSelectedIndex or not firstZeroColumnSelectedIndex.isValid():
            print 'buttonClicked(): not firstZeroColumnSelectedIndex.isValid()'; return

        startingRow=firstZeroColumnSelectedIndex.row()
        print '\n buttonClicked() startingRow =', startingRow

        if button.objectName()=='removeButton':
            tableView.model().removeRows(startingRow, len(zeroColumnSelectedIndexes), QModelIndex())

        elif button.objectName()=='insertButton':
            tableView.model().insertRows(startingRow, len(zeroColumnSelectedIndexes), QModelIndex())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

rawDescription: How to insert and remove row from model linked to QTableView

description: Insert and remove row from model linked to QTableView


code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

def onclick(event):
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
    event.button, event.x, event.y, event.xdata, event.ydata)

fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', onclick)
plt.plot([0, 1, 2], [5, 10, 15])

plt.ion()
plt.show()
count = 0
next = 0

while plt.fignum_exists(fig.number):
    print "Working %s" % count

    while time.time() < next:
        plt.pause(.001)

    next = time.time() + 1.0
    count += 1

rawDescription: Matplotlib event handling without use of `show()`


code:
import os,sys, api

RootDir=os.getcwd()
#Add this directory to export
if RootDir not in sys.path:
    sys.path.append(RootDir)

#Plugin stuff
def LoadPlugins():
    PluginsDir=os.path.join(RootDir,'plugins')
    Plugins=os.listdir(PluginsDir)

    Modules=[]
    for P in Plugins:
        PItems=os.path.splitext(P)
        PName=PItems[0]
        if PName!='__init__' and PItems[len(PItems)-1]=='.py':
            print "Loading plugins."+PName
            Mod=__import__("plugins."+PName,fromlist=['*'])
            Modules.append(Mod)
    return Modules
def RunPlugins(Modules):
    for Plugin in Modules:
        Plugin.Run()

Plugins=LoadPlugins()

#Just checking plugins can modify variables.
api.Run()
RunPlugins(Plugins)
api.Run()

rawDescription: Python Plugin Capbility

description: Python Plugin Capbility


code:
import calendar
import datetime

def mSandE(yy,mm):
    lastDay=calendar.monthrange(yy,mm)[1]
    dt1=datetime.date(yy, mm, 1)
    dt2=datetime.date(yy, mm, lastDay)
    return (dt1, dt2)

def prevmSandE(yy,mm):
    dt=mSandE(yy,mm)[0]
    dt=dt-datetime.timedelta(days=1)
    lastDay=calendar.monthrange(dt.year,dt.month)[1]
    return (dt.replace(day=1),datetime.date(dt.year,dt.month,lastDay))

print mSandE(2012,2)
print prevmSandE(2012,2)
print prevmSandE(2012,1)

rawDescription: Some python date manipulation

description: Some python date manipulation


code:
import numpy as np
abc_array = np.array(['B', 'D', 'A', 'F', 'H', 'I', 'Z', 'J'])

transdict = {'A': 'Adelaide',
             'B': 'Bombay',
             'C': 'Cologne',
             'D': 'Dresden',
             'E': 'Erlangen',
             'F': 'Formosa',
             'G': 'Gdansk',
             'H': 'Hague',
             'I': 'Inchon',
             'J': 'Jakarta',
             'Z': 'Zambia'
}

phoenetic = [transdict[letter] for letter in abc_array]
print ' '.join(phoenetic)

rawDescription: How to use a dictionary to translate/replace elements of an array?

description: Use a dictionary to translate/replace elements of an array


code:
from chardet.universaldetector import UniversalDetector
chardet_detector = UniversalDetector()

def charset_detect(f, chunk_size=4096):
    global chardet_detector
    chardet_detector.reset()
    while 1:
        chunk = f.read(chunk_size)
        if not chunk: break
        chardet_detector.feed(chunk)
        if chardet_detector.done: break
    chardet_detector.close()
    return chardet_detector.result

# Exercise for the reader: replace the above with a class

import csv
import sys
from pprint import pprint

pathname = sys.argv[1]
delim = sys.argv[2] # allegedly known
print "delim=%r pathname=%r" % (delim, pathname)

with open(pathname, 'rb') as f:
    cd_result = charset_detect(f)
    encoding = cd_result['encoding']
    confidence = cd_result['confidence']
    print "chardet: encoding=%s confidence=%.3f" % (encoding, confidence)
    # insert actions contingent on encoding and confidence here
    f.seek(0)
    csv_reader = csv.reader(f, delimiter=delim)
    for bytes_row in csv_reader:
        unicode_row = [x.decode(encoding) for x in bytes_row]
        pprint(unicode_row)

rawDescription: Python: A resilient, actually working CSV implementation for non-ascii?


code:
from pyDes import *
import hashlib
import base64
key = hashlib.md5("L6#F&,q2$xLx").digest()
data = "I love security"
k = triple_des(key, ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
base64Encrypted= base64.b64encode(d)
print "Encrypted: %r" % d
base64Decrypted= base64.b64decode(base64Encrypted)
print "Decrypted: %r" % k.decrypt(base64Decrypted)

rawDescription: Encrypting Datas using python

description: Encrypting Datas using python


code:
filtered = sorted(data["GROUP-A"].items(), key= lambda kv: max(value for group_b in kv[1].itervalues() for key_b in group_b.itervalues() for group_c in key_b.itervalues() for value in group_c.itervalues()))
print filtered

rawDescription: Challenge: create a list by sorting a bunch of nested dict


rawDescription: printing and formatted list in python

description: Printing and formatted list in python


code:
def get_row(table, col_name, val, default=None):
    col = getattr(table.c, col_name)
    row = table.select(col == S).execute().fetchone()
    if row == None:
        print "Warning: No row found for %s in %s; using %s" % (val, table, default)
        row = table.select(col == default).execute().fetchone()
    return row[0]

rawDescription: Generic function that accept a table and column name and returns all the primary key values that matches a filter value given


rawDescription: how to delete the "u and ' ' " before the of database table display by python

description: Delete the "u and ' ' " before the of database table display by python


code:
from win32com.client import GetObject

WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')

for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'):
    print "--running cmd.exe---"
    for prop in [prop.Name for prop in p.Properties_]:
        print prop,"=",p.Properties_(prop).Value

rawDescription: How to close a cmd window using python 2.7

description: Close a cmd window using python 2.7


code:
odd = [1, 3, 5, 7]
even = [2, 4, 6, 8]

user_input = int(raw_input("enter a number: "))

if user_input in odd or user_input in even:
  print "the number "+str(user_input)+" was already entered"
else:
  if user_input %2 == 0:
    even.append(user_input)
    print "added to even list"
  else:
    odd.append(user_input)
    print "added to odd list"

rawDescription: Using Python, how can I tell the user they already entered a number in the list?


code: print result

rawDescription: Matching dates with regular expressions in Python?


code:
import re

dnsconf = open('dns.txt', 'rt')

x = []
for line in dnsconf:
    cont = re.findall('^local-data:\s+\"(\S+)\s+IN\s+(\S+)\s+(\S+)\"', line)
    if cont:
        x.append(cont)
        print cont

rawDescription: parsing a dns configuration file with python

description: Parsing a dns configuration file with python


code:
def predicateB(v):
    """
    some logic that eventually returns a True/False value
    """
    return False

predicateA.alwaysReturnsFalse = False
predicateB.alwaysReturnsFalse = True

for pred in [predicateA, predicateB]:
    print "Function:", pred.__name__
    print "Documentation:", pred.__doc__
    if pred.alwaysReturnsFalse:
        print "(This function always returns false)"

rawDescription: how to obtain a function's name and/or a description given a pointer

description: Obtain a function's name and/or a description given a pointer


code:
from Tkinter import *
import xml.etree.ElementTree as ET

rootframe = Tk()

def runScript(text = 'default text', row=None):
    entries = entries_by_row[row] if row is not None else []
    print 'runScript {}. Contents of entries: {}'.format(text, [entry.get() for entry in entries])

xmlString = '''
<window>
      <Tab id="tabpage5" name="Debugging" type="custom">
        <command dest="1" mode="CONFIG" unit="4" id="SET_TIMEOUT" type="COMMAND">
          <initiator name="Set Timeout" type="button" />
          <parameter editable="true" param_name="PARAM1">31536000</parameter>
        </command>
        <command dest="1" mode="CONFIG" unit="4" id="SET_thing" type="COMMAND">
          <initiator name="Set Timeout" type="button" />
          <parameter param_name="PARAM1" >31536000</parameter>
          <parameter param_name="PARAM2">5</parameter>
        </command>
        <command />
        </Tab>
</window>
'''

xmlRoot  = ET.fromstring(xmlString)

entries_by_row = []

for tab in xmlRoot.iter('Tab'):
    row = 0
    column = 0

    for command in tab.iter('command'):
        entries_by_row.append([])
        for tag in command.iter() :
            #not sure why command tag is here but skipping it
            if tag.tag == 'command':
                pass
                continue
            if tag.tag == 'initiator' and tag.attrib['type'] == 'button':
                    button = Button(rootframe, text=tag.attrib['name'], command=lambda row=row: runScript('nondefault text', row))
                    button.grid(row=row, column=column, sticky='w')
                    column +=1
            elif tag.tag == 'parameter':
                    entry = Entry(rootframe)
                    entry.insert(0,tag.text)
                    entry.grid(row=row, column=column)
                    column +=1
                    entries_by_row[-1].append(entry)
        row +=1
        column = 0

rootframe.mainloop()

rawDescription: Passing parameters to a dynamically created Button from an Entry widget in Tkinter


code:
from itertools import combinations
from collections import defaultdict

def coocurrence (common_entities):

    com = defaultdict(lambda : defaultdict(lambda: {'weight':0}))

    # Build co-occurrence matrix
    for w1, w2 in combinations(sorted(common_entities), 2):
        if w1 != w2:
            com[w1][w2]['weight'] += 1

    return com

print coocurrence('abcaqwvv')

rawDescription: Python: creating undirected weighted graph from a co-occurrence matrix


code:
class MyLineEdit(QtGui.QLineEdit):

    mousePressed = QtCore.pyqtProperty(QtGui.QMouseEvent)

    def __init__(self, value):

        super(MyLineEdit, self).__init__(value)

    def mousePressEvent(self, event):
        print 'forwarding to the main window'
        self.mousePressed.emit(event)

rawDescription: Add a click on QLineEdit

description: Add a click on QLineEdit


code:
import xml.etree.ElementTree
import collections

s = """\

        Height
        Width
        Depth

        10
        12
        5

        0
        3
        678

        5
        3
        4

"""

table = xml.etree.ElementTree.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    for key, value in collections.OrderedDict(zip(headers, values)).iteritems():
        print key, value

rawDescription: Pure python solution to convert HTML tables to readable plain text


code:
items=d.items() # List of tuples
random.shuffle(items)
for key, value in items:
    print key, value

keys=d.keys() # List of keys
random.shuffle(keys)
for key in keys:
    print key, d[key]

rawDescription: How to iterate through dict in random order in Python?

description: Iterate through dict in random order in Python


rawDescription: get all elements from list of lists in rows of 5

description: Get all elements from list of lists in rows of 5


code:
text = u"don\u2019t think"
textencode = text.encode('utf-8').split(" ")
print textencode[0]

rawDescription: Encode ASCII text

description: Encode ASCII text


code:
from datetime import datetime, time

utcnow = datetime.utcnow()
midnight_utc = datetime.combine(utcnow.date(), time(0))
delta = utcnow - midnight_utc
print delta.seconds # <-- careful

rawDescription: Number of seconds since the beginning of the day UTC timezone


rawDescription: Extract first date from string in a data frame


code:
for ch in root.xpath('/text()'):
    print ch

rawDescription: Parsing XML using lxml, unable to get text when there is another child node


code:
class VideoListView(ListView):
    # ..... your fields

    def get_queryset(self, **kwargs):
        # ... Your code ...
        actual_page = self.request.GET.get('page', 1)
        if actual_page:
            print actual_page
        # ... Your code ...

rawDescription: Get current page of pagination in view and manually set count of page


code:
data = [('abc','state','fsf', "val"), ('pqr','state','efg', "val2")]
import json
print json.dumps(data)

rawDescription: python list of tuples to javascript array of arrays

description: Python list of tuples to javascript array of arrays


code:
start_date = pd.to_datetime('2013-01-01 00:00:00')
end_date = pd.to_datetime('2013-01-01 00:00:07')
print df
print df[(df.ts > start_date) & (df.ts < end_date)].groupby(['uid','action'])['ts'].count().unstack('action').fillna(0)

rawDescription: Selecting rows in a given range from grouped object


code:
class MetaA(type):
    def __new__(cls, name, bases, dct):
        print 'MetaA.__new__'
        return type.__new__(cls, name, bases, dct)
    def __init__(cls, name, bases, dct):
        print 'MetaA.__init__'

class A(object):
    __metaclass__ = MetaA

rawDescription: What is the difference between type and type.__new__ in python?


code:
import itertools

def ranges(i):
    for a, b in itertools.groupby(enumerate(i), lambda (x, y): y - x):
        b = list(b)
        yield b[0][1], b[-1][1]

print(list(ranges([1, 2, 3, 4, 12])))

rawDescription: Python - buildung an Index

description: Python - buildung an Index


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open('this-stackoverflow-page.html'))

for anchor in soup('a'):
    print anchor.contents, anchor.get('href')

rawDescription: How to use Beautiful Soup to get plaintext and URLs from an HTML document?

description: Use Beautiful Soup to get plaintext and URLs from an HTML document


code:
result = []
for l in lst:
    flag=True
    for m in mapp:
        if m[0] < l < m[1]:
            result.append(mapp[m])
            flag = False
            break
    if flag:
        result.append(-1)
print result

rawDescription: Check if a list of numbers is in a certain range?


code:
class LernaSpider(CrawlSpider):
    """Our ad-hoc spider"""

    name = "lerna"

    def __init__(self, name=None, url=url, allow_follow='.*', deny_follow='', allow_extraction='.*', deny_extraction='', **kw):
        parsed_url = urlparse(url)
        domain = str(parsed_url.netloc)
        self.allowed_domains = [domain]
        self.start_urls = [url]
        self.rules = (
            # Extract links
            # and follow links from them (since no callback means follow=True by default).
            Rule(SgmlLinkExtractor(allow=allow_follow, deny=deny_follow)),

            # Extract links and parse them with the spider's method parse_item
            Rule(SgmlLinkExtractor(allow=allow_extraction, deny=deny_extraction), callback='parse_item'),
        )
        super(LernaSpider, self).__init__(name, **kw)

    def parse_item(self, response):
        print 'Crawling... %s' % response.url
        # more stuff here

rawDescription: Creating editable CrawlSpider rules in Scrapy


code:
from bulbs.rexster import Graph
from people import Person, Knows
g = Graph()
g.add_proxy("people", Person)
g.add_proxy("knows", Knows)
james = g.people.create(name="James")
julie = g.people.create(name="Julie")
knows = g.knows.create(james, julie)
print james.age
print knows.timestamp

rawDescription: Python Bulbs framework example of fget argument in a bulbs object init method


code:
def better_split(text,markersString):
    # simple and better way for 'for e in markerString...'
    markers = list(markersString)
    splited = []

    # there is no need to assign variable n, we all know it should be 1
    # n = 1

    def iter_text(text):
        # check if text is an empty string,
        # NOTE this `text` will cover `text` in upper function as to local scope,
        # so it's actually the text everytime iter_text() get,
        # not the one better_split() get.
        if not text:
            return
        # [UPDATES 2012-03-17 01:07 EST]
        # add a flag to judge if there are markers in `text`
        _has_marker = False
        for character in text:
            if character in markers:
                # set `_has_marker` to True to indicate `text` has been handled
                _has_marker = True
                point = text.find(character)
                word = text[:point]
                splited.append(word)
                # check if text[point] is legal, to prevent raising of IndexError
                while point + 1 <= len(text) and text[point] in markers:
                    point = point + 1
                text = text[point:]
                # break the loop when you find a marker
                # and change `text` according to it,
                # so that the new loop will get started with changed `text`
                break
        # if no marker was found in `text`, add the whole `text` to `splited`
        if not _has_marker:
            splited.append(text)
        else:
            iter_text(text)

    iter_text(text)

    print 'final splited = ', splited

rawDescription: Unexpected behavior of a function built to replace split ()


code:
import numpy as np

rows = 20
cols = 10
n = 3

#fixed number of ones per row in random places
print (np.argsort(np.random.rand(rows, cols)) < n).view(np.uint8)

#fixed number of ones per row in random contiguous place
data = np.zeros((rows, cols), np.uint8)
I = np.arange(rows*n)/n
J = (np.random.randint(0,cols-n+1, (rows,1))+np.arange(n)).flatten()
data[I, J] = 1
print data

rawDescription: Numpy array creation with patterns

description: Numpy array creation with patterns


code:
import sys
import glob
import serial

def serial_ports():

    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result

if __name__ == '__main__':

    VARIABLE = serial_ports()[0] #Assign first port as COM port
    ser = serial.Serial(
    port=VARIABLE,
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
    )

    print "Is port", VARIABLE , " open ?", ser.isOpen()

rawDescription: Assign variable to pyserial port

description: Assign variable to pyserial port


code:
from time import strftime
import re

ss = ('--||  ||:|||:||--||| \r\n'
      '#10 23:30 abcdef : \r\n'
      '802 12:25 xyz  :  \r\n'
      '\r\n'
      '#:35 11:18+14:39 sunny vale : sunny sea\r\n'
      '  651454451 drh:hdb 54:1\r\n'
      '    \r\n'
      ': 541514 oi:npvert654165:8\r\n'
      '#5415:v541564zervt\r\n'
      '#     ::    \r\n'
      '#::: :::\r\n'
      ' E\r\n')

regx = re.compile('(\r?\n(?!$))|(\r?\n$)')

def smartdispl(com,smth,regx = regx):
    print '\n%s\n%s\n%s' %\
          ('{0:{fill}{align}70}'.format(' %s ' % com,fill='=',align='^'),
           '\n'.join(repr(el) for el in smth.splitlines(1)),
           '{0:{fill}{align}70}'.format('',fill='=',align='^'))

logSys = 'poiu.txt'

with open(logSys,'wb') as f:
    f.write(ss)

with open(logSys,'rb') as f:
    smartdispl('content of the file '+logSys,f.read())

newLogSys = "%s_%s.csv" % (logSys,strftime("%Y_%m_%d_ %H_%M_%S"))

with open(logSys,'rb') as log, open(newLogSys,'wb') as nL:
    nL.writelines(lineI.replace(':' if lineI[0]=='#' else ' ', ',')
                  for lineI in log)

with open(newLogSys,'rb') as f:
    smartdispl('content of the file '+newLogSys,f.read())

rawDescription: Python Replacing white spaces in a text file with a comma


code:
import os

file_path = ""
for n in [1,2,3]:
    user_inp = raw_input('Please provide the filename: ')
    if os.path.isfile(user_inp):
        file_path = user_inp
        break
    print('Invalid file name, try again please')

if file_path:
    # Write ypur code.
    print "Processing file Name:", file_path
else:
    print "User not enters correct file name."

rawDescription: How to exit for loop once valid file name is provided and give 3 chances for correct input

description: Exit for loop once valid file name is provided and give 3 chances for correct input


code:
icon = u'\u25b2'
print icon

rawDescription: How to use Unicode characters in a python string

description: Use Unicode characters in a python string


code:
@overload((str, int))
def f(a, b):
    return a * b
@overload((int, int))
def f(a, b):
    return a + b
print f('a', 2)
print f(4, 2)
@overload((str,), (('foo', int), ('bar', float)))
def g(a, foo, bar):
    return foo*a + str(bar)
@overload((str,), (('foo', float), ('bar', float)))
def g(a, foo, bar):
    return a + str(foo*bar)
print g('a', foo=7, bar=4.4)
print g('b', foo=7., bar=4.4)

rawDescription: Decorator for overloading in Python

description: Decorator for overloading in Python


code:
def is_square(apositiveint):
  x = apositiveint // 2
  seen = set([x])
  while x * x != apositiveint:
    x = (x + (apositiveint // x)) // 2
    if x in seen: return False
    seen.add(x)
  return True

for i in range(110, 130):
   print i, is_square(i)

rawDescription: How could I check if a number is a perfect square?


code:
import json
obj = json.loads("""{"link": ["http://www.ponudadana.hr/Planinarski-dom-Kalnik-2-dana-s-doruckom-za-dvoje-za-149kn-umjesto-300kn-7482_1"], "title": ["Planinarski dom Kalnik - 2 dana s doru\u010dkom za dvoje za 149kn umjesto 300kn!"]}""")
obj['title']
print obj['title'][0]

rawDescription: How to scrap data with special characters?

description: Scrap data with special characters


code:
from django.conf import settings
settings.configure()
print settings.SECRET_KEY

rawDescription: List quickly all settings of your Django project


rawDescription: Extracting data from a list of tuples

description: Extracting data from a list of tuples


code:
import calendar

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
d, m, y = map(int, raw_input("Enter a date: ").split('/'))
weekday = calendar.weekday(y, m, d)
print days[weekday]

rawDescription: dd/mm/yyyy and day python without library at python

description: Dd/mm/yyyy and day python without library at python


code:
import string

myFilename = "countries.txt"

myTuples = []

myFile = open (myFilename, 'r')

for line in myFile.readlines():
    splitLine = string.split (line)
    code = splitLine [-3]
    country = string.join(splitLine[:-3])
    myTuples.append(tuple([country, code]))

myDict = dict(myTuples)
print myDict

rawDescription: Easiest way to convert two columns to Python dictionary


code:
print json_obj['list']['story'][0]['title']['$text']
print json_obj['list']['story'][1]['title']['$text']
print json_obj['list']['story'][2]['title']['$text']

rawDescription: Python for loop syntax

description: Python for loop syntax


code: print len(inputs), len(inputs[0]), inputs[0]

rawDescription: Apply a function to a list of dictionaries in python


code:
def func1():
    global inner_func
    inner_func = func2
    print 1

def func2():
    print 2

inner_func = func1

for i in range(5):
    inner_func()

rawDescription: Does Python optimize function calls from loops?


code:
from sqlalchemy import *
from sqlalchemy import create_engine, orm
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

metadata = MetaData()
Base = declarative_base()
Base.metadata = metadata

class Event(Base):
    __tablename__ = 'event'
    id                  = Column(Integer, Sequence("event_seq"), primary_key=True)
    name                = Column(String(32))
    def __repr__(self):
        return "%s(name=\"%s\",id=\"%s\")" % (self.__class__.__name__,self.name,self.id)

class EventsAssoc(Base):
    __tablename__ = 'events'
    id                  = Column(Integer, Sequence("events_seq"), primary_key=True)
    left_id = Column(Integer, ForeignKey('order.id'))
    right_id = Column(Integer, ForeignKey('event.id'))

#    order_id            = Column(Integer, ForeignKey('order.id'), primary_key=True)
#    event_id            = Column(Integer, ForeignKey('event.id'), primary_key=True)
    type                 = Column(Enum('corporate', 'personal', name='enum_ev_type'))

    event = relationship(Event, backref="order_assocs")

    def __repr__(self):
        return "%s(events=%r,id=\"%s\")" % (self.__class__.__name__,self.event,self.id)

class Order(Base):
    __tablename__ = 'order'
    id                  = Column(Integer, Sequence("order_seq"), primary_key=True)
    name = Column(String(127))
    events = relationship(EventsAssoc)
    def __repr__(self):
        return "%s(name=\"%s\",id=\"%s\")" % (self.__class__.__name__,self.name,self.id)

db = create_engine('sqlite:////temp/test_assoc.db',echo=True)

#making sure we are working with a fresh database
metadata.drop_all(db)
metadata.create_all(db)

sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

o = Order(name="order1")
ea_corp = EventsAssoc(type="corporate")
ea_corp.event = Event(name="Big Corporation")

ea_pers = EventsAssoc(type="personal")
ea_pers.event = Event(name="Person")

o.events.append(ea_corp)
o.events.append(ea_pers)
session.add(o)
session.flush()

query = session.query(Order).filter(and_(EventsAssoc.type=="corporate",Event.name=="Big Corporation"))

for order in query.all():
    print order
    print order.events

rawDescription: SQLAlchemy - Using Relationships to filter by class of row type


code:
l = [A(5), A(4), A(4)]
print list(set(l))
print list(set(l))[0].__class__  # ==> __main__.A. It's a object of class

rawDescription: efficient way to remove duplicates from list of custom objects in python

description: Efficient way to remove duplicates from list of custom objects in python


code:
print heapq.nlargest(n=3, iterable=y, key=y.get)
# ['c', 'a', 'b']

rawDescription: Obtain x'th largest item in a dictionary


rawDescription: Issues with Scatter size and position

description: Issues with Scatter size and position


code:
for c in sorted(range(10), reverse=True):
    print c

rawDescription: Counting backward from an integer using Python range built-in function, related to parse trees


code:
exitButton = Button(root)

def command_exit():
    print "exit"
    root.destroy()

exitButton.config(
    anchor=CENTER,
    font=("default", FONT_SIZE),
    text="Exit",

    # Leave colors
    background="black",
    foreground="white",

    # without border
    borderwidth=0,
    highlightthickness=0,

    # Enter colors
    activebackground="grey",
    activeforeground="white",

    # run on click
    command=command_exit
)

rawDescription: Python Tkinter loop to change button color on Enter and on Leave (python 3.4, Windows 10)


code:
class Base(object):

    def __new__(cls, category, *arguments, **keywords):
        for subclass in Base.__subclasses__():
            if subclass.category == category:
                return super(cls, subclass).__new__(subclass, *arguments, **keywords)
        raise Exception, 'Category not supported!'

class ChildA(Base):
    category = 'A'

    def __init__(self, *arguments, **keywords):
        print 'Init for Category A', arguments, keywords

    def func(self):
        print 'func for Category A'

class ChildB(Base):
    category = 'B'

    def func(self):
        print 'func for Category B'

if __name__ == '__main__':
    a = Base('A')
    a.func()
    print type(a)
    b = Base('B')
    b.func()
    print type(b)

rawDescription: Pythonic way to create dynamic class methods


code: print y     # Now [4,5,6]

rawDescription: Data-Binding in Python?

description: Data-Binding in Python


code:
import pandas as pd
df = pd.DataFrame({'x': xrange(10), 'y': xrange(10)})
df = df.ix[2::2]  # now we only have "time sample" every 2 ms
df['events'] = ''  # add a TTL channel
df.loc[3, 'events'] = 'kowabunga!'
df.loc[5, 'events'] = 'kowabunga2!'
df.loc[1, 'events'] = 'kowabunga3!'
df.sort(inplace=True)
print df

rawDescription: How can I insert a row into a dataframe, while preserving numerical order of row indexes?

description: Insert a row into a dataframe, while preserving numerical order of row indexes


code:
from robot.parsing import TestData
import sys

def main(path):
    suite = TestData(parent=None, source=path)
    tags = get_tags(suite)
    print ", ".join(sorted(set(tags)))

def get_tags(suite):
    tags = []

    if suite.setting_table.force_tags:
        tags.extend(suite.setting_table.force_tags.value)

    if suite.setting_table.default_tags:
        tags.extend(suite.setting_table.default_tags.value)

    for testcase in suite.testcase_table.tests:
        if testcase.tags:
            tags.extend(testcase.tags.value)

    for child_suite in suite.children:
        tags.extend(get_tags(child_suite))

    return tags

if __name__ == "__main__":
    main(sys.argv[1])

rawDescription: How to print available tags while using Robot Framework

description: Print available tags while using Robot Framework


code:
def get_printed_size(text, myfont):
    root = tk.Tk()
    font = tkFont.Font(family=myfont[0], size=myfont[1])
    (w,h) = (font.measure(text),font.metrics("linespace"))
    print "%s %s: (%s,%s)" % (myfont[0],myfont[1],w,h)
    return w

rawDescription: Get the printed length of a word by text width


code:
searchValue = 'test2'; found = []
for masterkey,mastervalue in defaultdict.iteritems():
    for childkey,childvalue in mastervalue.iteritems():
        if searchValue in childkey:
            found.append(childvalue)
print found

rawDescription: Nested dict in python, searhing based on inner key get inner value and parent key


rawDescription: Convert Python string to its ASCII representants


code:
try:
    retval = gfile.mount_enclosing_volume_finish(result)
except gio.Error, e:
    # If we run the tests too fast
    if e.code == gio.ERROR_ALREADY_MOUNTED:
        print ('WARNING: testfile is already mounted, '
        'skipping test')
        loop.quit()
        return
    raise
self.failUnless(retval)

rawDescription: gio: check if volume is mounted

description: Gio: check if volume is mounted


code:
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': 'D:\dev\djcode\mysite\media'}),

(r'^uploads/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': 'D:\dev\djcode\mysite\uploads'}),

rawDescription: Django Tinymce file manager

description: Django Tinymce file manager


code:
def noun(word):
    nouns = []
    for word in sentence.split():
      word, tag = word.split('/')
      if (tag.lower() == 'np'):
        nouns.append(word);
    return nouns

if __name__ == '__main__':
    nouns = []
    with open('tesu.txt', 'r') as file_p:
         for sentence in file_p.read().split('\n\n'):
              result = noun(sentence)
              if result:
                   nouns.extend(result)
    print nouns

rawDescription: chunks using python

description: Chunks using python


code:
for count, (key, value) in enumerate(my_dict.iteritems(), 1):
    print key, value, count

rawDescription: how to get item index or number along with key,value in dict

description: Get item index or number along with key,value in dict


code:
data = l.split('(', 1)[1].split(')')[0].split(',')
for d in data:
    print d.strip().replace(' ',',')

rawDescription: Combine results from regex to make x,y pairs


code:
import hashlib
import base64
url = 'http://stackoverflow.com/questions/ask'
print base64.urlsafe_b64encode(hashlib.md5(url).digest()[-4:])[:-2]

rawDescription: How do I use Python to pack a big integer treating four characters as an unsigned long in network byte order as Ruby's .pack("N") does?

description: Use Python to pack a big integer treating four characters as an unsigned long in network byte order as Ruby's .pack("N") does


code:
class SubclassStatic(TestStatic):
    @staticmethod
    def do_something():
        print 'I am the subclass'

s = SubclassStatic()
s.use_me()

rawDescription: calling static method from inside the class

description: Calling static method from inside the class


code:
np.random.seed(1)
N = 800
DD = dict()
R = range(N)
for i in xrange(N):
    DD[i] = dict()
    S = np.random.permutation(R)
    S = S[:N/4]
    for j in S:
        DD[i][j] = np.random.randn(1)[0]

K = MSK(DD, R)
import cProfile
cProfile.runctx("A = K.M * K.M.T", globals(), locals())
print A.todense()

rawDescription: How to efficiently compute the inner product of two dictionaries

description: Efficiently compute the inner product of two dictionaries


code:
from StringIO import StringIO
from csv import DictReader
from classes import Customer, Order

data1 = """
first_name surname address notes purchase_order order_date
"Bob" "Smith" "123 Lucky Street" "Bad customer" "123ABC", 2013/10/20
"Zoe" "Jackson" "5 Mountain View Street" "Good customer" "abc211" 2014/01/01
""".strip()

data2 = """
first_name surname address phone_home phone_mobile purchase_order order_date total
"Bob" "Smith" "123 Lucky Street" "12345678" "1234567890" "123ABC" 2013/10/20, $100
"Zoe" "Jackson" "5 Mountain View Street" "87654321" "0987654321" "abc211" 2014/01/01 $1000
""".strip()

buf1 = StringIO(data1)
buf2 = StringIO(data2)

reader = DictReader(buf1, delimiter=" ")
for rec in reader:
    print rec
    customer = Customer(**rec)
    print customer.report()
    order = Order(**rec)
    print order
    print order.report()

print "---next one comes---"

reader = DictReader(buf2, delimiter=" ")
for rec in reader:
    print rec
    customer = Customer(**rec)
    print customer.report()
    order = Order(**rec)
    print order
    print order.report()

rawDescription: Parsing CSV data based on header fields using Pyparsing


code:
from multiprocessing.pool import ThreadPool

def foo(word, number):
    print word*number
    return number

def starfoo(args):
    """

    We need this because map only supports calling functions with one arg.
    We need to pass two args, so we use this little wrapper function to
    expand a zipped list of all our arguments.

    """
    return foo(*args)

words = ['hello', 'world', 'test', 'word', 'another test']
numbers = [1,2,3,4,5]
pool = ThreadPool(5)
# We need to zip together the two lists because map only supports calling functions
# with one argument. In Python 3.3+, you can use starmap instead.
results = pool.map(starfoo, zip(words, numbers))
print results

pool.close()
pool.join()

rawDescription: How to obtain the results from a pool of threads in python?

description: Obtain the results from a pool of threads in python


rawDescription: Can you split a set into equal parts?

description: Split a set into equal parts


code:
import itertools
print list(itertools.takewhile(lambda i:i*i < 10,itertools.count()))

rawDescription: Python SyntaxError when creating a list using a generator


code:
import shelve

sh = shelve.open("myshelf")

sh["foo"] = (1,2,3,4)
sh["bar"] = "I like spam"

sh.close()

sh = shelve.open("myshelf")
print sh["foo"]
print sh.keys()

rawDescription: Modify variables in a different module

description: Modify variables in a different module


code:
from collections import Counter
print [key for key, count in Counter(words).items() if count == 3]

rawDescription: Printing items in a list that occur a certain number of times?


code:
class B(object):
    def __eq__(self, other):
        print "B.__eq__()"
        return False

class A(object):
    def __eq__(self, other):
        print "A.__eq__()"
        return False

a = A()
b = B()
a == b
b == a

rawDescription: Optimising Python dictionary access code


code:
for w, wvals in data.items():
    for x, xvals in wvals.items():
        for y, yvals in xvals.items():
            for z, zvals in yvals.items():
                print '%s:%s:%s:%s:%s' % (
                    w, x, y, z,
                    ':'.join("%s=%r" % pair for pair in d.items()))

rawDescription: How to os.walk deep defaultdict for values?

description: Os.walk deep defaultdict for values


code:
import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command help')

init_parser = subparsers.add_parser('init', help='do the init stuff')

snap_parser = subparsers.add_parser('snap', help='do the snap stuff')
snap_parser.add_argument('--file', '-f', required=True)

check_parser = subparsers.add_parser('check', help='do the check stuff')
check_parser.add_argument('--file', '-f', required=True)

args = parser.parse_args()

print args

rawDescription: How to make positional argument optional in argparser based on some condition in python

description: Make positional argument optional in argparser based on some condition in python


code:
s="""{
  "data": {
    # Some information about field 1
    # on multiple lines
    # threeeeeeeeecomment
    "field1": "XXXXXXXXXX"

    # Some more info on a single line
    "field2": "XXXXXXXXXXX",

    "field3": "#this would be ignored"
  }
}"""
from itertools import groupby

comments =[[i for i in j if i.strip().startswith('#')] for _,j in groupby(s.split('\n'),lambda x: x.strip().startswith('#'))]

for i,j in enumerate([m for m in comments if m],1):
        l=[t.strip(' #') for t in j]
        print 'group {} :{}'.format(i,' & '.join(l))

rawDescription: Regex to extract multiline hash comments


code:
# rest as before
from scipy import ndimage
tic = time.time()
new_result = np.zeros(im.shape)
coords = np.array([yy,xx,np.zeros(im.shape[:2])])
for d in range(im.shape[2]):
    new_result[:,:,d] = ndimage.map_coordinates(im,coords,order=1)
    coords[2] += 1
toc = time.time()
print "interpolation time:",toc-tic

rawDescription: Speeding up linear interpolation of many pixel locations in NumPy


code:
for name, number, weight in elements:
    print '{:>10}: {:3d} {:7.3f}'.format(name, number, weight)

rawDescription: Using for loops with nested loops in python


code: print re.findall(r'\s\w+', words)

rawDescription: Difference between re.search() and re.findall()


code:
def f(x):
    print(x == 'Manual').all()

print df.groupby("Team")['Method'].apply(f)
True
False
False

rawDescription: How to groupby or exclude based on value counts?

description: Groupby or exclude based on value counts


code:
def task(depth):
    print 'started depth %d' % (depth, )
    if depth > 10:
        return depth
    else:
        task(depth + 1)

rawDescription: Python thread pools - tasks that create subtasks and wait on them


code:
from ftplib import FTP
import shelve

olddir = shelve.open('filelist.shl')   # create a persistent dictionary

ftp = FTP('ftp1.freebsd.org')
ftp.login()

result = []
ftp.dir(result.append)
newdir = set(result[1:])

print ' New Files '.center(50, '=')
for line in sorted(set(newdir) - set(olddir)):
    print line
    olddir[line] = ''
print ' Done '.center(50, '=')
olddir.close()

rawDescription: Python programming with FTP and lists

description: Python programming with FTP and lists


code:
def click_dim(self, dim):
    print dim
    if dim == "2D":
        self.updatePlotAdd2d()
    elif dim == "3D":
        self.updatePlotAdd3d()
    else:
        self.updatePlotAdd4d()

rawDescription: Matplotlib Radiobutton doesn't work anymore after clf()


code:
for l in sys.stdin:
    l = l.decode('utf-8', 'replace')
    print l

rawDescription: delays in reading stdin with codecs

description: Delays in reading stdin with codecs


code:
a = np.arange(5)
print a[nt]
# [0 1 2 3 4]
print a[-nt]
# []

rawDescription: python/numpy: negate or complement a slice

description: Python/numpy: negate or complement a slice


code:
def go():
    go.first = [1,2,3,4,5,1]
    return go

second = [6,7,8,9,10]

print map(sum, izip_longest(go().first, second, fillvalue=0))

rawDescription: Calling a list from a function in Python


code:
def slice_reading(filepath,y,z,x=0):
    # x : number of lines to skip before the periodical treatment
    # y : number of lines to periodically skip
    # z : number of lines to periodically print
    with open('poem.txt') as f:
        lines = f.readlines()
        lgth = len(lines)

    if lgth > x+y:
        for a in xrange(x+y,lgth,y+z):
            print lines[a:a+z]
    else:
        print 'Not enough lines before lines to print'

slice_reading('poem.txt',7,3,5)

rawDescription: Using python to process a chunk of a file every x lines


code:
def compare_triples(a, b):
    ret=cmp(a[0], b[0])
    if ret: return ret
    ret=cmp(b[2], a[2])
    if ret: return ret
    return cmp(a[1], b[1])

for i in m: print i
print "-" * 79
m2=sorted(m, cmp=compare_triples)
for i in m2: print i

rawDescription: Sort string-matrix [[a, b, c], ...] by a, -c, b, maintaining order?


code:
import sqlite3

conn = sqlite3.connect(":memory:")
c = conn.cursor()

c.execute("create table firms (founded, hq, name, rev, size, type)")
c.execute("insert into firms ( name ) values (?) ",("bar", ))
conn.commit()

def update(information):
    updates = ', '.join(["`"+field+"`" + '=:'+field for field in information.keys() if field != 'name'])
    where = ' WHERE name == :name'
    values = information
    query = 'UPDATE firms SET ' + updates + where
    c.execute(query, values)
    conn.commit()

update(dict(name='bar', founded='1062', rev='1 MILLION DOLLARS!'))
print c.execute('select * from firms').fetchall()

rawDescription: Sqlite thinks I lack bindings

description: Sqlite thinks I lack bindings


code:
def rhythmbox_owner_changed(new_owner):
    if new_owner == '':
        print 'Rhythmbox is no longer running'
    else:
        print 'Rhythmbox is now running'

bus.watch_name_owner('org.gnome.Rhythmbox')

rawDescription: Check if Rhythmbox is running via Python


code: print "Hi, my name is", name

rawDescription: Python 2.7: % string format vs. calling variable outside string?


rawDescription: How to make nntplib author name human readable?

description: Make nntplib author name human readable


code:
my_num = 123456.7890
print my_num
print '{0:e}'.format(my_num)

rawDescription: typing e exponent in python

description: Typing e exponent in python


code:
p = subprocess.Popen(["./AO_FelixStrategy_UnitTest",
                      "--bats", "31441", "--chix", "12467",
                      "--enxutp", "31884", "--turq", "26372",
                      "--symbol", "SOGN", "--target_date", '2009-Oct-16'],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)
output = p.communicate('S\nL\n')[0]
print output

rawDescription: why does python.subprocess hang after proc.communicate()?

description: Why does python.subprocess hang after proc.communicate()


code:
class mytest:
    def action(self):
        print 'Original'

a = mytest()
a.action()

tmp = a.action

def apply(f):
    print 'Not the ',
    return f

a.action = apply(a.action)
a.action()

a.action = tmp
a.action()

rawDescription: Is there any way you can get back to the original function?


code:
#!/usr/bin/env python

import readline

readline.clear_history()
readline.add_history('foo')
readline.add_history('bar')

while 1:
    print raw_input('> ')

rawDescription: Howto do python command-line autocompletion but NOT only at the beginning of a string


code:
yaml.dump([1L, 1L])
yaml.dump([1L, 1L], Dumper=ExplicitDumper)

rawDescription: Is it possible to emit valid YAML with anchors / references disabled using Ruby or Python?


code:
f = open(sys.argv[1], 'rb')
data = f.read()
f.close()
if data[:2] == '\xff\xfe':
    data = data.decode('utf16').encode('ascii')
# ilines is a generator which produces newline-terminated strings
ilines = (line + '\n' for line in data.splitlines())
mb_toc_urlpart = "%20".join(
    str(x) for x in calculate_mb_toc_numbers(filter_toc_entries(ilines))        )
print mb_toc_urlpart

rawDescription: Python kludge to read UCS-2 (UTF-16?) as ASCII


code:
all_data = [float(row[1]) for row in csvin]
print "differences: ", [next - curr for next, curr in zip(all_data[1:], all_data[: -1])]

rawDescription: How to operate with values in the same column in .csv files

description: Operate with values in the same column in .csv files


rawDescription: Python csv writer truncates number format


code:
#!/usr/bin/python

import time,readline,thread
import sys,struct,fcntl,termios

def blank_current_readline():
    # Next line said to be reasonably portable for various Unixes
    (rows,cols) = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ,'1234'))

    text_len = len(readline.get_line_buffer())+2

    # ANSI escape sequences (All VT100 except ESC[0G)
    sys.stdout.write('\x1b[2K')                         # Clear current line
    sys.stdout.write('\x1b[1A\x1b[2K'*(text_len/cols))  # Move cursor up and clear line
    sys.stdout.write('\x1b[0G')                         # Move to start of line

def noisy_thread():
    while True:
        time.sleep(3)
        blank_current_readline()
        print 'Interrupting text!'
        sys.stdout.write('> ' + readline.get_line_buffer())
        sys.stdout.flush()          # Needed or text doesn't show until a key is pressed

if __name__ == '__main__':
    thread.start_new_thread(noisy_thread, ())
    while True:
        s = raw_input('> ')

rawDescription: Reading input from raw_input() without having the prompt overwritten by other threads in Python


code:
List = ['android', 'ios', 'android', '', 'none', 'android']
OS_list = ['android', 'ios', 'windows']

y=set(List)
print [i for i in OS_list if i in y]

rawDescription: Python List: Pythonic way to get unique items in given List from a given Set


code:
cycled = itertools.cycle(lst)
for i in range(index + 1):
    print i, next(cycled)

rawDescription: Relooping the list

description: Relooping the list


code:
d = {'hi':[1,2,3,4], 'bye':[5,6,7,8]}
t = 2
print {k:[j for i in zip(*[v for _ in range(t)]) for j in i] for k, v in d.items()}
print {k:v*t for k, v in d.items()}

rawDescription: Extending dictionary list values in a certain way


code:
import os

filenames =['testfile1','testfile2']

for file in filenames:
    if os.path.isfile(file+'.csv'):
        print "File "+ file + ".csv exists."
    else:
        print "File "+ file + ".csv does not exist."

rawDescription: Using a reference list to find specific files by name


code:
def enum(classname, values):
    class EnumMeta(type):
        def __iter__(cls):
            return cls._instances.itervalues()

    class EnumType(object):
        __metaclass__ = EnumMeta
        _instances = {}
        _next_id = 0
        def __init__(self, value):
            self.value = value
            self.id = type(self)._next_id
            type(self)._next_id += 1

        def instance(self, value):
            return type(self)._instances[value]

    cls = type(classname, (EnumType, ), {})
    instances = dict((value, cls(value)) for value in values)
    cls._instances = instances

    def __new__(cls, value):
        raise TypeError('No more instances allowed')

    cls.__new__ = staticmethod(__new__)
    return cls

Genre = enum('Genre', ['scifi', 'comic', 'science'])

for item in Genre:
    print item, item.value, item.id
    assert(item is Genre(item.value))
    assert(item is item.instance(item.value))

Genre('romance')

rawDescription: python enumeration class for ORM purposes

description: Python enumeration class for ORM purposes


rawDescription: Determine corner coords from a set of coords on a page Python / OpenCV