code:
import gevent
from gevent.event import AsyncResult
a = AsyncResult()

def f1():
    gevent.sleep(3)
    a.set({'first':'Hello', 'second':'World'})

def f2():
    print a.get()['first']

def f3():
    print a.get()['second']

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2),
    gevent.spawn(f3),
])

rawDescription: python gevent asyncResult send different value to coroutine

description: Python gevent asyncResult send different value to coroutine


code:
import keylogger
import time

now = time.time()
done = lambda: time.time() > now + 60
def print_keys(t, modifiers, keys): print "%.2f   %r   %r" % (t, keys, modifiers)

keylogger.log(done, print_keys)

rawDescription: Python 2.7: Detect DELETE key pressed on raw_input


code:
im = open('Tiff.tif','r')
image_data = im.read()
im.close()

#lets look at the first few characters
for char in image_data[:64]:
    print ord(char),  #need to use ord so we can see the number

rawDescription: Converting an image instance (file) to an array (python)


code: print ''.join(txt)

rawDescription: Removing html tags using python?

description: Removing html tags using python


code:
def getlohiint():
    while True:
        lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
        try:
            low, high = [int(x) for x in lohi.split()]
        except ValueError:
            # either not integers or not exactly 2 numbers entered.
            print "You must enter exactly 2 numbers here"
            continue

        if low <= 2 and high <= 1000 and low < high:
            # valid input, return
            return low, high

        if low > 2:
            print 'The minimum must be 2 or lower'
        if high > 1000:
            print 'The maximum must be 1000 or lower'
        if low >= high:
            print 'The maximum must be greater than the minimum'

rawDescription: get raw input that is between a set of numbers with some checks

description: Get raw input that is between a set of numbers with some checks


code:
from subprocess import Popen, PIPE

hostIP = "87.215.133.109"
cmd = "/usr/local/bin/geo-ip.pl --short %s" % hostIP
output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]

## alternate form ##
# cmd = ["/usr/local/bin/geo-ip.pl, "--short", hostIP]
# output = Popen(cmd, stdout=PIPE).communicate()[0]

print output.strip()
# Netherlands

rawDescription: Change DenyHosts report: Call external command from Python


code:
import inspect

def func2():
    cframe = inspect.currentframe()
    func = inspect.getframeinfo(cframe.f_back).function
    print 'called from ' + func

def func1():
    func2()

func2()
func1()

rawDescription: Get the name of an outer function from inner function in python


code: print '[' + ',\n '.join(str(x) for x in grid) + ']'

rawDescription: Printing List within list in python line by line


code:
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.kijiji.ca/v-2-bedroom-apartments-condos/city-of-halifax/clayton-park-west-condo-style-luxury-2-bed-den/1016364514")
soup = BeautifulSoup(driver.page_source , 'html.parser')
print soup.find_all("span",{"class":"ad-visits"})

rawDescription: Using Requests and BeautifulSoup - Python returns tag with no text


code:
print 'c:\testfile.xml'
print r'c:\testfile.xml'   #raw string works fine

rawDescription: Replace text in a file

description: Replace text in a file


code:
def somecalulation(x):
    return (df['col'] == x).sum()

print somecalulation(1)
5
print somecalulation(2)
3

rawDescription: Pandas, Get count of a single value in a Column of a Dataframe


code:
import csv
import sys

input_file, output_file = sys.argv[1:3]

with open(input_file, 'rb') as inp_f, open(output_file, 'wb') as out_f:
    csv_writer = csv.writer(out_f)
    for row in csv.reader(inp_f):
        try:
            csv_writer.writerows(
                item for item in zip(reversed(row[0].split('+')), row[1:]))
        except IndexError:
            print 'bad row encountered', row
            raise

rawDescription: Reformat text file to csv that includes two different delimiter in python


code:
class Camera():
    def __init__(self):
        print "__instance created"

    def someFunc(self):
        print "Cool stuff here!"

c1 = Camera()

rawDescription: Python class service

description: Python class service


code:
import zbar
import Image

scanner = zbar.ImageScanner()

scanner.parse_config('enable')

img = Image.open("br.png").convert('L')
width, height = img.size
stream = zbar.Image(width, height, 'Y800', img.tostring())

scanner.scan(stream)

for symbol in stream:
    print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data

rawDescription: How to get type of Encoding Style of QR/bar-code with python-qrtools/ZBar?

description: Get type of Encoding Style of QR/bar-code with python-qrtools/ZBar


code:
# ... snip ...
import subprocess
con, addr = s.accept()
while True:
    datagram = con.recv(1024)
    if not datagram:
        break
    print "Rx Cmd:", datagram
    if settings.has_key(datagram):
        print "Launch:", settings[datagram]
        process = subprocess.Popen(settings[datagram]+" &", shell=True, stdout=subprocess.PIPE)
        stdout, stderr = process.communicate()
        con.send(stdout)
    con.close()
s.close()

rawDescription: Send output from a python server back to client


code:
import getpass

def custom_fallback(prompt="Password: ",stream=None): #Clone of parameters from getpass.fallback_getpass
    print "Custom message." #Custom message goes here
    return getpass._raw_input(prompt) #Use getpass' custom raw_input function for security

getpass.fallback_getpass = custom_fallback #Replace the getpass.fallback_getpass function with our equivalent

password = getpass.getpass("Password: ") #Prompt for password

rawDescription: Catch Warning in Python 2.7 Without Stopping Part of Progam


code: print  the_table.properties() # hint it's a dictionary do: type(the_table.properties() <type 'dict'>

rawDescription: Matplotlib table formatting

description: Matplotlib table formatting


code:
n = 4
num_triu_entries = n * (n + 1) / 2

triu_index_matrix = np.zeros([n, n], dtype=int)
triu_index_matrix[np.triu_indices(n)] = np.arange(num_triu_entries)
triu_index_matrix[np.triu_indices(n)[::-1]] = np.arange(num_triu_entries)

triu_vec = T.fvector()
triu_mat = triu_vec[triu_index_matrix]

f_triu_mat = theano.function([triu_vec], triu_mat)

print f_triu_mat(np.arange(1, num_triu_entries + 1).astype(np.float32))

# [[  1.   2.   3.   4.]
#  [  2.   5.   6.   7.]
#  [  3.   6.   8.   9.]
#  [  4.   7.   9.  10.]]

rawDescription: Initializing a symmetric Theano dmatrix from its upper triangle


code:
print ' '.join(map(str, indices(array)))
# 1 4 11

rawDescription: How can I get the list slice using a list of indexes in Python?

description: Get the list slice using a list of indexes in Python


code:
import re
s = re.sub(r'\\', r'/', r'\\test.abc.com\path1\path1_1\123\ubntu')
print s

rawDescription: To replace all backslashes with forward slashes using sed or python


code:
from pyparsing import nestedExpr

text = '(BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quotedprintable" 1207 50 NIL NIL NIL NIL))'

print nestedExpr().parseString(text)

rawDescription: parsing parenthesized list in python's imaplib

description: Parsing parenthesized list in python's imaplib


code:
def f (another_func): return another_func()
def g (): print "blah"
f(g)

rawDescription: Python OOP: Practice passing results of one method into another


code:
dicts=[]
dicts.append({"1":[{'q': ['Data'], 'q1': '110'}]})
dicts.append({"2":[{'q2':["other Data"], "q3" : "exp"},{'q2':["other Data2"], "q3" : "exp2"}]})

a=[[{key: j} for key in d2 for j in d2[key]] for d2 in dicts ]

nmax=max(len(x) for x in a)

newdicts=[dict() for i in range(nmax)]

for i in range(nmax):
    for j in range(len(a)):
        if i < len(a[j]):
            newdicts[i].update(a[j][i])

for i in newdicts:
    print i

rawDescription: Zip Two dict contain a list in Python

description: Zip Two dict contain a list in Python


code:
import SocketServer

class DebugTCPServer(SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, debug=True):
        self.debug = debug
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=True)

class DebugMETCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        # self.server is an instance of the DebugTCPServer
        DEBUG = self.server.debug
        self.data = self.request.recv(1024).strip()
        if DEBUG:
            print "{} wrote:".format(self.client_address[0])
        r = MExpressHandler(self.data, False)

server = DebugTCPServer((HOST, PORT), DebugMETCPHandler, debug=True)

rawDescription: send a variable to a TCPHandler in python

description: Send a variable to a TCPHandler in python


rawDescription: Accessing multiple values from a function within a function


code:
allsports = ['Basketball','Football','Other','Baseball','Handball',
             'Soccer','Volleyball','I do not like sport']
sports = []
reader = csv.reader(open('copy-john.csv'))
for row in reader:
    if reader.line_num: sports.append(s[3])
    print "%-14s|%-10s|%-5s|%-11s" % tuple(s)
for s in allsports: print s, sports.count(s)

rawDescription: python csv into dictionary

description: Python csv into dictionary


rawDescription: smartest way to join two lists into a formatted string

description: Smartest way to join two lists into a formatted string


code:
from EchoServer_client import *
import sys, time

loc  = EchoServerLocator()
port = loc.getEchoServer(url='http://localhost:7000/echo')

print "Echo: ",
msg = EchoRequest()
msg.Value = "Is there an echo in here?"
rsp = port.Echo(msg)
print rsp.Value

rawDescription: Are there any working examples of Zolera SOAP Infrastructure (ZSI)?


code:
from datetime import datetime
import sys
print sys.modules[datetime.__module__].__doc__

rawDescription: How to get a reference to the module of a class

description: Get a reference to the module of a class


code:
import re

# "fix" a number in exponential format
def fixexp(foo):
  # shift the decimal point
  foo = re.sub(r"(\d)\.", r".\1", foo)
  # add 0 for positive numbers
  foo = re.sub(r" \.",    r"0.",  foo)
  # increase exponent by 1
  exp = re.search(r"E([+-]\d+)", foo)
  newexp = "E{:+03}".format(int(exp.group(1))+1)
  foo = re.sub(r"E([+-]\d+)", newexp, foo)
  return foo

nums = [ -0.704411727284, -1.66021493805, 0.00964452299466, 0.0000000229380762349, -0.00000103417103118, -0.0000269314547877, 0.00140398741573 ]

# print the numbers in rows of 4
line = ""
for i in range(len(nums)):
  num = "{:18.11E}".format(nums[i])
  num = fixexp(num)
  line += num
  if (i%4 == 3 or i == len(nums)-1):
    print line
    line = ""

rawDescription: String format: Start scientific notation with 0. for positive number, with -. for negative number


code:
for word in generate_words('out', 5):
    print word

rawDescription: Make a list of words from given characters


code:
from ConfigParser import ConfigParser

config = ConfigParser()
config.read('config.ini')

print config.sections()
# ['section1', 'section2']

print config.items('section2')
# [('s', 'foo')]

rawDescription: Python: Parsing INI-style configuration files?


code:
for g, inds in itertools.groupby(enumerate(A), key=operator.itemgetter(1)):
     print g, list([i[0] for i in inds])

rawDescription: groupby on sparse matrix with scipy

description: Groupby on sparse matrix with scipy


code:
from inspect import getouterframes, currentframe

def make_call():
    print getouterframes(currentframe())[-1][-2][0]

class Work(object):
    def pick_up_phone(self):
        make_call()

class Home(object):
    def pick_up_phone(self):
        make_call()

Home().pick_up_phone()
Work().pick_up_phone()

rawDescription: How to get the calling class name inside a function

description: Get the calling class name inside a function


rawDescription: Splitting a list in python

description: Splitting a list in python


code:
gen = words(f)
for word in gen:
    if condition(word):
        print word

rawDescription: Python: read one word per line of a text file


code:
from google.appengine.ext import db

k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')
_app = k.app()
path = []
while k is not None:
  path.append(k.id_or_name())
  path.append(k.kind())
  k = k.parent()
path.reverse()
print 'app=%r, path=%r' % (_app, path)

rawDescription: How to decode a Google App Engine entity Key path str in Python?

description: Decode a Google App Engine entity Key path str in Python


code:
import numpy, scipy
from scipy.signal import square, sawtooth, correlate
from numpy import pi, random

period = 1.0                            # period of oscillations (seconds)
tmax = 10.0                             # length of time series (seconds)
nsamples = 1000
noise_amplitude = 0.6

phase_shift = 0.6*pi                   # in radians

# construct time array
t = numpy.linspace(0.0, tmax, nsamples, endpoint=False)

# Signal A is a square wave (plus some noise)
A = square(2.0*pi*t/period) + noise_amplitude*random.normal(size=(nsamples,))

# Signal B is a phase-shifted saw wave with the same period
B = -sawtooth(phase_shift + 2.0*pi*t/period) + noise_amplitude*random.normal(size=(nsamples,))

# calculate cross correlation of the two signals
xcorr = correlate(A, B)

# The peak of the cross-correlation gives the shift between the two signals
# The xcorr array goes from -nsamples to nsamples
dt = numpy.linspace(-t[-1], t[-1], 2*nsamples-1)
recovered_time_shift = dt[xcorr.argmax()]

# force the phase shift to be in [-pi:pi]
recovered_phase_shift = 2*pi*(((0.5 + recovered_time_shift/period) % 1.0) - 0.5)

relative_error = (recovered_phase_shift - phase_shift)/(2*pi)

print "Original phase shift: %.2f pi" % (phase_shift/pi)
print "Recovered phase shift: %.2f pi" % (recovered_phase_shift/pi)
print "Relative error: %.4f" % (relative_error)

# OUTPUT:
# Original phase shift: 0.25 pi
# Recovered phase shift: 0.24 pi
# Relative error: -0.0050

# Now graph the signals and the cross-correlation

from pyx import canvas, graph, text, color, style, trafo, unit
from pyx.graph import axis, key

text.set(mode="latex")
text.preamble(r"\usepackage{txfonts}")
figwidth = 12
gkey = key.key(pos=None, hpos=0.05, vpos=0.8)
xaxis = axis.linear(title=r"Time, \(t\)")
yaxis = axis.linear(title="Signal", min=-5, max=17)
g = graph.graphxy(width=figwidth, x=xaxis, y=yaxis, key=gkey)
plotdata = [graph.data.values(x=t, y=signal+offset, title=label) for label, signal, offset in (r"\(A(t) = \mathrm{square}(2\pi t/T)\)", A, 2.5), (r"\(B(t) = \mathrm{sawtooth}(\phi + 2 \pi t/T)\)", B, -2.5)]
linestyles = [style.linestyle.solid, style.linejoin.round, style.linewidth.Thick, color.gradient.Rainbow, color.transparency(0.5)]
plotstyles = [graph.style.line(linestyles)]
g.plot(plotdata, plotstyles)
g.text(10*unit.x_pt, 0.56*figwidth, r"\textbf{Cross correlation of noisy anharmonic signals}")
g.text(10*unit.x_pt, 0.33*figwidth, "Phase shift: input \(\phi = %.2f \,\pi\), recovered \(\phi = %.2f \,\pi\)" % (phase_shift/pi, recovered_phase_shift/pi))
xxaxis = axis.linear(title=r"Time Lag, \(\Delta t\)", min=-1.5, max=1.5)
yyaxis = axis.linear(title=r"\(A(t) \star B(t)\)")
gg = graph.graphxy(width=0.2*figwidth, x=xxaxis, y=yyaxis)
plotstyles = [graph.style.line(linestyles + [color.rgb(0.2,0.5,0.2)])]
gg.plot(graph.data.values(x=dt, y=xcorr), plotstyles)
gg.stroke(gg.xgridpath(recovered_time_shift), [style.linewidth.THIck, color.gray(0.5), color.transparency(0.7)])
ggtrafos = [trafo.translate(0.75*figwidth, 0.45*figwidth)]
g.insert(gg, ggtrafos)
g.writePDFfile("so-xcorr-pyx")

rawDescription: Find phase difference between two (inharmonic) waves


code:
# Built-in types such as int or object do not have __dict__ by
# default. __dict__ is normally obtained by inheriting from a
# dictless type using the class statement.  Checking for the
# existence of __dict__ is an indication of a class instance.
#
# Caveat: a built-in or extension type can still request instance
# dicts using tp_dictoffset, and a class can suppress it with
# __slots__.
def is_class_instance(o):
    return hasattr(o, '__dict__')

# A reliable approach, but one that is also more dependent
# on the CPython implementation.
Py_TPFLAGS_HEAPTYPE = (1L<<9)       # Include/object.h
def is_class_instance(o):
    return bool(type(o).__flags__ & Py_TPFLAGS_HEAPTYPE)

rawDescription: In python at runtime determine if an object is a class (old and new type) instance


code:
form_list = ['blah', 12, [], {}, 'yeah!']
print map(type, form_list)

rawDescription: Best way to find out the object type of each item in a list

description: Find out the object type of each item in a list


code:
result = p4.run("fstat", "<FileName>")
print result

rawDescription: P4python: get changelist number of latest revision of file checked in in perforce by python code


code:
root='/path/to/my/dir'
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print dirlist

rawDescription: Python folder names in the directory

description: Python folder names in the directory


code:
import collections

def get_ip_address(start_time, end_time):
    global d_entries

    matching_ip = set()
    for k, v in d_entries.items():
        for timestamp in v:
            if start_time <= timestamp <= end_time:
                matching_ip.add(k)

    return matching_ip

ip_list = [
"10.1.1.10 1441110489",
"10.1.1.15 1441110490",
"10.1.1.10 1441110491",
"10.1.1.11 1441110492",
"10.1.1.10 1441110492",
"10.1.1.11 1441110493"]

d_entries = collections.defaultdict(list)

for ip_entry in ip_list:
    ip, timestamp = ip_entry.split(" ")
    d_entries[ip].append(int(timestamp))

print get_ip_address(1441110490, 1441110492)

rawDescription: dynamically create and search a dictionary of IPs with their seen timestamps

description: Dynamically create and search a dictionary of IPs with their seen timestamps


code:
import re
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.zomato.com/ncr/salad-days-dlf-cyber-city-gurgaon")

mapping = {
    "icon-font-level-9": 5.0,
    "icon-font-level-8": 4.5,
    "icon-font-level-6": 3.5
    # ... TODO
}

pattern = re.compile(r"icon-font-level-\d+")
for review in driver.find_elements_by_css_selector("div[itemprop=review]"):
    author = review.find_element_by_css_selector("div[itemprop=author] div[itemprop=name] a").text

    rating_class = review.find_element_by_xpath(".//div[. = 'Rated']").get_attribute('class')
    rating = mapping.get(pattern.search(rating_class).group(0))
    print author, rating

rawDescription: How can get text which is a symbol in a tag using selenium and python?


code:
def h(width,top,top_count):
    """
    Producing lists of length 'width' containing numbers from 0 to top-1.
    Where top-1 only occur exactly top_count times.
    """
    if width == 0:
        yield []
    elif width == top_count:
        yield [top-1]*top_count
    else:
        for x in range(top-1):
            for result in h(width-1,top,top_count):
                yield [x]+result
        if top_count > 0:
            for result in h(width-1,top,top_count-1):
                yield [top-1]+result

def m(width,top):
    yield [0]*width
    for current_top in range(2,top+1):
        for top_count in range(1,width+1):
            print "=== h{}".format((width,current_top,top_count))
            for result in h(width,current_top,top_count):
                print result
                yield result

ans = [x for x in m(3,3)]

rawDescription: Generator for combinations in special order


code: print word_list[0][0]    # first entry of the first tuple

rawDescription: Tuple indexing and printing

description: Tuple indexing and printing


rawDescription: Looping copied list and deleting from original list deletes from copied list


code: print data.xpath('//div[re:match(@class, "title_dep\d+")]/text()', namespaces={"re": "http://exslt.org/regular-expressions"})

rawDescription: Extracting divs with regular expressions


code:
print repr('test\ttest 2'.replace('\t', ' ' * 8))
print repr('tessst\ttest 2'.replace('\t', ' ' * 8))
# output: 'test        test 2'
#         'tessst        test 2'

rawDescription: Length of tab character

description: Length of tab character


code:
response = 'Hello there. Your ID is: 6. Your name is: Number 6.'
before, matched, after = response.partition('Your ID is: ')
if after:
    yourid, _, _ = after.partition('.')
    print yourid

rawDescription: Read characters in a string only if I have found the part that I need? [Python]


code:
import pandas as pd
import glob

idx = ['Number', 'Average', 'niquely number', '%']
df = pd.DataFrame()
i = 0

for files in glob.glob('dir/*.txt'):

    i = i + 1
    column = ['sample_' + str(i)]

    df1 = pd.read_csv(files, names=column, sep='|', header=None, usecols=[1])
    #print df1
    #remove NaN value from df1
    df1 = df1.dropna()
    #concat df1 to df
    df = pd.concat([df, df1], axis=1)

#add column idx do df
df['idx'] = pd.Series(idx, index=df.index)
#set index from column idx
df = df.set_index('idx')
#remove index name
del df.index.name

print df

rawDescription: merging columns from other files into one file

description: Merging columns from other files into one file


code:
class DefaultClassMethods(type):
    def __getattr__(cls, attr):
        def _defaultClassMethod(cls):
            print 'Hi, I am the default class method!'
        setattr(cls, attr, classmethod(_defaultClassMethod))
        return getattr(cls, attr)

class A(object):
    __metaclass__ = DefaultClassMethods

A.spam
A.spam()

rawDescription: Python dynamic class methods

description: Python dynamic class methods


code:
import lxml.html

root = lxml.html.fromstring('''

    2014-05-25
    Wikipedia (link)
    Yandex (link)
    another needed info(info 3)

    1
    2
    3
    ...

''')

tr_list = root.xpath('//*[starts-with(@id, "element-")]')
for tr in tr_list:
    print tr.get('id').split('-')[1]
    print tr.get('data-date')

rawDescription: How to get all html elements with id equal to `constant_text-something_changed`?

description: Get all html elements with id equal to `constant_text-something_changed`


code:
count_line = 0
for n, line in enumerate(open('test.txt')):
    count_line = count_line +1
    fields = line.rstrip('\n').split('\t')
    ##print count_line, fields
    already_text = open('test_words.txt').read() if n > 0 else ''
    file = open('test_words.txt', 'w+')
    count_word = 0
    file.write(already_text)
    for words in fields:
        wordsplit = words.split()
        for word in wordsplit:
             count_word = count_word + 1
             print count_word, word
             file.write(str(count_word) + " " + word + '\n')
        file.close()

rawDescription: How to write words from list to file?

description: Write words from list to file


code:
if not a and b:
  print "not a and b"
elif a and not b:
  print "a and not b"

rawDescription: More pythonic way to handle this if condition?


code:
import sys

if __name__=="__main__":
    print "command arguments:", sys.argv

rawDescription: How to use sys.argv in python to check length of arguments so it can run as script?

description: Use sys.argv in python to check length of arguments so it can run as script


code:
import re

def ld(a,b):
    "Calculates the Levenshtein distance between a and b."
    n, m = len(a), len(b)
    if n > m:
        # Make sure n <= m, to use O(min(n,m)) space
        a,b = b,a
        n,m = m,n

    current = range(n+1)
    for i in range(1,m+1):
        previous, current = current, [i]+[0]*n
        for j in range(1,n+1):
            add, delete = previous[j]+1, current[j-1]+1
            change = previous[j-1]
            if a[j-1] != b[i-1]:
                change = change + 1
            current[j] = min(add, delete, change)
    return current[n]

s='Mary had a little lamb'
d={}
regs=[r'.*', r'Mary', r'lamb', r'little lamb', r'.*little lamb',r'\b\w+mb',
        r'Mary.*little lamb',r'.*[lL]ittle [Ll]amb',r'\blittle\b',s,r'little']

for reg in regs:
    m=re.search(reg,s)
    if m:
        print "'%s' matches '%s' with sub group '%s'" % (reg, s, m.group(0))
        ld1=ld(reg,m.group(0))
        ld2=ld(m.group(0),s)
        score=max(ld1,ld2)
        print "  %i edits regex->match(0), %i edits match(0)->s" % (ld1,ld2)
        print "  score: ", score
        d[reg]=score
        print
    else:
        print "'%s' does not match '%s'" % (reg, s)

print "   ===== %s =====    === %s ===" % ('RegEx'.center(10),'Score'.center(10))

for key, value in sorted(d.iteritems(), key=lambda (k,v): (v,k)):
    print "   %22s        %5s" % (key, value)

rawDescription: Matching 2 regular expressions in Python


code:
def bin(values):
    bins = [[] for _ in range(10)]    # create ten bins
    for n in values:
        b = int(n * 100)              # normalize the value to the bin number
        bins[b].append(n)             # add the number to the bin
    return bins

d =  [0.0432,
  0.0336,
  0.0345,
  0.044,
  0.0394,
  0.0555]
print bin(d)

rawDescription: Binning variable length lists in python

description: Binning variable length lists in python


code:
array_np = numpy.asarray(array)
print numpy.sort(array_np[array_np >= lowValY])[-highCountX:]

rawDescription: Fastest way to zero out low values in array?


rawDescription: Numpy arctan2 of multidimensional array

description: Numpy arctan2 of multidimensional array


code:
import bisect

rules = {
 3: 15,
 6: 21
}

def generate_time_off_paid_days_list(years, rules, default):
    r_list = rules.keys()
    r_list.sort()  # sorted list of the keys in the rules dict
    d = {}
    for y in years:
        # First, find the index of the year in r_list that's >= to "y"
        r_index = bisect.bisect_left(r_list, y)
        if r_index == len(r_list):
            # If the index we found is beyond the largest index in r_list,
            # we use the default
            days_off = default
        else:
            # Otherwise, get the year key from r_list, and use that key to
            # retrieve the correct number of days off from the rules dict
            year_key = r_list[r_index]
            days_off = rules[year_key]
        d[y] = days_off
    return d

print generate_time_off_paid_days_list(range(1,11), rules, 30)

rawDescription: How to generate a dictionary based on a list and dictionaries

description: Generate a dictionary based on a list and dictionaries


code:
for k, v in d.items():
    print k, v.count('s1')+v.count('s2')

rawDescription: using data from txt file to answer questions in python

description: Using data from txt file to answer questions in python


code:
from cStringIO import StringIO
sample = '''\
>164778
AATCTAGATTTGTGTTGAACAACCCTTGGTACAACAAATACTTGGCACTTTTATAACCCAACTGTATGGTATAATCGACA
TCTGTGTTATGAAAGGAACTTGATTTGTTGTTAACATAAGCAATCACCATGAATACCTGATAATATTTACAAGTATTGGC
ATTACTCGAATAAGATAATTAATGTAATCATGTTAACAATTTATAATCTAATTGAAACCTCCTTTGTGTGTGGTTTCCAA
TTGGGCAATAAGAGTTTATAC
>164779
AAATCACTTTCAGTGGAAAATTATAAAACCTATTAATTTATTGCCGGCCCTCAAATCAACGCAACCCAAAACCTATTAAT
TATAAAACCTATTAATTTATTTTTTCAATCAACTACGACTATTAATTATATTTGATGATAATGAATGAAATGACACCATG
GTTATATAAAAAATATGTCAAAAGCTATTCTTAATAGGGTTT
'''
spacer = "N" * 64
fh_in = iter(sample.splitlines(True))
fh_out = StringIO()
prev = next(fh_in)  # first line
for line in fh_in:
   if line.startswith('>'):
       prev = prev.rstrip('\n') + spacer + '\n'
   fh_out.write(prev)
   prev = line

fh_out.write(prev.rstrip('\n') + spacer + '\n')
print fh_out.getvalue()

rawDescription: How to add bunch of "N's" at the end of file in python?

description: Add bunch of "N's" at the end of file in python


code:
from pyparsing import *

LBRACK,RBRACK,LBRACE,RBRACE,LANGLE,RANGLE,VERT_BAR = map(Suppress,"[]{}<>|")

expr = Forward()

ident = Word(alphas, alphanums+'-_')

optional_expr = (LBRACK + expr + RBRACK)
reqd_expr = (LBRACE + expr + RBRACE)
user_expr = (LANGLE + OneOrMore(ident) + RANGLE)

term = ident | optional_expr | reqd_expr | user_expr
term = Group(term * (2,None)) | term

expr <<= OneOrMore(term + ~VERT_BAR | Group(delimitedList(term,VERT_BAR)))

tests = """\
element-type { a | b | c | d} [ duration ]
tcp [ udp-mode { off | on { encrypted | plain }}]""".splitlines()

for t in tests:
    print t
    print expr.parseString(t).asList()[0]
    print

rawDescription: Parsing data between multiple brackets and different kind of brackets


code:
crimes_and_times = [('a time', 'a crime'), ('b time', 'b crime'), ('b time', 'c crime')]
for i in xrange(1, len(crimes_and_times)):
    cur = crimes_and_times[i]
    prev = crimes_and_times[i - 1]
    if cur[0] == prev[0]:
        print cur

rawDescription: Comparing values of list of tuples, current and next


code:
line = '"190","Windows 2000","2000","609"'
sliced = line.split(',')
print sliced
first_item = sliced[0][1:-1]
print first_item

rawDescription: How to create a list to select index?

description: Create a list to select index


code:
import SOAPpy
test = 42
server = SOAPpy.SOAPProxy("http://localhost:8888")
server = server._sa ("urn:soapinterop")
#Header
hd = SOAPpy.Header()
hd.InteropTestHeader = 'This should fault,as you don\'t understand the header.'
hd._setMustUnderstand ('InteropTestHeader', 1)
hd._setActor ('InteropTestHeader','http://schemas.xmlsoap.org/soap/actor/next')
server = server._hd (hd)

print server.echoInteger (test)

rawDescription: Sage CRM web services example in Python

description: Sage CRM web services example in Python


code:
import types

class TestClass(object):

    def __init__(self, ctrl_func):
        self.a = 4
        self.ctrl_func = types.MethodType(ctrl_func, self)

    def do_stuff(self):
        self.ctrl_func()

def test_controller(self):
    self.a = 20

my_thing = TestClass(test_controller)
print my_thing.a         #this prints 4
my_thing.ctrl_func()
print my_thing.a         #this prints 4 but I want it to print 20

rawDescription: a function that modifies its class's data objects

description: A function that modifies its class's data objects


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, minimize_scalar

x = [1,2,3.2,4,5]
y = [1,4,16,4,1]

def f(x, p1, p2, p3):
    return p3*(p1/((x-p2)**2 + (p1/2)**2))

p0 = (8, 16, 0.1) # guess perameters
plt.plot(x,y,"ro")
popt, pcov = curve_fit(f, x, y, p0)

# find the peak
fm = lambda x: -f(x, *popt)
r = minimize_scalar(fm, bounds=(1, 5))
print "maximum:", r["x"], f(r["x"], *popt)  #maximum: 2.99846874275 18.3928199902

x_curve = np.linspace(1, 5, 100)
plt.plot(x_curve, f(x_curve, *popt))
plt.plot(r['x'], f(r['x'], *popt), 'ko')
plt.show()

rawDescription: Finding the maximum of a curve scipy

description: Finding the maximum of a curve scipy


rawDescription: Removing Trailing Zeros in Python

description: Removing Trailing Zeros in Python


code:
import collections
from blist import sorteddict

class ValueSortedDict(collections.MutableMapping):
    def __init__(self, data):
        self._dict = {}
        self._sorted = sorteddict()
        self.update(data)

    def __getitem__(self, key):
        return self._dict[key]

    def __setitem__(self, key, value):
        # remove old value from sorted dictionary
        if key in self._dict:
            self.__delitem__(key)
        # update structure with new value
        self._dict[key] = value
        try:
            keys = self._sorted[value]
        except KeyError:
            self._sorted[value] = set([key])
        else:
            keys.add(key)

    def __delitem__(self, key):
        value = self._dict.pop(key)
        keys = self._sorted[value]
        keys.remove(key)
        if not keys:
            del self._sorted[value]

    def __iter__(self):
        for value, keys in self._sorted.items():
            for key in keys:
                yield key

    def __len__(self):
        return len(self._dict)

x = ValueSortedDict(dict(a=1, b=4, c=3))
x['a'] += 1
print list(x.items())
x['a'] += 10
print list(x.items())
x['d'] = 4
print list(x.items())

rawDescription: Python data structure for sorted key-value pairs


code:
@threads_over_lists
def add_1(val):
    return val + 1

print add_1(10)
print add_1([10, 15, 20])

# if there are multiple arguments, threads only over the first element,
# keeping others the same

@threads_over_lists
def add_2_numbers(x, y):
    return x + y

print add_2_numbers(1, 10)
print add_2_numbers([1, 2, 3], 10)

rawDescription: Automatically use list comprehension/map() recursion if a function is given a list


code:
a = '    Hello, I  am     trying  to       strip spaces  perfectly '
print ' '.join(a.split())

rawDescription: How to strip spaces in Python and UNIX to render only one space uniformly throughout the string

description: Strip spaces in Python and UNIX to render only one space uniformly throughout the string


code:
def read():
    FIFO_PATH = '/tmp/my_fifo'
    i = 0
    with open(FIFO_PATH, 'r') as read_fifo:
        while i < 10:
            i += 1
            print i, read_fifo.readline().rstrip()

rawDescription: using FIFOs for input and output in python

description: Using FIFOs for input and output in python


code:
def load_data_nn():
    training_data, validation_data, test_data = load_data()
    # suppose training_data[0].shape == (50000,28,28), otherwise leave it as is
    inputs = training_data[0].reshape((50000,784,1))
    print inputs[0]
    # create identity matrix and use entries of training_data[1] to
    # index corresponding unit vectors
    results = np.eye(10)[training_data[1]]
    training_data = zip(inputs, results)
    # suppose test_data[0].shape == (50000,28,28), otherwise leave it as is
    test_inputs = test_data[0].reshape((50000,784,1))
    return (training_data, test_inputs, test_data[1])

rawDescription: How to write the ndarray to text file in python?

description: Write the ndarray to text file in python


code:
from glob import glob
from urllib2 import urlopen
from ConfigParser import ConfigParser
from re import search

# I use RE here, you might consider BeautifulSoup because RE can be stupid
TITLE = r"<title>([^<]+)</title>"

result = []
for file in glob("*.url"):
    config = ConfigParser.ConfigParser()
    config.read(file)
    url = config.get("InternetShortcut", "URL")

    # Get the title
    page = urlopen(url).read()
    try: title = search(TITLE, page).groups()[0]
    except: title = "Couldn't find title"

    result.append((url, title))

for url, title in result:
    print "'%s' <%s>" % (title, url)

rawDescription: How can I create a script that manufactures MLA citations?

description: Create a script that manufactures MLA citations


code:
def convert_timedelta(duration):
    days, seconds = duration.days, duration.seconds
    hours = days * 24 + seconds // 3600
    minutes = (seconds % 3600) // 60
    seconds = (seconds % 60)
    return hours, minutes, seconds
td = datetime.timedelta(2, 7743, 12345)
hours, minutes, seconds = convert_timedelta(td)
print '{} minutes, {} hours'.format(minutes, hours)

rawDescription: How to convert datetime.timedelta to minutes, hours in Python?

description: Convert datetime.timedelta to minutes, hours in Python


code:
import requests
from bs4 import BeautifulSoup
r = requests.get('http://www.chess.com/members/view/MagnusCarlsen')
soup = BeautifulSoup(r.content)
for link in soup.select('a[href^=/livechess/game?id=]'):
    print link['href']

rawDescription: Game scraping python regular expression

description: Game scraping python regular expression


code:
def gaus(n, ls = list()):
    if n == 1:
        return ls
    else:
        ls.append(n / 2.)           # Step 1:  n / 2
        ls.append(ls[-1] * 3 + 1)   # Step 2: (n / 2) * 3 + 1
        return gaus(n - 1, ls)

print gaus(30)

rawDescription: A python non finished function

description: A python non finished function


code:
def lookup(addr):
    try:
        return socket.gethostbyaddr(addr)
    except socket.herror:
        return None, None, None
name,alias,addresslist = lookup('4.2.2.2')
print name
name,alias,addresslist = lookup('114.143.51.197')
print name

rawDescription: Difficulty using Python's socket.gethostbyaddr()


code:
matrix = Matrix()
matrix[2,3] = 1066
print matrix
matrix[2,3]
matrix[3,2]
matrix[1,1]

rawDescription: Symmetrically adressable matrix

description: Symmetrically adressable matrix


code: print '{:04b}'.format(5)

rawDescription: what is the best way to represent a char in its bits representation(Python)

description: What is the best way to represent a char in its bits representation(Python)


code:
balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))

for month in xrange(1, 12+1):
  interestPaid = round(interestRate / 12.0 * balance, 2)
  minPayment = round(minPayRate * balance, 2)
  principalPaid = round(minPayment - interestPaid, 2)
  remainingBalance = round(balance - principalPaid, 2)

  print 'Month:', month
  print 'Minimum monthly payment:', minPayment
  print 'Principle paid:', principalPaid
  print 'Remaining balance:', remainingBalance

  balance = remainingBalance

rawDescription: Python Beginner. Is this Python code as efficient as it could be?


code:
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup('''\

Table of Contents

#

One

Two

Three

''')
matching_link = soup.find('a', text=re.compile('one', re.IGNORECASE))
print matching_link.string
print matching_link['href']

rawDescription: Beautiful Soup and searching in results

description: Beautiful Soup and searching in results


code:
ancestral = ['A', 'C', 'G', 'T', 'C', 'A', 'T', 'C', 'A']
bases = ['a', 'g', 'c', 't']

for i in range(len(ancestral)):
    for b in bases:
        test = list(ancestral)
        test.insert(i, b)
        print test

rawDescription: Create new lists by adding elements

description: Create new lists by adding elements


code:
print 'generating test data'
num_sets = 100000
set_size = 40
elements = range(500)
U = set(elements)
R = U
S = []
for i in range(num_sets):
    random.shuffle(elements)
    S.append(set(elements[:set_size]))
w = [random.randint(1,100) for i in xrange(100)]

C = []
costs = []

rawDescription: How do I make my implementation of greedy set cover faster?

description: Make my implementation of greedy set cover faster


rawDescription: Need help printing multiple rows in loop


code:
people = {"Peter" : [], "Max" : []}
new_values = [('Peter', 'value1', 2), ('Peter', 'value2', 3), ('Max', 'value3', 4), ('Max', 'value3', 4)]
for name, v1, v2 in new_values:
    people[name].append((v1, v2))
print people

rawDescription: Design-Help Python Variable DataStructure List/Dict/Tuple


code:
for lists_data in dict_of_lists_values:
    print lists_data[0], ' holds ', dict_of_lists_values[lists_data], lists_data[1]

rawDescription: What approach can I take if I can't have similar names in a dict?


code:
class Tree:
    def __init__(self, value):
        self.value = value
        self.children = []

def get_paths(t, paths=None, current_path=None):
    if paths is None:
        paths = []
    if current_path is None:
        current_path = []

    current_path.append(t.value)
    if len(t.children) == 0:
        paths.append(current_path)
    else:
        for child in t.children:
            get_paths(child, paths, list(current_path))
    return paths

t = Tree(1)
t2 = Tree(2)
t7 = Tree(7)
t2.children = [t7]
t5 = Tree(5)
t9 = Tree(9)
t8 = Tree(8)
t5.children = [t9, t8]
t.children = [t2, t5]

print get_paths(t)

rawDescription: All paths of a tree

description: All paths of a tree


code:
a = Foo(1, 2)
a.sayhi()

b = Bar(1, 2, 3)
b.sayhi()  # 'inherited' from class Foo
b.saybye()

try:
    b.c = 1         # will raise an AttributeError
except AttributeError:
    print "Immutable"

print "issubclass(Bar, Foo): {0}".format(issubclass(Bar, Foo))

try:
   d =  {b: 1}        # No problems
except TypeError:
    print "Cant put it in a dict"
else:
    print "Can put it in a dict"

rawDescription: Immutable types allowing subclassing in Python


code:
import lxml.html

listitems = ['Adams<\/a>\n', 'Donovan Smith<\/a>\n']

string = ' '.join(listitems)

page = lxml.html.fromstring(string)

a_tags = page.cssselect('a')

names = []
for tag in a_tags:
  names.append(tag.text_content().strip())

print names
['Adams', 'Donovan Smith']

rawDescription: Is accepting special characters for a range within a regex pattern possible?


code:
import sys
class Sentinel(Exception): pass

class SetTrace(object):
    """
    with SetTrace(monitor):
        ...
    """
    def __init__(self, func):
        self.func = func

    def __enter__(self):
        sys.settrace(self.func)
        return self

    def __exit__(self, ext_type, exc_value, traceback):
        sys.settrace(None)
        # http://effbot.org/zone/python-with-statement.htm
        # When __exit__ returns True, the exception is swallowed.
        # When __exit__ returns False, the exception is reraised.

        # This catches Sentinel, and lets other errors through
        return isinstance(exc_value, Sentinel)

def monitor(frame, event, arg):
    if event == "line":
        l = frame.f_locals
        x = l.get('x', 0)
        print('x = {}'.format(x))
        if x > 3:
            raise Sentinel()
    return monitor

def foo():
    x = 0
    while True:
        print 'bar'
        x += 1

with SetTrace(monitor):
    foo()

rawDescription: Python : Adding a code routine at each line of a block of code


code:
data = range(10)
print [x*x for x in Iter(data)]

rawDescription: Python: the mechanism behind list comprehension


code:
import requests
r = requests.get('http://127.0.0.1/some_path/small.csv')
print len(r.content.split('\n')) -1

rawDescription: Read info from hyperlink located remotely (know that by hyperlink it will be csv file, but can't find general approach)


code:
import async_subprocess as subprocess

cmd = ['python', '-u', 'testfile.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
so = p.asyncread()
print so,
(so, se) = p.communicate()
print so

rawDescription: Getting stdout to display called script containing input


code:
from Crypto.Cipher import Blowfish
from base64 import b64encode, b64decode
passw='secretPassword12'
ntext='helloworld123456'

cipher=Blowfish.new(passw, Blowfish.MODE_ECB)
encStr=b64encode(cipher.encrypt(data))
print encStr

rawDescription: Howto send encryped messages between python and php using blowfish for encryption?


code:
import sqlite3
conn = sqlite3.connect('database.db')

cur = conn.cursor()

tables = ('table1', 'table2', 'table3')
results = [list(cur.execute('select column from %s' % table)) for table in tables]

def try_list(lst, i):
    try:
        return lst[i]
    except IndexError:
        return ('',)

maxlen = max(len(i) for i in results)
results2 = [[try_list(line, i) for line in results] for i in xrange(maxlen)]

output = '\n'.join(','.join(str(i[0]) for i in line) for line in results2)
print output

rawDescription: don't get duplicated values when exporting sqlite3 file to csv using python?

description: Don't get duplicated values when exporting sqlite3 file to csv using python


code:
import collections
print [x for x, y in collections.Counter(myList).iteritems() if y == 1]
# [6, 211, -8]

rawDescription: Removing all duplicates from the list - keeping no instance of a duplicate item


rawDescription: How can I efficently pad an RGB numpy array with the median of the image?

description: Efficently pad an RGB numpy array with the median of the image


code:
# assume your bytes came from a file:
bytesIneed = bytearray([234,232,231,188,122,132,145])
import base64

bytesConverted = base64.b64encode(bytesIneed)

print "encoded string: "
print bytesConverted

bytesRecovered = base64.b64decode(bytesConverted)

print "decoded binary: "
for c in bytesRecovered: print(ord(c))

rawDescription: Trying to store raw bytes inside my one Python script file


code:
print format(integervalue, '05d')
print 'Formatted String : {0:05d}'.format(integervalue)

rawDescription: Python format Integer into fixed length strings


rawDescription: Python Regular Expressions Findall

description: Python Regular Expressions Findall


code: print [items[0] + items[1] for items in product(a, b)]

rawDescription: Generate a lattice using python

description: Generate a lattice using python


code:
for i in open("Sample.txt").readlines():
  if i[:i.index(' : ')] in A:
    print i[i.index(' : ')+3:].split()[0]

rawDescription: Reading Specific Python list from a text file


code:
import numpy as np

data = np.array([4,2,5,6,7,5,4,3,5,7])

print data.reshape(-1, 2).mean(axis=1)

rawDescription: Binning a numpy array

description: Binning a numpy array


code:
from cStringIO import StringIO
fileA = StringIO("""20111225, 20111226, 20090101""")
fileB = StringIO("""20111225, 20111226, 20090101, 20090102, 20111227, 20090105""")

def fileReader(infile):
  for line in infile:
    for part in line.split(','):
      yield part.strip()

def next_or_none(iterable):
  for value in iterable:
    yield value
  yield None

def combine(a,b):
  current_val = None
  hasA = hasB = False
  next_a, next_b = next_or_none(a).next, next_or_none(b).next
  current_a, current_b = next_a(), next_b()
  while True:
    if current_val is None:
      if current_a == current_b:
        current_val = current_a
        hasA = hasB = True
        current_a, current_b = next_a(), next_b()
      elif current_a is not None and (current_b is None or current_a < current_b):
        current_val = current_a
        hasA = True
        current_a = next_a()
      elif current_b is not None and (current_a is None or current_b < current_a):
        current_val = current_b
        hasB = True
        current_b = next_b()
      else:
        break
    else: # There's a current_val
      sub_a = []
      while current_a is not None and current_a < current_val:
        sub_a.append(current_a)
        current_a = next_a()
      sub_b = []
      while current_b is not None and current_b < current_val:
        sub_b.append(current_b)
        current_b = next_b()
      if sub_a or sub_b:
        sub_ab = list(combine(sub_a,sub_b))
      else:
        sub_ab = []
      yield (current_val,hasA,hasB,sub_ab)
      current_val = None
      hasA = hasB = False

for row in combine(fileReader(fileA),fileReader(fileB)):
  print row

rawDescription: Python combine two lists of objects recursively by comparing datetimes


code:
list1, list2, list3, list4 = [1, 2, 3], [2, 3, 1], [1, 2, 3, 4], [1, 2, 3, 3]
from collections import Counter
print Counter(list1) == Counter(list2)    # True
print Counter(list2) == Counter(list3)    # False
print Counter(list1) == Counter(list3)    # False
print Counter(list1) == Counter(list4)    # False

rawDescription: Python compare tuples

description: Python compare tuples


code:
def difft(start,end):
    a,b,c,d = start.hour, start.minute, start.second, start.microsecond
    w,x,y,z = end.hour, end.minute, end.second, end.microsecond
    delt = (w-a)*60 + (x-b) + (y-c)/60. + (z-d)/60000000

    D = '%sh %smn %ss %sms - %sh %smn %ss %sms == '
    ft = '%s + 1440 = %s  (1440 = 24x60mn)'
    return D % (w,x,y,z,a,b,c,d) +( ft % (delt, delt+1440) if delt<0 else str(delt))

print difft(time(11,30,0),time(12,35,0))
print difft(time(11,30,0),time(10,35,0))
print
print difft(time(20,40,0),time(22,41,0))
print difft(time(20,40,0),time(18,41,0))

rawDescription: how to substract two datetime.time values in django template,and how to format a duration as hour,minutes

description: Substract two datetime.time values in django template,and how to format a duration as hour,minutes


code:
globals().update({d[0]:d[1:] for d in columns})
print Timestamp # or whatever

rawDescription: Python: creating variable name from header row in csv read


code:
import mechanize

br = mechanize.Browser()
br.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp')
br.select_form(name="main")
br.find_control(name="disclaimer").items[0].selected = True
reponse = br.submit()
print reponse.read()

rawDescription: Forms not getting submitted with MECHANIZE in PYTHON!


code:
mask = df[['col1', 'col2']].apply(lambda x: x.str.contains('vhigh|high', regex=True)).any(axis=1)
print df[mask]

rawDescription: Search and filter pandas dataframe with regular expressions


code:
a = 1
def change(d):
    global a
    a = d
    print a

change(5)
print a

rawDescription: Django persistent API connections between requests


code:
from lxml import etree
from io import BytesIO

class FindClasses(object):
    @staticmethod
    def parse_xml(xml_string):
        parser = etree.XMLParser()
        fs = etree.parse(BytesIO(xml_string), parser)
        fstring = etree.tostring(fs, pretty_print=True)
        element = etree.fromstring(fstring)
        return element

    def find(self, xml_string):
        for parent in self.parse_xml(xml_string).getiterator('connection'):
            for child in parent:
                if child.tag == 'id':
                    print child.text
                    self.find_classes(child)

    @staticmethod
    def find_classes(child):
        for parent in child.getparent():  # traversing up -> connection
            for children in parent.getchildren():  # children of connection -> classes
                for child in children.getchildren():  # child of classes -> class
                    print child.text
        print

if __name__ == '__main__':
    xml_file = open('foo.xml', 'rb')  #foo.xml or path to your xml file
    xml = xml_file.read()
    f = FindClasses()
    f.find(xml)

rawDescription: How to properly parse parent/child XML with Python

description: Properly parse parent/child XML with Python


code:
import numpy as np

def reverse(a, axis=0):
    idx = [slice(None)]*len(a.shape)
    idx[axis] = slice(None, None, -1)
    return a[idx]

a = np.arange(24).reshape(2,3,4)
print reverse(a, axis=2)

rawDescription: Reverse an arbitrary dimension in an ndarray


code:
from sympy import *

a,b,c,d = symbols("a,b,c,d")
eq = a * b * c + b * c + a * d
print collect(eq, b)
print collect(eq, c)
print collect(eq, b*c)

rawDescription: Choosing between different expression factorizations in SymPy


rawDescription: How to find number of matches in the array or dictionary?

description: Find number of matches in the array or dictionary


code:
A = [['a', 'b','c'], ['d','e', 'f']]
B = [['b', 'a', 'c'], ['a', 'o', 'p']]

diff = lambda a,b: [list(x) for x in map(tuple, map(sorted, a)) if x not in map(tuple, map(sorted, b))]
print diff(A, B)
print diff(B, A)

rawDescription: Find a particular list inside a list of lists


code:
# Replaced with something better.
def dosync(self):
    print "Got an event!"
    res = self.M.recent()
    print res

rawDescription: Find new messages added to an imap mailbox since I last checked with python imaplib2?


code:
import os

(_, _, my_files) = os.walk('some_directory').next()
print len([f for f in my_files if f.endswith('.txt')])

rawDescription: Count how many text files in a directory using python 2.7 and edit them


code:
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class Echo(Protocol):
    def dataReceived(self, data):
        print 'recieved:', data
    def connectionLost(self, reason):
        print 'connection closed', reason

f = Factory()
f.protocol = Echo
reactor.listenTCP(8080, f)
reactor.run()

rawDescription: Initiating TCP Client after running reactor.run()


code: print "my list:", my_opmenu.list

rawDescription: Get list variable from tkinter OptionMenu in Python


code:
_input = [
    [1],
    [[2]],
    [3],
    [['a','b','c'] , [['z','x','y']], ['d','f','g']],
    4
]

_input = map(lambda(x): x if isinstance(x, list) else [x], _input)

import itertools
for element in itertools.product(*_input):
    print flat(list(element))  # this line was modified

rawDescription: python: how can I achieve a cartesian product of all the lists in a list?

description: Python: how can I achieve a cartesian product of all the lists in a list


code:
import sys, termios, atexit
from select import select

# save the terminal settings
fd = sys.stdin.fileno()
new_term = termios.tcgetattr(fd)
old_term = termios.tcgetattr(fd)

# new terminal setting unbuffered
new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)

# switch to normal terminal
def set_normal_term():
    termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)

# switch to unbuffered terminal
def set_curses_term():
    termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)

def putch(ch):
    sys.stdout.write(ch)

def getch():
    return sys.stdin.read(1)

def getche():
    ch = getch()
    putch(ch)
    return ch

def kbhit():
    dr,dw,de = select([sys.stdin], [], [], 0)
    return dr <> []

rawDescription: easiest way to pause a command-line python program?

description: Easiest way to pause a command-line python program


code:
import itertools
for p in itertools.combinations(foo, 2):
    print zip(*p)

rawDescription: How to Combine Each of the Elements of Two Lists in Python?


code:
print [x.encode('UTF8') for x in idx.tolist()]
['Newal', 'Saraswati Khera', 'Tohana']

rawDescription: how to convert Index into list?

description: Convert Index into list


code:
fID=open('TopicMapped.txt')

myDict=dict() #init empty dictionary

for line in fID:
    #read the file line-by-line (if it's huge, it might be cumbersome to import it entirely in memory, e.g. using readlines())
    # and also remove newline tags
    line=line.rstrip()

    #create a list where the first element is the number and the second element is the text
    line=line.split("\t")

    #update dictionary
    myDict[line[0]]=line[1]

print myDict
fID.close()

rawDescription: Making a python dictionary from a huge textfile?


code:
from datetime import date

def display_birthday_wishes():
    name = raw_input("enter your name")

    current_year = current_year = date.today().year
    year_born = raw_input("enter your year of birth")

    current_age = (int(current_year)-int(year_born))

    month_born = raw_input("enter your month of birth")

    return "Hi, " + name + ". You are " + str(current_age) +\
    " years old this year! Here's a bouquet of flowers for you!"

print display_birthday_wishes()

rawDescription: Wrap code in a function

description: Wrap code in a function


code:
Python
import re
def time_replace(timeword):
    timestr = timeword.group().lower()
    flag = None
    if 'h' in timestr:
        flag = 1
    elif ':' in timestr:
        flag = 2
    elif 'm' in timestr:
        flag = 3
    elif 'at' in timestr:
        return "Location"

    if flag == 1:
        hour = timestr.split('h')[0]
        if int(hour) > 12 and int(hour) < 24:
            return str(int(hour) - 12) + ":00 PM"
        elif int(hour) == 24:
            return str(int(hour) - 12) + ":00 AM"
        elif int(hour) == 12:
            return hour + ":00 PM"
        else:
            return hour + ":00 AM"
    elif flag == 2:
        hour, minute = timestr.split(':')
        if int(hour) > 12 and int(hour) < 24:
            return str(int(hour) - 12) + ":" + minute + " PM"
        elif int(hour) == 24:
            return str(int(hour) - 12) + ":" + minute + " AM"
        elif int(hour) == 12:
            return hour + ":" + minute + " PM"
        else:
            return hour + ":" + minute + " AM"
    elif flag == 3:
        time = re.search(r"\d+(\.\d+)?", timestr).group()
        hour, ampm = time[-2:], timestr[-2:]
        meridiem = " PM" if 'pm' in ampm else " AM"
        return "%s:00%s" % (hour, meridiem)
    else:
        return timestr

agenda = """
    ---------------------------------------
    8h going swimming with friends
    16H going swimming with friends

    8:00 going swimming with friends
    08:35 going swimming with friends

    8pm going for dinner
    8AM going swimming with friends
    7PM going for dinner at ahmedabad
    9am going swimming with friends"""

print agenda
print re.sub(r"(\d{1,2}h)|(\d{1,2}:\d{2})|(\d{1,2}(?:am|pm))|((?!\s)at(?=\s))", time_replace, agenda, flags=re.I|re.M)

rawDescription: Python find "xxh" from string and replace into xx:00 AM/PM in existing string


code:
from socket import *

ip="192.168."
print("Searching for IP...")
for i in range(0,256):
    for j in range(0,256):
        host=ip+str(i)+"."+str(j)
        add=(host,1060)
        print host
        s=socket(AF_INET,SOCK_STREAM) # create the socket in loop
        s.settimeout(4) # set the timeout value as 4 seconds
        try:
            s.connect(add)
            print("Server Found:",add)
        except:
            print(host,"failed")
        s.close() # close it
        del s

rawDescription: How to flood IP addresses to find server

description: Flood IP addresses to find server


rawDescription: Extract Only Unicode Characters from a String using Regular Expressions


code:
numbers = []
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
            date, process,company,number,rate = row
            numbers.append(number)

numbers.sort()
print numbers

rawDescription: sort names in alphabitical order in mysql using python

description: Sort names in alphabitical order in mysql using python


code:
def factorial(num):
    res = 1
    for i in xrange(1,num+1):
        res *= i
    return res

def factorial_cap(num):
    print "Input number:", num
    F = 0
    x = 0
    while (F < num):
        x = x+1
        F = factorial(x)

    print "The answer is:", x
    return x

for t in xrange(0,30):
    factorial_cap(t)
    print

rawDescription: My python program keeps returning the wrong value doubled


code:
def foo():
    print 'called!'
    return False

def bar():
    print 'also called!'
    return False

foo() and bar()
foo() & bar()

rawDescription: Explicitly evaluate both conditions when using boolean and


code:
pattern = re.compile(r'^p:(\w*)\t')
foo = re.match(pattern, line)
if foo:
  print 'MATCH'

rawDescription: Python regex match all characters except tab


code:
from pyparsing import *
num = Word(nums)
accessionDate = Combine(num + "/" + num + "/" + num)("accDate")
accessionNumber = Combine("S" + num + "-" + num)("accNum")
patMedicalRecordNum = Combine(num + "/" + num + "-" + num + "-" + num)("patientNum")
gleason = Group("GLEASON" + Optional("SCORE:") + num("left") + "+" + num("right") + "=" + num("total"))
assert 'GLEASON 5+4=9' == gleason
assert 'GLEASON SCORE:  3 + 3 = 6' == gleason

patientData = Group(accessionDate + accessionNumber + patMedicalRecordNum)
assert '01/02/11  S11-4444 20/111-22-3333' == patientData

partMatch = patientData("patientData") | gleason("gleason")

lastPatientData = None
for match in partMatch.searchString(data):
    if match.patientData:
        lastPatientData = match
    elif match.gleason:
        if lastPatientData is None:
            print "bad!"
            continue
        print "{0.accDate}: {0.accNum} {0.patientNum} Gleason({1.left}+{1.right}={1.total})".format(
                        lastPatientData.patientData, match.gleason
                        )

rawDescription: Pyparsing: extract variable length, variable content, variable whitespace substring


code: print path

rawDescription: How to read an attribute in another class?

description: Read an attribute in another class


code:
class P:
    def __init__(self, x):
        self.x = x

d = { 'how': P(3), 'hi': P(2), 'you': P(5), 'are': P(4) }
print list(d.iteritems())
print sorted(d.iteritems(), key=lambda x: x[1].x)

rawDescription: Sort a dictionary by values that are instance attributes


code:
from PySide import QtCore

mutex = QtCore.QMutex()

class QtLock(QtCore.QThread):

    def __init__(self, name):
        super(QtLock, self).__init__()
        self.name = name

    def run(self):

        for i in range(10):
            mutex.lock()
            print i, self.name,
            mutex.unlock()

threads = []
for i in range(5):
    name = chr(i + ord('a'))
    threads.append(QtLock(name))

for thread in threads:
    thread.start()

for thread in threads:
    thread.wait()

rawDescription: Custom Locks Threading python

description: Custom Locks Threading python


code:
from twitter import *
t = Twitter(
            auth=OAuth('OAUTH_TOKEN','OAUTH_SECRET',
                       'CONSUMER_KEY', 'CONSUMER_SECRET')
           )
query = int(raw_input("Type how many tweets do you need:\n"))
x = t.statuses.home_timeline(count=query)
for i in range(query):

  print x[i]['text']

rawDescription: How to increase the number of tweets read using python for sentiment analyser

description: Increase the number of tweets read using python for sentiment analyser


code:
def printBMITable(startHeight, endHeight, startWeight, endWeight):

    for x in range (startWeight, endWeight + 1, 10):
        print "\t",x,

    print '\n'

    for i in range(startHeight, endHeight + 1):
        print i,
        for x in range(startWeight, endWeight + 1, 10):
            print str(round(calculateBMI(i, x), 2)).rjust(7),
        print ''

rawDescription: Beginner Python: Calculation Formatting

description: Beginner Python: Calculation Formatting


code:
HVInfoDict = {
    369136986: {
        'cmstrk': 'cms_trk_dcs_05:CAEN',
        'trackersy': 'CMS_TRACKER_SY1527_8',
        'branch': 'branchController05',
        'crate': 'easyCrate1',
        'board': 'easyBoard03',
        'channel': 'channel002'
    }
}

input3 = raw_input("Write the property(s) which modules connected you want to know, separated by a single space \n > ")
input_list3 = input3.split(' ')
for k in input_list3:
    print "%r" % k
    txt.write("\t\n The modules with property %r are:\n" % k)
    for l,m in HVInfoDict.items():
        if k in m.values():
            print l
        else:
            print("Does not exist!")

rawDescription: get key from value python

description: Get key from value python


code:
import collections
ctr = collections.Counter()

for ii in range(0,5):
    charList = getList()
    ctr.update(charList)

ctr['total'] = sum(ctr.values())
print ctr

rawDescription: Dictionary key count

description: Dictionary key count


code:
def camel(s):
    return (s != s.lower() and s != s.upper())

tests = [
        "camel",
        "camelCase",
        "CamelCase",
        "CAMELCASE",
        "camelcase",
        "Camelcase",
        "Case"
        ]

for test in tests:
    print test, camel(test)

rawDescription: Check for camel case in Python

description: Check for camel case in Python


rawDescription: functionalities of continue/ break on the code in Python and its output

description: Functionalities of continue/ break on the code in Python and its output


code: print inzipfile.namelist()

rawDescription: Selective extracting and opening for zipfile in python


rawDescription: Python nested list recursion search

description: Python nested list recursion search


code:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
import sys, time

class HeartbeatSender(DatagramProtocol):
    def __init__(self, name, host, port):
        self.name = name
        self.loopObj = None
        self.host = host
        self.port = port

    def startProtocol(self):
        # Called when transport is connected
        # I am ready to send heart beats
        self.transport.joinGroup('224.0.0.1')
        self.loopObj = LoopingCall(self.sendHeartBeat)
        self.loopObj.start(2, now=False)

    def stopProtocol(self):
        "Called after all transport is teared down"
        pass

    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)

    def sendHeartBeat(self):
        self.transport.write(self.name, (self.host, self.port))

class HeartbeatReciever(DatagramProtocol):
    def __init__(self, name):
        self.name = name

    def startProtocol(self):
        "Called when transport is connected"
        self.transport.joinGroup('224.0.0.1')
        pass

    def stopProtocol(self):
        "Called after all transport is teared down"

    def datagramReceived(self, data, (host, port)):
        now = time.localtime(time.time())
        timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now))
        print "%s received %r from %s:%d at %s" % (self.name, data, host, port, timeStr)

heartBeatSenderObj = HeartbeatSender("sender", "224.0.0.1", 8005)

reactor.listenMulticast(8005, HeartbeatReciever("listner1"), listenMultiple=True)
reactor.listenMulticast(8005, HeartbeatReciever("listner2"), listenMultiple=True)
reactor.listenMulticast(8005, heartBeatSenderObj, listenMultiple=True)
reactor.run()

rawDescription: UDP client and server with Twisted Python


code:
from bottle import SimpleTemplate

tpl = SimpleTemplate("""Make = <SELECT name="where_make">
        % for make in makes:
            <option value="{{make}}" {{!'selected="selected"' if make == defaults['make'] else ""}}>{{make}}</option>
        %end""")
print tpl.render(make='test', defaults={'make': 'test'}, makes=['test'])

rawDescription: Python Bottle - Inline IF statements in Template


code:
from Crypto.Cipher import AES
import base64
import os
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
BLOCK_SZ = 14

# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'

# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
secret = "332SECRETabc1234"
iv = "HELLOWORLD123456"
cipher=AES.new(key=secret,mode=AES.MODE_CBC,IV=iv)
my_text_to_encode = "password"
encoded = EncodeAES(cipher, my_text_to_encode)
print 'Encrypted string:', encoded

rawDescription: Encrypt data with python, decrypt in php


code:
from datetime import timedelta
print datetime(2012, 1, 1) + timedelta(days=291)
# datetime.datetime(2012, 10, 18, 0, 0)

rawDescription: How to complete the information in a python time tuple?

description: Complete the information in a python time tuple


code:
for p in itertools.permutations(range(3)):
    if p[0] < p[-1]:
        print p

rawDescription: How to generate permutations of a list without "reverse duplicates" in Python using generators

description: Generate permutations of a list without "reverse duplicates" in Python using generators


code:
Input_List=[[1,2,3],[4,5,6],[7,8,9]]
for i,element in enumerate(Input_List):
    for j,item in enumerate(element):
        if item %2==0:
            Input_List[i][j]="Even"
        else:
            Input_List[i][j]="Odd"
print Input_List

rawDescription: Mapping Odd/Even to nested lists

description: Mapping Odd/Even to nested lists


code:
import datetime

a = 20120628061533.0

dt = datetime.datetime.strptime(str(int(a)), '%Y%m%d%H%M%S')
dt -= datetime.timedelta(minutes=1)

print dt.strftime('%Y%m%d%H%M%S')

rawDescription: Subtracting seconds from int with no formatting


code:
def print_dict(d, current_depth=1):
    for k, v in d.items():
        if isinstance(v, dict):
            print '-' * current_depth + str(k)
            print_dict(v, current_depth + 1)
        else:
            print '-' * current_depth + str(k) + ':' + str(v)

rawDescription: Python Looping Entire Dictionary

description: Python Looping Entire Dictionary


code:
from pymongo.uri_parser import parse_uri

mongo_uri = 'mongodb://james:brewer@localhost/test'

for k, v in parse_uri(mongo_uri).items():
    print k, ':', v

rawDescription: Pymongo MongoClient: if you put a database in via URI, how do you get it back out?


code:
xml = et.XML("<root><test/>whatever<end_test/></root>")
root = tree.getroot()
root[:] = xml
root.text, root.tail = xml.text, xml.tail
print et.tostring(tree, xml_declaration=True, encoding="utf-8")

rawDescription: Creating a doctype with lxml's etree

description: Creating a doctype with lxml's etree


rawDescription: Python Improve List Compare Speed

description: Python Improve List Compare Speed


code:
with open(r'path to input file') as f:
    inputfileContents = f.readlines()

def printLines(lines):
    loop_cnt = []
    label_to_idx = {}
    for i, line in enumerate(lines):
        line = line.split('#')[0] #removing comments
        print line.split('{')[-1].split('}')[0]
        line_label = line.split('{')[0].strip()
        line_label = line_label.replace(':','') #I assume the colon is a typo?
        label_to_idx[line_label] = i

        if line.startswith('Jump '):
            if not loop_cnt:
                return
            jump_label = line.split()[1]
            start = label_to_idx[jump_label]
            loopCount = loop_cnt.pop()
            for cnt in range(loopCount):
                printLines(lines[start:])
        elif line.startswith('Loop '):
            loopCount = int(line.split()[1])-1
            loop_cnt.append(loopCount)

printLines(inputfileContents)

rawDescription: How to decompress a nested loop in a file : Python

description: Decompress a nested loop in a file : Python


code:
import re
stri = "Hello guys.\nHow are you doing?\nI hope you have sweet dreams tonight."
regex = re.compile("guys.*$", re.DOTALL)
print regex.findall(stri)

rawDescription: Fetching a part of a string using regex starting from a given word untill the end of the string(one that includes newlines)


code:
from Tkinter import *
import time
import RPi.GPIO as GPIO

class App():

    def __init__(self, master):

        self.master = master

        self.frame = Frame(master)

        self.p2diagString = "Player 2 Score: "
        self.p2score = 0

        self.p2diag = StringVar()
        self.p2diag.set(self.p2diagString + str(self.p2score))

        p2Label = Label(self.frame, fg="white", bg="blue", textvariable=self.p2diag)
        p2Label.grid(row=1, column=1)

        self.startGameButton = Button(
            self.frame, text="Start Game!", command=self.start_game
        )
        self.startGameButton.grid(row=3, columnspan=2)

    def p2ScoreEvent(self, p1pin):
        print "ScoreEvent"

        self.p2score += 1
        self.p2diag.set(self.p2diagString + str(self.p2score))

    def start_game(self):
        self.game_time = 30
        self.end_time = time.time() + self.game_time

        P1PIN = 23
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(P1PIN, GPIO.IN)
        GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent)

        try:
            GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent)
            self.my_loop()
        except:
            print "Something went wrong..."
            GPIO.cleanup()

    def my_loop(self):
        if time.time() < self.end_time:
           print "listening"
           root.after(5000, self.my_loop) # run my_loop again after 5000 milliseconds

    def run(self):
        self.master.mainloop()

#----------------------------------------------------------------------

App(Tk()).run()

rawDescription: Python RaspberryPi GPIO Event Detection in Tkinter Failing


code:
import pytz
import datetime
s = '2013:07:04:14:00'
mydate = datetime.datetime.strptime(s, '%Y:%m:%d:%H:%M')
mydate = mydate.replace(tzinfo=timezone('Australia/Sydney'))
print mydate

rawDescription: Python date string manipulation based on timezone - DST


code:
import a
a.user = '4343'
print a.foo()

rawDescription: modifying a variable from python module in second script for function in first script

description: Modifying a variable from python module in second script for function in first script


code:
for col in dp.columns:
    print 'column', col,':', col[0]

rawDescription: Setting column types while reading csv with pandas


code:
import hashlib
import base64

def obfuscate(s):
    m = hashlib.sha256()
    m.update(s)
    hash = base64.b64encode(m.digest(), altchars="ZZ")  # make one way base64 encode, to fit characters into alphanum space only
    return hash[:16]    # cut of hash at 16 chars - gives about 96 bits which should
    # 96 bits means 1 in billion chance of collision if you have 1 billion tags (or much lower chance with fewer tags)
    # http://en.wikipedia.org/wiki/Birthday_attack

print obfuscate('Tag 1')
print obfuscate('Tag 2')
print obfuscate('Tag 3')

rawDescription: Encrypt a string in Python. Restrict the characters used to only alphanumeric


rawDescription: Reverse itemgetter (itemsetter?): inserting a list of items into specific positions in a larger list


code:
listone = [5,5,5,6,7,8,9]
listtwo = [4,2,3,4,5,6,7]
for _ in range(len(listone)):
    x, y = listone[_], listtwo[_]
    value = y/float(x)*100
    print "In a survey %.2f%% of dentists recommend this toothpaste" % value

rawDescription: Average out two list Python3

description: Average out two list Python3


code:
import re
from bs4 import BeautifulSoup

data = "your html"
soup = BeautifulSoup(data)

pattern = re.compile("http://example.com/Stuff/preview/v/\d+/fl/1/t/")
print soup.find_all('a', {'href': pattern})

rawDescription: Finding all links matching specific URL template in an HTML page


code:
for l in d.values():
   if len(l) < 10: continue

   print 'Same key found %d times:' % len(l)

   for filename, line in l:
       print '%s: %s' % (filename, line)

rawDescription: Multiple file comparison

description: Multiple file comparison


code:
password=None
def function():
  global password
  password = blahblah

def function2():
  print password

rawDescription: TypeError: password() takes exactly 1 argument (0 given)


code:
from psycopg2.extensions import AsIs

data_list = [
    {
        'extra': 'ex1',
        'produktcode': 'ACE001',
        'typ': 'A',
        'hotelname': 'foo01',
        'kategorie': 3,
        'size': 'big'
    },
    {
        'extra': 'ex2',
        'produktcode': 'ACE002',
        'typ': 'B',
        'hotelname': 'foo02',
        'kategorie': 4,
        'size': 'small'
    }
]

heads = data_list[0].keys()

insert_statement = 'insert into stamm_data (%s) values %s'

for d in data_list:

    print cursor.mogrify(insert_statement, (
        AsIs(','.join(heads)),
        tuple([d[head] for head in heads])
    ))

rawDescription: Passing a list of column names and values to Psycopg


code:
import itertools

epochs = [10, 100]
architecture = [5, 10]

for epock in epochs:
    for nodes_count in xrange(1, 4):
        combinations = itertools.product(architecture, repeat=nodes_count)
        for combination in combinations:
            print epock, list(combination)

rawDescription: How could all combinations of a set of possible arguments of a function be tried and the resultant values be collected?


code: print '\n'.join(textwrap.wrap(s, 80))

rawDescription: Is there a nice way splitting a (potentially) long string without splitting in words in Python?


code:
import urllib2
from bs4 import BeautifulSoup
url = 'http://www.amazon.com/dp/B00IOXUJRY'
page = BeautifulSoup(urllib2.urlopen(url), 'html.parser')
print page.find(id='productTitle')
page = BeautifulSoup(urllib2.urlopen(url), 'html5lib')
print page.find(id='productTitle')
page = BeautifulSoup(urllib2.urlopen(url), 'lxml')
print page.find(id='productTitle')

rawDescription: BeautifulSoup find function unusual behaviour


code:
from cStringIO import StringIO
import struct
import time

def decode(f):

    def read_le16(f):
        return struct.unpack('<h', f.read(2))[0]

    def read_timestamp(f):
        ts = struct.unpack('<l', f.read(4))[0]
        return time.ctime(ts)

    def read_byte(f):
        return ord(f.read(1))

    def read_pascal(f):
        l = ord(f.read(1))
        return f.read(l)

    result = []

    # Read total length
    result.append('Total message length is %d bytes' % read_le16(f))

    # Read timestamp
    result.append(read_timestamp(f))

    # Read 3 x byte
    result.append(read_byte(f))
    result.append(read_byte(f))
    result.append(read_byte(f))

    # Read 1 x LE16
    result.append(read_le16(f))

    # Read 3 x pascal string
    result.append(read_pascal(f))
    result.append(read_pascal(f))
    result.append(read_pascal(f))

    return result

s = 'L\x00k\x07vQ\n\x01\xffh\x00\x04NGIN\x04MAIN6Product XX finished reprocessing cdc XXXXX at jesadr 0c\x00k\x07vQ\n\x01\xffF\x00\x06CSSPRD\x0cliab_checkerCCheckpointed to XXXXXXXXXXXXXXXX:XXXXXXX.XXX at jesadr 0 (serial 0)[\x00l\x07vQ\n\x00\xff\x01\x00\x05MLIFE\x06dayendBdayend 1 Copyright XXXX XXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXX.'

f = StringIO(s)
print decode(f)
print decode(f)
print decode(f)

rawDescription: Python unpacking binary stream from tcp socket


code:
import re

ss = '''qslkjqskqsdhf
#start
REPLACE ANYTHING IN HERE
#end
2135468761265
'''

reg = re.compile('(?<=#start)(\r?\n)'
                 '(.*?)'
                 '(?=\r?\n#end)',re.DOTALL)

print ss
print '----'
print reg.sub('\\1Ia orana',ss)

rawDescription: Find and replace everything between two placeholders with the contents of a variable


code:
import maya.cmds as cmds
from PySide import QtCore, QtGui
from maya import OpenMayaUI as omui
from shiboken import wrapInstance

def getMayaWindow():
    omui.MQtUtil.mainWindow()
    ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(ptr), QtGui.QWidget)

newPath = r"C:\Users\pfruchet\Desktop\NewSceneName.ma"

mayaWindow = getMayaWindow()

print mayaWindow.windowTitle() #Prints the window title with your original scene path
cmds.file(rename = newPath)
print mayaWindow.windowTitle() #Prints the window title with your original scene path
print cmds.file(query=True, sn=True) #But Prints C:/Users/pfruchet/Desktop/NewSceneName.ma ---> Scene name changed but not updated in window title

mayaWindow.setWindowTitle(r"Autodesk Maya 2014: " + newPath) #here is the magic
print mayaWindow.windowTitle() #Prints Autodesk Maya 2014: C:\Users\pfruchet\Desktop\NewSceneName.ma
mayaWindow.setWindowModified(False)

rawDescription: Maya - How to update file name displayed on menu bar after renaming the scene


code:
import csv
from xml.etree.ElementTree import Element, SubElement, tostring

root = Element('viewpointlist')
with open('test.csv') as f:
    reader = csv.DictReader(f)
    for line in reader:
        child = SubElement(root, "viewpoint")

        element = SubElement(child, 'vpid')
        element.text = line['FRAME']
        element = SubElement(child, 'lat')
        element.text = line[' LAT']
        element = SubElement(child, 'lng')
        element.text = line[' LON']

print tostring(root)

rawDescription: CSV file, need to extract data, format data and convert to xml


code:
from mpi4py import MPI
import pdb
import os

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

assert size == 2

# Declare the array that will store all the temp results
temps = [[0 for x in xrange(5)] for x in xrange(4)]

# declare the array that holds the local results
locals =[[0 for x in xrange(5)] for x in xrange(2)]

# Loop over all directories
if rank==0:
   counter = 0
   for i in range(2):
      for j in range(5):
         locals[i][j] = counter
         counter = counter + 1

else:
   counter = 20
   for i in range(2):
      for j in range(5):
         locals[i][j] = counter
         counter = counter + 1

temps = comm.gather(locals,temps,root=0)

if rank==0:
   print temps

rawDescription: How to share data between processes in Python using MPI?

description: Share data between processes in Python using MPI


code:
#!/usr/bin/env python
import sqlparse

sql = """
select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where
"""

print sqlparse.format(sql, reindent=True)

rawDescription: sql nested select parsing

description: Sql nested select parsing


code:
import timeit

groups = dict(('1037_%d' % i, ["a","b","c","d","e"]) for i in xrange(100))

class FOut(object):
    def write(self, v):
        #print v
        pass

file_out = FOut()

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

def initial_version():
    for l in groups.iteritems():
        for p in xrange(len(l[1])):
            file_out.write(l[1][p])

def seq_iteration():
    for l in groups.iteritems():
        for p in l[1]:
            file_out.write(p)

def seq_iteration_values():
    for l in groups.itervalues():
        for p in l:
            file_out.write(p)

def list_compr():
    [[file_out.write(v) for v in g] for g in groups.itervalues()]

tests = ('initial_version', 'using_map', 'seq_iteration', 'list_compr', 'seq_iteration_values')

for test in tests:
    print test, timeit.timeit('%s()'%test, 'from __main__ import %s'%test, number=10000)

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


code:
from itertools import product, combinations, chain
L = [(1, 2, 3), (2, 4)]
def powerset(iterable):
    "powerset minus the empty element"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))

print [list(chain.from_iterable(c)) for c in product(*(powerset(x) for x in L))]

rawDescription: combinations of elements of different tuples in the list

description: Combinations of elements of different tuples in the list


code:
VARIABLEHERE = "myToken"
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('GET', '/1/users/%s'%VARIABLEHERE, '', {
"X-Parse-Application-Id"
})
result = json.loads(connection.getresponse().read())
print result

rawDescription: String formatting in Python?

description: String formatting in Python


code:
html = """<DOC>
<DOCNO> XXX-2222 </DOCNO>
<FILEID>AP-NR-02-12-88 2344EST</FILEID>
<HEAD>Reports Former Saigon Officials Released from Re-education Camp</HEAD>
<TEXT>
Lots of text here
</TEXT>
</DOC>
"""

import bs4

d = {}

soup = bs4.BeautifulSoup(html, features="xml")
docs = soup.findAll("DOC")
for doc in docs:
    d[doc.DOCNO.getText()] = (doc.HEAD.getText(), doc.TEXT.getText())

print d
#{u' XXX-2222 ':
#   (u'Reports Former Saigon Officials Released from Re-education Camp',
#    u'\nLots of text here\n')}

rawDescription: Beautifulsoup HTML data extraction with BeautifulSoup and Python


code:
try:
  import readline
except ImportError:
  print "Module readline unavailable."
else:
  import rlcompleter
  readline.parse_and_bind("tab: complete")

rawDescription: python prompt with a bash like interface

description: Python prompt with a bash like interface


code:
import copy

a = [[13, 15, 17], [66,77], [1, 2, 4], [1,7,9]]

#- Get base
base = None
length_a = len(a)
base_flag = True
i = -1
while base_flag and i!=length_a-1:
    i += 1
    item = a[i]
    for j in xrange(i+1, length_a):
        tmp = set(item).intersection(set(a[j]))
        if tmp:
            base = set(item)
            base_flag = False
            break

print "Selected base:", base
if base:
    tmp_list = copy.copy(a)
    target_index = i
    tmp_list.pop(target_index)
    flag = True
    while flag:
        flag = False
        for i, item in enumerate(tmp_list):
            tmp = base.intersection(set(item))
            if tmp:
                base.update(set(item))
                tmp_list.pop(i)
                flag = True
                break

    print "base:", base
    print "tmp_list:", tmp_list
    result = tmp_list
    result.insert(target_index, list(base))

else:
    result = a

print "\nFinal result:", result

rawDescription: Nested lists , check if one list has common elements with other and if so join


code:
for white_net in myWhiteList:
    if my_ip in white_net:
        print "My IP is in the whitelist! Yay!"
        break

rawDescription: How to determine if IP address in whitelist with IPy?

description: Determine if IP address in whitelist with IPy


code: print str(count) + '  ' + str(conv)

rawDescription: How do I add space between two variables after a print in Python

description: Add space between two variables after a print in Python


code:
import math

class IntegerBasedFloat(float):
    def __format__(self, spec):
        value = float(self)

        # apply the following only, if the specifier ends in Q
        # otherwise, you maintain the original float format
        if spec.endswith('Q'):
            # split the provided float into the decimal
            # and integer portion (for this math is required):
            DEC, INT = math.modf(value)

            # determine the length of the integer portion:
            LEN = len(str(abs(int(INT))))

            # calculate the number of available decimals
            # based on the overall length
            # the -1 is required because the separator
            # requires one digit
            DECIMALS = int(spec[-2]) - LEN - 1

            if DECIMALS < 0:
                print 'Number too large for specified format'
            else:
                # create the corresponding float formatter
                # that can be evaluated as usual:
                spec = spec[-2] + '.' + str(DECIMALS) + 'f'

        return format(value, spec)

DATA = [12.345, 2.3456, 345.6789]

print '{:4Q}'.format(IntegerBasedFloat(DATA[0]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[1]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[2]))
print 'This is a "custom" float: {:5Q} and a "regular" float: {:5.3f}'.format(IntegerBasedFloat(12.3456),12.3456)

rawDescription: Fixed digits number in floats

description: Fixed digits number in floats


code:
import re

def doot(x):
    return '\.?'.join(ch for ch in x) + '\.?'

def regexize(labels,doot=doot,
             wg2 = '(%s) *( %s)',wnog2 = '(%s)(%s)',
             ri = re.compile('(.(?!.*? )|[^ ]+)( ?) *(.+\Z)')):
    to_join = []
    modlabs = {}
    for K in labels.iterkeys():
        g1,g2,g3 = ri.match(K).groups()
        to_join.append((wg2 if g2 else wnog2)
                       % (doot(g1), doot(g3.lower())))
        modlabs[g1+g2+g3.lower()] = labels[K]
    return (re.compile('|'.join(to_join), re.I), modlabs)

def code(X,labels,regexize = regexize):
    reglab,modlabs = regexize(labels)
    for ma in reglab.finditer(X):
        a,b = tuple(x for x in ma.groups() if x)
        k = (a + b.lower()).replace('.','')
        GV = modlabs[k] if k in modlabs else '- bad match -'
        yield '  {!s:15}  {!s:^13}'.format(a+b, GV)

countries = {'Singapore':'SG','Austria':'AU',
             'Swiss':'CH','Chile':'CL',
             'Den LMM':'DN','LMM Den':'LM'}

assert(all('.' not in k and
          (k.count(' ')==1 or k[0].upper()==k[0])
          for k in countries))

s = ('  Singapore  SIngapore  SiNgapore  SinGapore'
     '  SI.Ngapore  SIngaPore  SinGaporE  SinGAPore'
     '  SINGaporE  SiNg.aPoR   singapore  sIngapore'
     '  siNgapore  sinGapore  sINgap.ore  sIngaPore'
     '  sinGaporE  sinGAPore  sINGaporE  siNgaPoRe'
     '    Austria    Aus.trIA    aUSTria    AUSTRiA'
     '  Den L.M.M     Den   Lm.M    DEn Lm.M.'
     '  DEN L.MM      De.n L.M.M.     Den LmM'
     '    L.MM   DEn      LMM DeN     LM.m  Den')

print '\n'.join(res for res in code(s,countries))

rawDescription: Python RE ( In a word to check first letter is case sensitive and rest all case insensitive)


code:
class A(object):
  def test(self):
    print message

class B(A):
  pass

def main():
  global message
  message = "hello"
  A().test()
  B().test()

  # resolve circular import by importing in local scope
  import mod2
  mod2.C().test()

if __name__ == "__main__":
  # break into mod1 namespace from __main__ namespace
  import mod1
  mod1.main()

rawDescription: How does name resolution work when classes are derived across modules?


code: print repr(x)

rawDescription: Decimal(str(my_float)) seems to be better than Decimal(my_float), what's going on?


code:
for filename in ftp.nlst(filematch):
    target_file_name = os.path.basename(filename)
    with open(target_file_name ,'wb') as fhandle:
        ftp.retrbinary('RETR %s' % filename, fhandle.write)
    the_files.append(target_file_name)
    mtime = modification_date(target_file_name)
    mtime_str_for_file = str(mtime)[0:10] + str(mtime)[11:13] + str(mtime)[14:16]    + str(mtime)[17:19] + str(mtime)[20:28]#2014-12-11 15:08:00.338415.
    sorted_xml_files = [file for file in glob.glob(os.path.join('\\\\Storage\\shared\\', '*.xml'))]
    sorted_xml_files.sort(key=os.path.getmtime)
    last_file = sorted_xml_files[-1]
    file_is_the_same = filecmp.cmp(target_file_name, last_file)
    if not file_is_the_same:
        print 'File changed!'
        copyfile(target_file_name, '\\\\Storage\\shared\\'+'datebreaks'+mtime_str_for_file+'.xml')
    else:
        print 'File '+ last_file +' hasn\'t changed, doin nothin'
        continue

rawDescription: Python shutil copyfile - missing last few lines


code:
class MagicWrapper(object):
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __getattr__(self, attr):
        return getattr(self._wrapped, attr)

    def __setattr__(self, attr, val):
        if attr == '_wrapped':
            super(MagicWrapper, self).__setattr__('_wrapped', val)
        else:
            setattr(self._wrapped, 'old_' + attr, getattr(self._wrapped, attr))
            setattr(self._wrapped, attr, val)

class MyObject(object):
    def __init__(self):
        self.attr_one = None
        self.attr_two = 1

obj = MyObject()
obj = MagicWrapper(obj)
obj.attr_one = 'new value'
obj.attr_two = 2

print obj.old_attr_one
print obj.attr_one
print obj.old_attr_two
print obj.attr_two

rawDescription: Track changes of atributes in instance. Python


code:
found_in_data_portgroup  = [pg for pg in portgroups if pg in data_portgroup["data_portgroup"]]
found_in_mgmt_portgroup  = [pg for pg in portgroups if pg in mgmt_portgroup["mgmt_portgroup"]]
found_in_trunk_portgroup = [pg for pg in portgroups if pg in trunk_portgroup["trunk_portgroup"]]

print found_in_data_portgroup
print found_in_mgmt_portgroup
print found_in_trunk_portgroup

rawDescription: How to check dictionary items are present in the list ? PYTHON

description: Check dictionary items are present in the list ? PYTHON


code:
from subprocess import PIPE, Popen
import time

title = ''
root_check = ''

while True:
    time.sleep(0.6)
    root = Popen(['xprop', '-root'],  stdout=PIPE)

    if root.stdout != root_check:
        root_check = root.stdout

        for i in root.stdout:
            if '_NET_ACTIVE_WINDOW(WINDOW):' in i:
                id_ = i.split()[4]
                id_w = Popen(['xprop', '-id', id_], stdout=PIPE)

        for j in id_w.stdout:
            if 'WM_ICON_NAME(STRING)' in j:
                if title != j.split()[2]:
                    title = j.split()[2]
                    print "current window title: %s" % title

rawDescription: Xorg, Python, and Current Window Title

description: Xorg, Python, and Current Window Title


rawDescription: Adding values corresponding to one key in python dictionary


code:
from maya import cmds
import math
def drawHelix(radius, length, coils):
    numPoints = int(8)
    degrees = float((360 / numPoints))
    centerX = float(0)
    centerZ = float(0)
    xLoc = float(0)
    zLoc  = float(0)
    yLoc  = float(0)
    yOffset = float(((length / float(coils)) / float(numPoints)))
    vectorIndex = int(0)
    pointStr = []
    knotStr = []
    yLoc = 0
    for i in range(1, (360 * coils), 20):
        t = i + degrees
        xLoc = centerX + (math.cos(t) * radius)
        zLoc = centerZ - (math.sin(t) * radius)
        pointStr.append((xLoc, yLoc,zLoc))
        knotStr.append(vectorIndex)
        vectorIndex = i + 1
        yLoc = yLoc + yOffset
    print pointStr
    spiral = cmds.curve(p= pointStr, k=knotStr,d=float(1.0))
    cmds.rebuildCurve (spiral, ch=1, rpo=1,
                       rt=0, end=1, kr=1, kcp=0, kep=0,
                       kt=0, s=0, d=3, tol=0.001)
    return spiral

rawDescription: Maya Variable Concatenation

description: Maya Variable Concatenation


code:
import abc

class MyInterface(object):
    """docstring for MyInterface"""

    __metaclass__ = abc.ABCMeta

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

    @abc.abstractmethod
    def test(self):
        pass

class MyClass(MyInterface):
    """docstring for MyClass"""
    def __init__(self, arg):
        super(MyClass, self).__init__(arg)

    def test(self):
        """docstring for test"""
        print self.arg

class MyImplementation(object):
    __implements__ = (MyClass, )

rawDescription: Why pylint keeps saying my class is R0923 - 'interface not implemented'


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


code:
l = list(myset)
l_copy = [x for x in l]
for k in l_copy:
    l = l[1:]
    print l

rawDescription: delete items from a set while iterating over it

description: Delete items from a set while iterating over it


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

expr = lambda (a,b) : a
expr = nest((lambda x, (a, b): x + (a - b)), expr)
expr = nest((lambda x, (a, b): x + (a - b)), expr)

print expr((1,2)) # prints -1

rawDescription: Concatenation/creation of symbolic expressions/statements


code:
class Super(object):
    def __init__(self):
        print 'init super'
        if self.__class__ == Super:
            self.load()
    def load(self):
        print 'load super'

class Sub(Super):
    def __init__(self):
        # always do super first in init
        super(Sub, self).__init__()
        print 'init sub'
        self.load()
    def load(self):
        # load is essentially an extension of init
        # so you still need to call super first
        super(Sub, self).load()
        print 'load sub'

sub = Sub()

rawDescription: Calling load functions in correct order from constructors


code: print " ".join(map(ord, raw_input("input something")))

rawDescription: Is it possible to suppress Python's escape sequence processing on a given string without using the raw specifier?


code:
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print = True)

rawDescription: Read an XML file with tags and indentation into a python variable


rawDescription: Python regex to parse semi-fixed width file


code:
columns = ['value']
with open(waveform, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        rec = dict(zip(columns, row))
        print rec

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


code:
def highlight_one(text, keyword):
    replacement = "\033[91m" + keyword + "\033[39m"
    text = re.sub(re.escape(keyword), replacement, text, flags=re.I)
    print text

rawDescription: Highlight multiple words using Regex function


code:
def wrapper(x, y):
    if compare(x, y):
        print 'Proceed further'
    else:
        print 'Break'

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

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


code:
import inspect

class Inspector:
    def __init__(self, passedFunc):
        self.passedFunc = passedFunc

    def __call__(self, *args, **kwargs):

        spec = inspect.getargspec(self.passedFunc)
        params = dict(zip(spec.args, args))
        defaults = dict(zip(spec.args[-len(spec.defaults):], spec.defaults))

        for k, v in kwargs.items():
            if k not in spec.args:
                raise TypeError('unexpected argument', k)
            if k in params:
                raise TypeError('mulitple values for argument', k)
            params[k] = v

        for k in spec.args:
            if k not in params:
                if k in defaults:
                    params[k] = defaults[k]
                else:
                    raise TypeError('missing argument', k)

        args_in_order = [params[x] for x in spec.args]

        print args_in_order

rawDescription: generate a list of arguments in correct order from args and kwargs?

description: Generate a list of arguments in correct order from args and kwargs


code:
match_model = lambda m: m in ['Crz', 'Bmw 320 D', 'Benz', 'Mercedes_E 350 Cdi',   'Toyota_Corolla He 1.8']

for c in df:
    if df[c].map(match_model).sum()/len(df) > 0.1:
        print "Column %s is 'Model'"% c
        df.rename(columns={c:'Model'}, inplace=True)

rawDescription: Rearrange CSV data

description: Rearrange CSV data


code: print datetime.datetime.now(EST())

rawDescription: Python - datetime of a specific timezone


code:
load_profile = open('users/file.txt', "r")
read_it = load_profile.readline()
print read_it

rawDescription: How do you read a specific line of a text file in Python?

description: Read a specific line of a text file in Python


code:
def a(lst, target, with_replacement=False):
    def _a(idx, l, r, t, w):
        if t == sum(l): r.append(l)
        elif t < sum(l): return
        for u in range(idx, len(lst)):
            _a(u if w else (u + 1), l + [lst[u]], r, t, w)
        return r
    return _a(0, [], [], target, with_replacement)

def b(lst, target, subset_lengths=range(1, 21), method='combinations'):
    import itertools
    return [comb for i in subset_lengths for comb in
            getattr(itertools, method)(lst, i) if sum(comb) == target]

vals = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186]

from timeit import timeit
print 'no replacement'
print timeit("a(vals, 270)", "from __main__ import vals, a", number=10)
print timeit("b(vals, 270)", "from __main__ import vals, b", number=10)
print 'with replacement'
print timeit("a(vals, 270, True)", "from __main__ import vals, a", number=10)
print timeit("b(vals, 270, method='combinations_with_replacement')", "from __main__ import vals, b", number=10)

rawDescription: Finding Combinations to the provided Sum value


code:
from collections import OrderedDict
from operator import itemgetter

# store all key,value pairings to sort later
items = []
for item in lines:
    specificy = c[item]
    try:
        MI1= specificy/float(specificx)
        MI2= MI1*specificx
        M13= specificx*specificx
        Mutual_Information = MI1* math.log(MI1/float(MI2))
        # add tuple of key/value to items
        items.append((item,Mutual_Information))
    except ZeroDivisionError:
        print "divide by zero"

# create OrderedDict from sorted items, sorting by the second element
d = OrderedDict(sorted(items,key=itemgetter(1),reverse=True))

rawDescription: storing variables in dictionary and descending order sorting

description: Storing variables in dictionary and descending order sorting


code:
data = tldextract.extract('http://example.com.mx')
print '{0}.{1}'.format(data.domain, data.suffix)

rawDescription: How to crawl shortened urls and get the actual domain in python?

description: Crawl shortened urls and get the actual domain in python


code:
from pygsr import Pygsr
speech = Pygsr()
# duration in seconds
speech.record(3)
# select the language
phrase, complete_response = speech.speech_to_text('en_US')

print phrase

rawDescription: Getting started with speech recognition and python