code:
# you can ignore this part, it's only here for the demo
from StringIO import StringIO
HTML = StringIO("""
<html>
<body>
    <form name="form1" action="/foo">
        <input name="uselessInput" type="text" />
    </form>
    <form name="form2" action="/bar">
        <input name="firstInput" type="text" />
        <input name="secondInput" type="text" />
    </form>
</body>
</html>
""")

# here goes the useful code
import lxml.html
tree = lxml.html.parse(HTML) # you can pass parse() a file-like object or an URL
root = tree.getroot()
for form in root.xpath('//form[@name="form2"]'):
    for field in form.getchildren():
        if 'name' in field.keys():
            print field.get('name')

rawDescription: Extracting Fields Names of an HTML form - Python


code:
import serial
import re

ser = serial.Serial('/dev/tty.usbserial-AH02MAUE', 9600)

def rfidResponse(responseID):
    #rID = responseID.strip() #no need for stripping, instead do the next line:
    #print responseID #you can print without `repr`.
    print responseID
    if responseID == "750047FB76BF":
        print "This one"
    else:
        print "other one"

while True:
    try:
        responseID = ser.readline()
        #stringResponse = str(response) # you don't need this line
        response = re.search('[A-Z0-9]{12}(?=\s+)', responsID) #your NFC ID should be of fixed length
        if response:
            rfidResponse(response.group(0))
        else:
            print 'No NFC ID received'
    except KeyboardInterrupt:
        ser.close() #better also close `serial` communication in case of exception
        break

ser.close()

rawDescription: A better way to get the value of an NFC card?


code:
#!/usr/bin/env python

"""Generate a css file thanks to pygments that will contain both short
and long class names."""

import subprocess
import sys

PYGMENTIZE = 'pygmentize'

def parse_command_line():
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-s', '--style', default='colorful')
    parser.add_argument('-p', '--prefix', default='.highlight')
    return parser.parse_args()

def pygmentize(style, prefix='.highlight'):
    cmd = '{0} -f html -S {1} -a {2}'.format(PYGMENTIZE, style, prefix)
    # This will fail if pygmentize does not exist.
    try:
        p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    except OSError:
        print >> sys.stderr, '{0}: command not found'.format(PYGMENTIZE)
        exit(1)

    out, err = p.communicate()
    if p.returncode != 0:
        exit(p.returncode)
    return out

def main():
    args = parse_command_line()
    style = args.style
    prefix = args.prefix

    # Print new css header.
    header = """\
/*
 * This is pygment css style {0} generated with
 *     {1}
 */""".format(style, ' '.join(sys.argv))
    print header

    # Parse pygmentize output.
    # Find long names based on comments.
    content = pygmentize(style, prefix)
    s = content.splitlines()
    out = ''
    for line in s:
        start = line.find("/* ") + 3
        end = line.find(" */")
        # if line has a comment
        if start != 2:
            comment = line[start:end]
            name = '.' + comment.lower()
            arg = line[line.find('{ '): start - 4]
            out += '%(prefix)s %(name)s %(arg)s\n' % vars()

    print content
    print out

if __name__ == '__main__':
    main()

rawDescription: Sphinx inline code highlight

description: Sphinx inline code highlight


code:
# idiomatic manner of importing numpy
import numpy as np

data = ['1 2 3.', '4. 5 8']
arraydata = np.array([[float(n) for n in row.split()] for row in data])
print arraydata

# [[ 1.  2.  3.]
#  [ 4.  5.  8.]]

rawDescription: Convert string with spaced out numbers into array


code:
s = u'o\ufb03ce'
print s
print [s]
print repr(s)
print '\n'.join([s])

rawDescription: Python - store chinese characters read from excel


code:
import urllib2
with open('books.json', 'rb') as data_file:
    my_data = data_file.read()
req = urllib2.Request(url='http://localhost:8983/solr/update/json?commit=true',
                      data=my_data)
req.add_header('Content-type', 'application/json')
f = urllib2.urlopen(req)
# Begin using data like the following
print f.read()

rawDescription: Convert solr curl updateJSON syntax to python using urllib2


code:
import socket

SERVER_ADDR = ("example.com", 80)

sock = socket.create_connection(SERVER_ADDR)
f = sock.makefile("r+", bufsize=0)

f.write("GET / HTTP/1.0\r\n"
      + "Host: example.com\r\n"    # you can put other headers here too
      + "\r\n")

# skip headers
while f.readline() != "\r\n":
    pass

# keep reading forever
while True:
    line = f.readline()     # blocks until more data is available
    if not line:
        break               # we ran out of data!

    print line

sock.close()

rawDescription: Reading HTTP server push streams with Python


code:
import gevent
import gevent.monkey
gevent.monkey.patch_all()

from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json

access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""

class MyStreamListener(StreamListener):
    def __init__(self):
        self.sockets = []
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        self.stream = Stream(auth, self)

    def add_socket(self, ws):
        self.sockets.append(ws)

    def run(self):
        try:
            self.stream.filter(track="#linux")
        except Exception:
            self.stream.disconnect()

    def start(self):
        gevent.spawn(self.run)

    def send(self, ws, coordinates):
        try:
            ws.send(json.dumps(coordinates))
        except Exception:
            # the web socket die..
            self.sockets.remove(ws)

    def on_data(self, data):
        decoded = json.loads(data)
        if decoded.get("coordinates", None) is not None:
            coordinates = decoded["coordinates"]["coordinates"]
            for ws in self.sockets:
                gevent.spawn(self.send, ws, coordinates)
        return True

    def on_error(self, status):
        print "Error", status

    def on_timeout(self):
        print "tweepy timeout.. wait 30 seconds"
        gevent.sleep(30)

stream_listener = MyStreamListener()
stream_listener.start()

def app(environ, start_response):
    ws = environ['wsgi.websocket']
    stream_listener.add_socket(ws)
    while not ws.closed:
        gevent.sleep(0.1)

server = pywsgi.WSGIServer(('', 10000), app, handler_class=WebSocketHandler)
server.serve_forever()

rawDescription: Consuming Twitter stream with tweepy and serving content via websocket with gevent


code:
class Foo (object):
    pass

Foo.lol = staticmethod (lambda: 1)
print Foo.lol ()

rawDescription: Is there a way to writing staticmethods to python classes outside of the classes without extending the class?


code:
if len(set(my_list)) < len(my_list):
    print "There's a dupe!"

rawDescription: How to compare values within an array in Python - find out whether 2 values are the same

description: Compare values within an array in Python - find out whether 2 values are the same


code:
class ControlPanel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.Bind(wx.EVT_SIZE, self.OnResize)

    def OnResize(self, *args, **kwargs):
        print "Resizing"

rawDescription: How to tell a panel that it is being resized when using wx.aui

description: Tell a panel that it is being resized when using wx.aui


code:
records = {}

for line in data:
    # parsing codes

    # store player -> gameid mappings to the index
    if player not in records:
        records[player] = []
    records[player].append(info)

print records['Sona']
# this should print out list of games played with Sona

rawDescription: Search list of dictionaries for name python


code:
from collections import defaultdict
from string import Formatter

fmtr = Formatter()
format_str = '{date} {version} {comment}'
data = defaultdict(lambda: 'N/A')

data['date'] = 'today'
data['version'] = 'v1'

print fmtr.vformat(format_str, (), data)

rawDescription: Formatting a defaultdict with keyword unpacking **


code:
import re
intext = """calf_n1 := n_-_c_le & n_-_pn_le &\n [ ORTH.FOO < "cali.ber,kl", 'calf' , "done" >,\nLKEYS.KEYREL.PRED "_calf_n_1_rel",\n ORHT2BAR <"what so ever >", "this that mess < up"> ,\n LKEYS.KEYREL.CARG "<20>",\nLOOSE.SCREW ">20 but <30"\n JOKE <'whatthe ', "what" >,\n THIS + ]."""
results = re.findall('\\n .*?([A-Z0-9\.]*) < *((?:[^>\n]|>")*) *>.*?(?:\\n|$)', intext)
print results

rawDescription: Recursively capture patterns in regex - Python


code:
from Crypto.Cipher import AES
from Crypto.Hash import SHA256

def sha1(text):
    s = SHA256.new()
    s.update(text)
    return s.hexdigest()

aes = AES.new('JG9A90cqiveJ8K7n', AES.MODE_CFB, 'g4vhFIR1KncRIyvO')

text = 'This is some text that will be encrypted'
encrypted_text = aes.encrypt(text)

aes = AES.new('JG9A90cqiveJ8K7n', AES.MODE_CFB, 'g4vhFIR1KncRIyvO')
decrypted_text = aes.decrypt(encrypted_text)

print 'Original:\t' + sha1(text)
print 'Encrypted:\t' + sha1(encrypted_text)
print 'Decrypted:\t' + sha1(decrypted_text)

rawDescription: Why is AES.decrypt not returning my original text?


code:
def check_file_ready(self, path):
    '''Check if file is not opened by another process.'''
    handle = None
    try:
        handle = win32file.CreateFile(
            path,
            win32file.GENERIC_WRITE,
            0,
            None,
            win32file.OPEN_EXISTING,
            win32file.FILE_ATTRIBUTE_NORMAL,
            None)
        return True
    except pywintypes.error, e:
        if e[0] == winerror.ERROR_SHARING_VIOLATION:
            # Note: other possible error codes include
            #  winerror.ERROR_FILE_NOT_FOUND
            #  winerror.ERROR_PATH_NOT_FOUND
            #  winerror.ERROR_ACCESS_DENIED.
            return False
        raise
    finally:
        if handle:
            win32file.CloseHandle(handle)

rawDescription: How to check a file saving is complete using Python?

description: Check a file saving is complete using Python


code:
df1 = pandas.DataFrame([[i*j for i in range(1, 3)] for j in range(2, 5)], index=list('abc'), columns=list('AB'))
print df1
df2 = pandas.DataFrame([[i*10**j for i in range(1, 4)] for j in range(1, 3)], columns=list('abc'))
print df2

df11 = df1.reindex(columns=pandas.MultiIndex.from_product([df1.columns, df2.index]), level=0)
print df11
df22 = df2.T.reindex(columns=pandas.MultiIndex.from_product([df1.columns, df2.index]), level=1)
print df22

df3 = df11.mul(df22)
print df3

rawDescription: how to multiply dataframes elementwise and create multi-index -- Python

description: Multiply dataframes elementwise and create multi-index -- Python


code:
import os

def find_paths(path):
    dir_names = []
    file_names = []
    path_names = []
    for dirname, dirnames, filenames in os.walk(path):
        for filename in filenames:
            # Combine dirname and filename into absolute path:
            filepath = os.path.join(dirname, filename)
            # Add info to lists:
            dir_names.append(dirname)
            file_names.append(filename)
            path_names.append(filepath)
    return dir_names, file_names, path_names

print find_paths(".") # Finds all dirs, files and paths in current folder.

rawDescription: get directories in bash

description: Get directories in bash


code:
theFile = open('thefile.txt','r')
FILE = theFile.readlines()
theFile.close()
printList = []
for line in FILE:
    if ('TestName' in line) or ('Totals' in line):
         # here you may want to do some splitting/concatenation/formatting to your string
         printList.append(line)

for item in printList:
    print item    # or write it to another file... or whatever

rawDescription: log file parsing python

description: Log file parsing python


code:
import cv2
import numpy as np
img = cv2.imread('image.png')

rows,cols,bands = img.shape
print rows,cols,bands

# Create image with new colour for replacement
new_colour_image= np.zeros((rows,cols,3), np.uint8)
new_colour_image[:,:]= (255,0,0)

# Define range of color to be exchanged (in this case only one single color, but could be range of colours)
lower_limit = np.array([0,0,0])
upper_limit = np.array([0,0,0])

# Generate mask for the pixels to be exchanged
new_colour_mask = cv2.inRange(img, lower_limit, upper_limit)

# Generate mask for the pixels to be kept
old_image_mask=cv2.bitwise_not(new_colour_mask)

# Part of the image which is kept
img2= cv2.bitwise_and(img,img, old_image_mask)

# Part of the image which is replaced
new_colour_image=cv2.bitwise_and(new_colour_image,new_colour_image, new_colour_mask)

#Combination of the two parts
result=cv2.bitwise_or(img2, new_colour_image)

cv2.imshow('image',img)
cv2.imshow('mask',new_colour_mask)
cv2.imshow('r',result)
cv2.waitKey(0)

rawDescription: How to copy a cropped image onto the original one, given the coordinates of the center of the crop

description: Copy a cropped image onto the original one, given the coordinates of the center of the crop


code:
import numpy as np
from collections import defaultdict

lb = np.genfromtxt('file2009.csv',dtype = None, delimiter = ',', names = True)
vms = np.genfromtxt('2009final.csv',dtype = None, delimiter = ',', names = True)

id_list = list(set(lb['ID']))

matchList = defaultdict(list)

for e in id_list:
    log = lb[lb['ID']==e]
    vms_list = vms[ np.logical_and(vms['date']==log[0]['date'] , vms['code']==log[0]['code'] )]
    print vms_list
    vms_id_list = list(set(vms_list['ID']))
    for row in log:
        if len(vms_id_list) == 1:
            break
        else:
            vmsIDs = vms[vms['ID'] == vms_id_list[0]]
            vms_ids = str(vms_id_list)
            for every in vms:
                if str(every['ID']) in vms_ids:
                    vmsIDs = np.hstack([vmsIDs, every])
            vms_id_list = []
            vms_list = vmsIDs[ np.logical_and(vmsIDs['date']==row['date'] , vmsIDs['code']==row['code'] )]
            vms_id_list = list(set(vms_list['ID']))
    matchList[e].append(vms_id_list)

rawDescription: Cannot perform task in python loop

description: Cannot perform task in python loop


code:
import sys
from contextlib import contextmanager

@contextmanager
def redirected(stdout):
    saved_stdout = sys.stdout
    sys.stdout = open(stdout, 'w')
    yield
    sys.stdout = saved_stdout

with redirected(stdout='file.txt'):
    print 'Hello'
print 'Hello again'

rawDescription: Python: storing print output from different module's function


code:
import random

def multiCaller(x):
        if x == 0:
                return []
        else:
                return [random.randint(0, 100)] + multiCaller(x-1)

def get_list(x):
    res = multiCaller(x)
    res.sort()
    return res

print get_list(5)

rawDescription: Using recursion to generate a list of X random numbers between 0 and 100, sorted from low to high in Python?


code:
# create the dict and save it to a file
d={
'part1':[
    'Ae',
    'Di',
    'Mo',
    'Fam',],
'part2':[
    'dar',
    'kil',
    'glar',
    'tres',],
}

import pickle
f=open('syllables','w')
pickle.dump(d,f)
f.close()

# read the dict back in from the file
f1=open('syllables','r')
sd=pickle.load(f1)
f1.close()

import random
first_part=sd['part1'][random.randint(0,len(sd['part1'])-1)]
second_part=sd['part2'][random.randint(0,len(sd['part2'])-1)]

print '%s%s'%(first_part,second_part)

rawDescription: Simple random name generator in Python

description: Simple random name generator in Python


code:
import time
limit_str = 'Wed Feb 26 12:30:00 2014'
limit = time.mktime(time.strptime(limit_str))

if time.time() > limit:
    print 'Demo time expired!'
else:
    print 'Program logic here'

rawDescription: build demo version .exe

description: Build demo version .exe


code:
tweet = "you're his i'm couldn't can't won't it's"
apostrophes = {"'s":" is","'re":" are","'ll":" will","'d":" would","i'm":"I am","I'm":"I am","won't":"will not", "'ve":" have","can't":"cannot","couldn't":"could not"}

for k, v in apostrophes.iteritems():
    tweet = tweet.replace(k, v)

print tweet # you are his I am could not cannot will not it is

rawDescription: Check for pattern and replace in words of sentence python


code:
import zipfile
import StringIO

path = "dev.zip"
encrypted_zip = zipfile.ZipFile( path  )
encrypted_zip.setpassword("pass")
print encrypted_zip.namelist()

with zipfile.ZipFile('spam.zip', 'w') as myzip:
    for nested_file in encrypted_zip.namelist():
        myzip.write(encrypted_zip.read(nested_file))

rawDescription: How to strip password encryption from zipfile with Python

description: Strip password encryption from zipfile with Python


code:
class Foo():

    l = []
    def __init__(self, x):
        self.l.append(x)
        print self.l

class Bar():

    def __init__(self, x):
        self.l = []
        self.l.append(x)
        print self.l

Foo(4) # prints [4]
Foo(4) # prints [4, 4]
Bar(4) # prints [4]
Bar(4) # prints [4]

rawDescription: Why is instantiating python class repeating former actions by other instances before doing new action?


code:
if any(n % x == 0 for x in mylist):
    print "Not Prime"

rawDescription: Is there a way to check a number against all numbers in a list?


code:
for one in many:
    print "Checking "+one
    url = "http://an.api/"+one
    contents = urllib2.urlopen(url)
    myData = contents.read()
    print len(myData) > 10
    if len(myData) > 10:
        print "online"
    else:
        print "offline"

rawDescription: If statements returning wrong data

description: If statements returning wrong data


code:
from functools import partial

def distance_squared(x, y):
    return (x[0] - y[0])**2 + (x[1] - y[1])**2

print min(big_list, key=partial(distance_squared, list_a))

rawDescription: Find the closest match of a list in a list containing lists


code:
import re
x=u'''
｜   配股次数     ｜      1       ｜ 募资总额(万元) ｜    834582.17     ｜
├────────┼───────┼────────┼─────────┤
｜   增发次数     ｜      1       ｜ 募资总额(万元) ｜    899850.51     ｜
├────────┼───────┼────────┼─────────┤
｜  发转债次数    ｜      1       ｜ 募资总额(万元) ｜    750000.00     ｜
├────────┴───────┴────────┼─────────┤
｜              再融资募资总额(万元)                ｜    2484432.68    ｜
├─────────────────────────┴─────────┤
｜                            ☆派现☆                                  ｜
├────────┬───────┬────────┬─────────┤
｜   派现次数     ｜      14      ｜ 派现总额(万元) ｜    1613873.88    ｜'''
print re.search(u'再融资募资总额\(万元\).*?(\d+\.\d+)', x).group(1)

rawDescription: how to extract the grouped number with search in python?

description: Extract the grouped number with search in python


code:
cmds.select("pCube1.vtx[*]")
sel = cmds.ls(sl=True)
print sel
# [u'pCube1.vtx[0:7]']
obj = cmds.ls(*sel, o=True)
print obj
# [u'pCubeShape1']

rawDescription: Get the mesh name from the selected vertex


code:
def unflatten(l):
  def helper(l, start):
    if isinstance(l[start], int):
      ret = []
      start += 1
      for _ in range(l[start - 1]):
        sub, start = helper(l, start)
        ret.append(sub)
      return ret, start
    else:
      return l[start], start + 1
  return helper(l, 0)[0]

print unflatten([2, 'x', 'y'])
print unflatten([ 3, "a", "b", 3, "t", "y", "u" ])
print unflatten([ 4, "a", "b", 3, "c", "d", 2, "x", "y", 2, "w" , 3, "t", "y", "u" ])

rawDescription: Unflattening a list in python

description: Unflattening a list in python


code:
def conv(m):
    return chr(int(m.group(1)))

pat = re.compile(r"""[+\s]*    # optional whitespace or +
                     \b        # word boundary
                     n?char    # NCHAR or CHAR
                     \(        # left paren
                     ([\d\s]+) # digits or spaces - group 1
                     \)        # right paren
                     [+\s]*    # optional whitespace or +
                  """, re.VERBOSE | re.IGNORECASE)
print pat.sub(conv, data)

rawDescription: Python regex for select/extract from nested groups


code:
import Tkinter, tkFileDialog

class Foo(object):
    def __init__(self, master):
        master.bind('<KeyPress-3>', self.do_bar)
        master.bind('<KeyPress-9>', self.load_new_config)

        self.load_config()

        if not self.conf:
            master.after(1, self.load_new_config)
        else:
            self.load_data()

    def load_config(self):
        try:
            self.conf = None#get stuff from known file
        except FailedToGetStuff:
            self.conf = None

    def load_new_config(self, e = 0):
        path = tkFileDialog.askopenfilename(initialdir='~')
        self.conf = None#get stuff from file in path
        self.load_data()

    def load_data(self, e = 0):
        pass
        #get data from self.conf, process and display

    def do_bar(self, e = 0):
        print 1
        #do stuff with displayed data

if __name__ == "__main__":
    root = Tkinter.Tk()
    Foo(root)
    root.mainloop()

rawDescription: Python TkInter bind breaking

description: Python TkInter bind breaking


rawDescription: In dictionary where keys are numbers, how to find key which is smaller but the most near to given number?


code:
# permute training data and score against its own model
epoch = 3
seeds = range(epoch)

scores = defaultdict(list) # {feature: change in R^2}

# repeat process several times and then average and then average the score for each feature
for j in xrange(epoch):
    clf = RandomForestRegressor(n_jobs = -1, n_estimators = trees, random_state = seeds[j],
                               max_features = num_features, min_samples_leaf = leaf)

    clf = clf.fit(X_train, y_train)
    acc = clf.score(X_train, y_train)

    print 'Epoch', j
    # for each feature, permute its values and check the resulting score
    for i, col in enumerate(X_train.columns):
        if i % 200 == 0: print "- feature %s of %s permuted" %(i, X_train.shape[1])
        X_train_copy = X_train.copy()
        X_train_copy[col] = np.random.permutation(X_train[col])
        shuff_acc = clf.score(X_train_copy, y_train)
        scores[col].append((acc-shuff_acc)/acc)

# get mean across epochs
scores_mean = {k: np.mean(v) for k, v in scores.iteritems()}

# sort scores (best first)
scores_sorted = pd.DataFrame.from_dict(scores_mean, orient='index').sort(0, ascending = False)

rawDescription: implementation of R random forest feature importance score in scikit-learn

description: Implementation of R random forest feature importance score in scikit-learn


code:
@app.route('/', methods=['POST'])
def parsexml():
    xmlrequest = xmltodict.parse(request.data)
    print xmlrequest
    return "Thanks for the data!"

rawDescription: Python requsts.post returning 405 error: The method is not allowed for the requested URL


code:
import subprocess
def _run_command( _args, input=[],withShell=False):
    """
    Pass args as array, like ['echo', 'hello']
    Waits for completion and returns
    tuple (returncode, stdout, stderr)
    """
    p = subprocess.Popen(_args, shell = withShell,
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    [p.stdin.write(v) for v in input]
    stdout, stderr = p.communicate()
    return p.returncode, stdout, stderr

_,op,er = _run_command(['cat'],["this","is","for","testing"])
value="".join(op)
print value

_,op,er = _run_command(['ls',"/tmp"])
value="".join(op)
print value

rawDescription: Communicating with a running process

description: Communicating with a running process


code:
#constants
TB = 2**43
GB = 2**33
MB = 2**23
KB = 2**13
BYTES = 2**3

#some test value here
fileSize = 8

#empty string to be filled and shown later
fileSizeStr = ""

#calculations
if fileSize >= TB:
    fileTB = fileSize / TB
    fileSize = fileSize % TB
    fileSizeStr += str(fileTB) + 'TB '

if fileSize >= GB:
    fileGB = fileSize / GB
    fileSize = fileSize % GB
    fileSizeStr += str(fileGB) + 'GB '

if fileSize >= MB:
    fileMB = fileSize / MB
    fileSize = fileSize % MB
    fileSizeStr += str(fileMB) + 'MB '

if fileSize >= KB:
    fileKB = fileSize / KB
    fileSize = fileSize % KB
    fileSizeStr += str(fileKB) + 'KB '

if fileSize >= BYTES:
    fileB = fileSize / BYTES
    fileSize = fileSize % BYTES
    fileSizeStr += str(fileB) + 'Byte(s) '

fileSizeStr += str(fileSize) + 'Bit(s)'

print fileSizeStr

rawDescription: Trouble outputing file size to a label from a listbox in Python 3


rawDescription: Printing numbers in python

description: Printing numbers in python


code:
import time
import random

high_score = []
def play_game():

    print "Welcome to my Number Press Game"
    print "the computer will display a number"
    print "you will have to enter the number before the time runs out"
    name = raw_input ("please enter your name: "+"\n")

    print "\n"+"welcome to the game "+name

    print "ready"
    time.sleep (1)
    print "steady"
    time.sleep (1)
    print "GO!"

    loop = -1
    t = 3
    score = 0

    while True:
        loop = loop+1
        x = random.randint(1,3)
        print x
        start = time.time()
        num = input("the number is: ")
        end = time.time()
        elapsed = end - start
        if elapsed > t and num == x:
            print "CORRECT, but too slow"
            break

        elif num != x and elapsed < t:
            print "\n"+"WRONG, but in time"
            break
        elif num != x and elapsed > t:
            print "WRONG and too slow"
            break

        if num == x and elapsed< t:
           print "CORRECT and in time"
           score += 1

           if t>0.7:
               t = t*0.9

    high_score.append(score)

    print "you loose"
    print name + " scored: "+ str(score)
    print "All highest_scores =", high_score
    highest_scores = sorted(high_score, reverse = True)
    print "All highest_scores =",highest_scores[0:3]

y = 5
for i in range (y):
    play_game()

rawDescription: Python Games high scores

description: Python Games high scores


code:
import operator
import json
from collections import defaultdict

my_lol = [['a', 1.01], ['x',1.00],['k',1.02],['p',3.00], ['b', 3.09]]
my_lol_sorted = sorted(my_lol, key=operator.itemgetter(1))

thres = 0.1
tmp_val = 0
tmp_ids = "-"

dol = defaultdict(list)
for ids, val in my_lol_sorted:
    if tmp_ids == "-":
        tmp_ids = ids
    else:
        diff = abs(tmp_val - val)
        if diff > thres:
            tmp_ids = ids
    dol[tmp_ids].append(ids)
    tmp_val = val

print json.dumps(dol, indent=4)

rawDescription: Simple clustering from list of list in Python


code:
def do_ls():
    print "I'm about to ls"
    ls = subprocess.Popen('ls', stdout=subprocess.PIPE)
    output = ls.communicate()[0] #wait for the process to finish, capture stdout
    print 'ls output:'
    print output
    print 'done.'

rawDescription: print statements only appearing before or after a subprocess call

description: Print statements only appearing before or after a subprocess call


code:
#!/usr/bin/python
class Foo(object):
  def bar(self):
    print type(self)

class SubFoo(Foo):
  pass

SubFoo().bar()

rawDescription: Python get subclass name

description: Python get subclass name


code:
import os, sys
import yum

yb = yum.YumBase()
yb.conf.cache = os.geteuid() != 1
pl = yb.doPackageLists(patterns=sys.argv[1:])
if pl.installed:
    print "Installed Packages"
    for pkg in sorted(pl.installed):
        print pkg
if pl.available:
    print "Available Packages"
    for pkg in sorted(pl.available):
        print pkg, pkg.repo
if pl.reinstall_available:
    print "Re-install Available Packages"
    for pkg in sorted(pl.reinstall_available):
        print pkg, pkg.repo

rawDescription: Given an rpm package name, query the yum database for updates


code:
def _sort(_list):
    buckets=[0]*len(_list)
    for i in _list:
        i=int(i)
        assert(0<=i<len(_list))
        buckets[i]+=1
    result=[]
    for num,count in enumerate(buckets):
        result.extend([num]*count)
    return result

alp=map(ord,list("dabce"))
m=min(alp)
alp=[i-m for i in alp]
alp=_sort(alp)
alp=[i+m for i in alp]
alp=map(chr,alp)

print zip(_sort([1,3,2,0,4]),alp)
#[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

rawDescription: What is an O(n) algorithm to pair two equally lengthed lists in order in place?


code:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
print 'Content-Type: text/html'
print ''
print result.content

rawDescription: How to display a page in my browser with python code that is run locally on my computer with "GAE" SDK?

description: Display a page in my browser with python code that is run locally on my computer with "GAE" SDK


code:
while True:
    # main program
    while True:
        answer = raw_input('Run again? (y/n): ')
        if answer in ('y', 'n'):
            break
        print 'Invalid input.'
    if answer == 'y':
        continue
    else:
        print 'Goodbye'
        break

rawDescription: How do I restart a program based on user input?

description: Restart a program based on user input


code:
import serial

ser = serial.Serial(
    port='/dev/tty1',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    timeout=1)

while True:
    line = ser.readline()
    if not line.strip():  # evaluates to true when an "empty" line is received
        var = raw_input()
        if var:
            ser.write(var)
    else:
        print line,

rawDescription: read several lines from serial connection until condition is met, then allow serial write action

description: Read several lines from serial connection until condition is met, then allow serial write action


code:
for index in liste1.curselelction:
    item = liste1.get(index)
    print index, ":", item

rawDescription: Retrieve the selection of a listbox or selectmode = extended in tkinter python


code:
import os
import os.path

for fname in os.listdir('.'):
    if os.path.isfile(fname):
        f = open(fname)
        if 'mystring' in f.read():
            print fname
        f.close()

rawDescription: How to search and return across multiple files?

description: Search and return across multiple files


code: print event['creator']['displayName']

rawDescription: Object types and accessing nested values


code:
variable = 12
print 'blah, blah %4.3f' %variable
print 'blah, blah %1.1f' %variable

rawDescription: Python - decimal places (putting floats into a string)


code:
def f(*args):
    theSum = 0
    for arg in args:
        theSum += arg
    return theSum

print f(1,2,3,4)

rawDescription: optional arguments function

description: Optional arguments function


rawDescription: Parsing a string which represents a list of tuples


code:
import requests
r = requests.get('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' +'älterer')
print r.text

rawDescription: urlopen.request with an umlaut in the url

description: Urlopen.request with an umlaut in the url


code:
import json
import requests
import numpy as np

def flip_geojson_coordinates(geo):
    if isinstance(geo, dict):
        for k, v in geo.iteritems():
            if k == "coordinates":
                z = np.asarray(geo[k])
                f = z.flatten()
                geo[k] = np.dstack((f[1::2], f[::2])).reshape(z.shape).tolist()
            else:
                flip_geojson_coordinates(v)
    elif isinstance(geo, list):
        for k in geo:
            flip_geojson_coordinates(k)

url = "https://www.sciencebase.gov/catalogMaps/mapping/ows/5342c5fce4b0aa151574a8ed?\
service=wfs&version=1.1.0&request=GetFeature&typeNames=sb:Conservation_Zone_WGS84&outputFormat=application/json"
resp = requests.get(url)
gj = json.loads(resp.text)

print gj
flip_geojson_coordinates(gj)
print gj

rawDescription: Pythonic way to reverse lon,lat coordinates in a GeoJSON response


code:
HTML = """
html
html

html

code-start
code
code

code
code-end

"""

new_html = ""
is_code = False
for line in HTML.split('\n'):
    # disable empty line remover when code starts
    if line == 'code-start':
        is_code = True
    # check for empty line/is_code
    if is_code or line != '':
        new_html += line+'\n'
    # enable empty line remover when code ends
    if line == 'code-end':
        is_code = False

print new_html

rawDescription: remove empty lines from HTML, except in  blocks

description: Remove empty lines from HTML, except in  blocks


code:
import networkx as nx
import string
str = "a,b,c\nd,e,f\nd,k,j"
print str
lines = string.split(str,'\n')
DG=nx.DiGraph()
for line in lines:
    nodes = line.split(",")
    location = nodes[0]
    manager =  nodes[1]
    report =   nodes[2]
    if (location not in DG):
        DG.add_node(location)
    if (manager not in DG):
        DG.add_node(location)
    if (report not in DG):
        DG.add_node(location)
    DG.add_edge(location,manager)
    DG.add_edge(manager,report)

print DG.nodes()
print DG.edges()

rawDescription: is there a processor for creating a network graph in Data Science Studio?

description: Is there a processor for creating a network graph in Data Science Studio


code:
with open('mylogging.py', 'w') as f:
    f.write('''from logging import *
my_customization = "it works"''')
import mylogging
print mylogging.my_customization
help(mylogging.log)

rawDescription: How to proxy all methods from a Python module to another?

description: Proxy all methods from a Python module to another


code:
import subprocess as sp
cmd = 'echo "test" | cat'
process = sp.Popen(cmd,stdout=sp.PIPE,shell=True)
output = process.communicate()[0]
print output

rawDescription: Python Subprocess stdout and communicate()[0] not printing output that terminal would


code:
column23 = str(df_test[23])
column24 = str(df_test[24])
column25 = str(df_test[25])
column29 = str(df_test[29])
column31 = str(df_test[31])

count = 0

if "SYNONYMOUS_CODING" in column23:
    print "YES Syn in Column 23"
    count += 1

    print "Count value:"
    print count

if "SYNONYMOUS_CODING" in column24:
    print "YES Syn in Column 24"
    count += 1

    print "Count value:"
    print count

if "SYNONYMOUS_CODING" in column25:
    print "YES Syn in Column 25"
    count += 1

    print "Count value:"
    print count

if "SYNONYMOUS_CODING" in column29:
    print "YES Syn in Column 29"
    count += 1

    print "Count value:"
    print count

if "SYNONYMOUS_CODING" in column31:
    print "YES Syn in Column 31"
    count += 1

    print "Count value:"
    print count

if "NON_SYNONYMOUS_CODING" in column23:
    print "YES Non_Syn in Column 23"
    count += 1

    print "Count value:"
    print count

if "NON_SYNONYMOUS_CODING" in column24:
    print "YES Non_Syn in Column 24"
    count += 1

    print "Count value:"
    print count

if "NON_SYNONYMOUS_CODING" in column25:
    print "YES Non_Syn in Column 25"
    count += 1

    print "Count value:"
    print count

if "NON_SYNONYMOUS_CODING" in column29:
    print "YES Non_Syn in Column 29"
    count += 1

    print "Count value:"
    print count

if "NON_SYNONYMOUS_CODING" in column31:
    print "YES Non_Syn in Column 31"
    count += 1

    print "Count value:"
    print count

rawDescription: Finding and Counting String Values in Pandas DataFrame


code:
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebView, QWebPage
import sys

def linkHandler(url):
    print "[DEBUG] Clicked link is: %s" % url
    if url == "My Triggering URL":
        print "Found my link, launching python script"
    else:
        # Handle url gracefully
        pass

def main():
    app = QApplication(sys.argv)
    webview = QWebView()
    # Tell our webview to handle links, which it doesn't by default
    webview.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
    webview.linkClicked.connect(linkHandler)
    webview.load(QUrl('http://google.com'))
    webview.show()
    return app.exec_()

if __name__ == "__main__":
    main()

rawDescription: Invoke local python script from web browser instance


code:
def findpattern(commit_msg):
    pattern = re.compile("\w\w*-\d\d*")
    group = pattern.finditer(commit_msg)

    found = 0
    issues = 0
    for match in group:
        print " print matched issues:"
        auth = soap.login(jirauser,passwd)

        print match.group(0)
        getIssue(auth,match.group(0))
        issues = issues + 1
        found += 1
    if found == 0:
        sys.exit("No issue patterns found.")

    print "Retrieved issues: " + str(issues)

rawDescription: python -- for with an if statement

description: Python -- for with an if statement


code:
if any(s.lower() == "ds" for s in x):
    print "Yes"

rawDescription: Testing String Exists Regardless of Capitalization, Python


code:
def f(i): return i*i
def g(i): return 1.0/(1+i*i)
t1, t2 = zip(*[(f(i),g(i+1)) for i in range(5)])
l1, l2 = map(list, zip(*[(f(i),g(i+1)) for i in range(5)]))
print t1, t2
print l1, l2

rawDescription: (list comprehension) getting more than one list with a for loop


code:
import subprocess

p = subprocess.Popen(['/bin/ls', '-l'], stdout=subprocess.PIPE)
(out, _) = p.communicate()
print "Output:", out

rawDescription: redirecting standard output to the calling process

description: Redirecting standard output to the calling process


code:
import os
import sys
import pickle
#'users' dictionary stores registed users and their passwords.
status=""
users={}

#loads pickled data
def loadUsers():
    global users
    users=pickle.load(open("Dump.txt", "rb"))
#saves pickled data to Dump.txt
def saveUsers():
    global users
    pickle.dump(users, open("Dump.txt", "wb"))
#login() can register people and login.
def login():

      global users
      status=raw_input("Are you a new user y/n? Press q to quit. ")
      #creates new user by adding username and password to 'users' dictionary
      if status == "y":
            createNewUser=raw_input("Create username: ")
            if createNewUser in users:
                  print "User already exists!"
            else:
                  createPsswrd=raw_input("Create new password: ")
                  users[createNewUser] = createPsswrd
                  print "Register succesful!"
      #logs in registered users by checking for them in 'users' dictionary
      elif status == "n":
            login=raw_input("Username: ")
            passw=raw_input("Password: ")
            if login in users and users[login] == passw:
                  print "Login successful!"
                  #opens protected app/file
                  os.system('python Basketball\ Stats.py')
            else:
                  print "Username and password do not match!"
      #returns status to main body of script
      return status

loadUsers()
#quit and save
try:
    while status != "q":
                    status = login()
except Exception as e:
    raise
finally:
    saveUsers()

rawDescription: How to store dictionary data over multiple uses?

description: Store dictionary data over multiple uses


code:
from pyparsing import nestedExpr, ungroup, originalTextFor

# use nestedExpr to define a default expression with left-right nesting markers
nestedText = ungroup(nestedExpr('{{','}}'))

sample = """{{detect this {{and this as well}} text}} but text does not ends here so it should {{not detect this}}."""

# note how reporting the results as a list keeps the nesting of {{ }}'s
print nestedText.parseString(sample).asList()
# prints ['detect', 'this', ['and', 'this', 'as', 'well'], 'text']

# if you just want the string itself, wrap with 'originalTextFor'
print originalTextFor(nestedText).parseString(sample)[0]
# prints {{detect this {{and this as well}} text}}

rawDescription: regular expression to detect text in between double curly braces

description: Regular expression to detect text in between double curly braces


code:
COINS = (("Dollars", 1.),
         ("Quarters", .25),
         ("Dimes",    .10),
         ("Nickels",  .05),
         ("Pennies",  .01))

def changeCalc(cost, pmt):
    change = pmt - cost
    print("Total Change: %.2f" % change)
    if (pmt - cost) < 0:
        print("The customer needs to pay %.2f more." % abs(change))
    else:
        runningTotal = 0
        for (name, value) in COINS:
            number = int((change - runningTotal) / value)
            if number > 0:
                print("Number of %s: %d" % (name, number))
                runningTotal += number * value
        print runningTotal, change, (runningTotal - change)

rawDescription: Seeking Feedback, Infinite loop

description: Seeking Feedback, Infinite loop


code:
myvar = ""
while myvar != "quit":
    myvar = raw_input()
    print myvar

rawDescription: python syntax for terminating a program when the user enters quit

description: Python syntax for terminating a program when the user enters quit


code:
import re
input = 'The sound of cracking. Splintering. A shape appears, in ice.'
print re.findall("(\.\s+[a-zA-Z]+)", input)

rawDescription: Regex: match fullstop and one word in python


code:
def get_int_input(prompt):
    while True:
        s = raw_input(prompt)
        try:
            i = int(s)
        except ValueError:
            print "Please enter an integer."
        else:
            return i

def get_non_int_input(prompt):
    while True:
        s = raw_input(prompt)
        try:
            i = int(s)
        except ValueError:
            return s
        else:
            print "Please don't enter an integer."

rawDescription: Checking user input via raw_input method


code:
from bs4 import BeautifulSoup

page = """

            Other Text

            (2013)

"""
soup = BeautifulSoup(page)
tbl = soup.find('table')
rows = tbl.findAll('tr')
for row in rows:
    cols = row.find_all('td')
    for col in cols:
        if col.has_key('class') and col['class'][0] == 'image':
            hrefs = col.find_all('a')
            for href in hrefs:
                print href.get('title')

        elif col.has_key('class') and col['class'][0] == 'title':
            spans = col.find_all('span')
            for span in spans:
                if span.has_key('class') and span['class'][0] == 'wlb_wrapper':
                    print span.get('data-tconst')

rawDescription: extract class name from tag beautifulsoup python

description: Extract class name from tag beautifulsoup python


code:
for each in users.splitlines():
    print each

rawDescription: For loop outputting one character per line


code: print 't-statistic = %6.3f pvalue = %6.4f' %  stats.ttest_1samp(x, m)

rawDescription: How to calculate the statistics "t-test" with numpy

description: Calculate the statistics "t-test" with numpy


code:
enc = AES.new(password, mode)
encrypted = enc.encrypt(text)
print "ORIGINAL: " + text
print "ENCRYPTED: " + str(encrypted)
dec = AES.new(password, mode)
print "DECRYPTED: " + str(dec.decrypt(encrypted))

rawDescription: python aes encrypt/decrypt does not return the same results

description: Python aes encrypt/decrypt does not return the same results


code:
data = '»Æ¹ûÊ÷'
data.decode('utf8').encode('latin1').decode('gb2312')
print _

rawDescription: How to convert encoding in Python?

description: Convert encoding in Python


code:
str_converter = {'aa': 1, 'b':2, 'c':3, 'ao': 4, 'uw':5, 'd':6, 'ih':7}
pre_converter = {'aw': ['ao', 'uw'], 'ay': ['ao', 'ih']}

input = ['b', 'd', 'aa', 'aw', 'ay', 'c']

work_list = []

for in_string in input:
    converted_str = pre_converter.get(in_string)
    if converted_str is None:
        work_list.append(in_string)
    else:
        work_list.extend(converted_str)

for work_string in work_list:
    print str_converter.get(work_string)

rawDescription: assigning a string with a combination of two and separate them in a list

description: Assigning a string with a combination of two and separate them in a list


code: print numpy.finfo(numpy.longdouble)

rawDescription: Mixing NumPy longdouble and SymPy numerical evaluation – what about precision?


code:
import cv2
img = cv2.imread("new.bmp", 0) #since the image is grayscale, we need only one channel and the value '0' indicates just that
for i in range (img.shape[0]): #traverses through height of the image
    for j in range (img.shape[1]): #traverses through width of the image
        print img[i][j]

rawDescription: How to get grayscale image,pixel matrix values within the [0-255] range python

description: Get grayscale image,pixel matrix values within the [0-255] range python


code:
cert = rfc2459.Certificate()
print cert.prettyPrint()
cert['tbsCertificate'] = None
print cert.prettyPrint()
cert['tbsCertificate']['extensions'] = None
print cert.prettyPrint()
cert['tbsCertificate']['extensions'][0] = None
print cert.prettyPrint()
cert['tbsCertificate']['extensions'][0]['extnID'] = '1.3.5.4.3.2'
cert['tbsCertificate']['extensions'][0]['extnValue'] = '\x00\x00'
print cert.prettyPrint()

rawDescription: Simpler way to add tagged items in pyasn1


rawDescription: Maximum value of kernel statistics - python


code:
for line in infile:
            for key in json_obj:
                line = line.replace(key, json_obj[key])
                print line
            outfile.write(line)

rawDescription: replace some tokens(strings) from a tex file with values from a dictionary in python?

description: Replace some tokens(strings) from a tex file with values from a dictionary in python


code:
import time

from twisted.internet import reactor
from twisted.internet.defer import gatherResults
from twisted.internet.threads import deferToThread, blockingCallFromThread

def workReallyHard():
    "'Work' function, invoked in a thread."
    time.sleep(0.2)

def longOperation():
    for x in range(10):
        workReallyHard()
        blockingCallFromThread(reactor, startShortOperation, x)
    result = blockingCallFromThread(reactor, gatherResults, shortOperations)
    return 'hooray', result

def shortOperation(value):
    workReallyHard()
    return value * 100

shortOperations = []

def startShortOperation(value):
    def done(result):
        print 'Short operation complete!', result
        return result
    shortOperations.append(
        deferToThread(shortOperation, value).addCallback(done))

d = deferToThread(longOperation)
def allDone(result):
    print 'Long operation complete!', result
    reactor.stop()
d.addCallback(allDone)

reactor.run()

rawDescription: Waiting on event with Twisted and PB

description: Waiting on event with Twisted and PB


code:
cursor1.execute(
    "select distinct iv.[Date_], iv.Time_, iv.Close, cp.Last_price, cp.Volatility " +
    "from [Intraday_values] AS iv INNER JOIN [Closing_prices] AS cp" +
    "    ON cp.[Date_] = iv.[Date_] " +
    "order by iv.[Date_], iv.Time_")
row1 = cursor1.fetchall()
for row1 in row1:
    print row1[0], row1[1], row1[2], row1[3], row1[4]

rawDescription: Using pyodbc to pull data from 2 tables using unique date as reference


code:
import numpy as np
from scipy.linalg import eig
np.set_printoptions(precision=4)
T = np.mat("0.2 0.4 0.4;0.8 0.2 0.0;0.8 0.0 0.2")
print "T\n", T
w, vl, vr = eig(T, left=True)
vl
[ np.allclose(np.dot(vl[:,i].T, T), w[i]*vl[:,i].T) for i in range(3) ]

rawDescription: left hand side eigenvector in python?

description: Left hand side eigenvector in python


code:
from string import ascii_lowercase

def letter_pyramid():
    data = raw_input('Enter stop: ')
    data = ascii_lowercase.partition(data)[0] + data

    for i, j in enumerate(data):
        for k in range(0, 2 * i + 4):
            print j * k

letter_pyramid()

rawDescription: How to write a program that ask the user a lower-case letter and then print tower of letters beginning from letter "a" up to the letter entered?

description: Write a program that ask the user a lower-case letter and then print tower of letters beginning from letter "a" up to the letter entered


code:
#!/usr/bin/python

import random
a = lambda: random.randint(0, 100)
print a

grade = a()
print grade

if grade == 100:
    print "You have a perfect score"

if grade >= 90 and grade < 100:
    print "You have scored an A"

if grade >= 80 and grade <= 89:
    print "You have scored a B"

if grade >= 70 and grade <= 79:
    print "You have scored a C"

if grade >= 60 and grade <= 69:
    print "You have scored a D"

if grade < 59:
    print "You have scored an F"

rawDescription: Program not running at all

description: Program not running at all


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

c1 = 0  # Corner values
c2 = 1
c3 = 1
c4 = 4

a=np.linspace(c1, c2, 8)
b=np.linspace(c3, c4, 8)
c = np.array([np.linspace(i,j,12) for i,j in zip(a,b)])

print np.shape(c)

plt.figure()
plt.imshow(c)
plt.show()

rawDescription: Estimate a matrix of numbers based on known corner values?


code:
from functools import partial
import types

class DummyClient(object):
    def connect(self, *a, **kw): print 'connecting %r %r' % (a, kw)
    def play(self): print 'playing'
    def stop(self): print 'stopping'

class PersistentMPDClient(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.client = DummyClient()
        self.client.connect(self.host, self.port)

    def __getattr__(self, attr, *args):
        cmd = getattr(self.client, attr, *args)
        if isinstance(cmd, types.MethodType):
            # a method -- wrap
            return lambda *a, **kw: self.command(attr, *a, **kw)
        else:
            # anything else -- return unchanged
            return cmd

    def command(self, cmd, *args, **kwargs):
        command_callable = partial(self.client.__getattribute__(cmd), *args, **kwargs)
        try:
            return command_callable()
        except ConnectionError:
            # Mopidy drops our connection after a while, so reconnect to send the command
            self.client._soc = None
            self.client.connect(self.host, self.port)
            return command_callable()

c = PersistentMPDClient(hostname, port)
c.play()
c.stop()

rawDescription: Proxying a class in Python

description: Proxying a class in Python


code:
with open("txt_files/input_data_set.txt") as f:
    reading_file_info = f.read()#reading lines exact content
    reading_file_info=f.read
    tdm = textmining.TermDocumentMatrix()
    tdm.add_doc(reading_file_info)

    tdm.write_csv('txt_files/input_data_set_result.txt', cutoff=1)
    for row in tdm.rows(cutoff=1):
        print row

rawDescription: Creating a Term Document Matrix from Text File


code:
import wx

class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)
        self.answers = {}
        self.questions = ["What is your age?", "What is your weight?",
                          "Which of the following computer languages is the best ever: C++, PHP, Fortran, COBOL, Python?"]
        self.nextQuestion = 0

        self.question = wx.StaticText(panel, label="What is your name?")
        self.answer = wx.TextCtrl(panel, value="")
        submitBtn = wx.Button(panel, label="Submit")
        submitBtn.Bind(wx.EVT_BUTTON, self.onSubmit)

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.panelSizer = wx.BoxSizer(wx.VERTICAL)

        sizer.Add(self.question, 0, wx.ALL, 5)
        sizer.Add(self.answer, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(submitBtn, 0, wx.ALL|wx.CENTER, 5)
        panel.SetSizer(sizer)

        self.panelSizer.Add(panel, 1, wx.EXPAND)
        self.SetSizer(self.panelSizer)

    #----------------------------------------------------------------------
    def onSubmit(self, event):
        """"""
        self.answers[self.question.GetLabel()] = self.answer.GetValue()
        self.question.SetLabel(self.questions[self.nextQuestion])
        self.answer.SetValue("")
        self.nextQuestion += 1
        print self.answers
        self.panelSizer.Fit(self)

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: Wxpython - how to generate a series of text prompts without closing the app?


code:
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import Lock

print_lock = Lock()
def testfunc(string):
    print_lock.acquire()
    print string
    print_lock.release()

def main():

    strings = ['one', 'two', 'three', 'four', 'five']
    pool = ThreadPool(10)
    results = pool.map(testfunc, strings)
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()

rawDescription: Why do I see extra line breaks when working with python multiprocessing pool?


code:
a = [3,4,5,6]
for i, val in enumerate(a):
    print i, val

rawDescription: Iterate a list with indexes in Python

description: Iterate a list with indexes in Python


code:
import sys
from PIL import Image, ImageOps

PAT_SIZE = (8, 10)
NUMS = 3
FIRST_NUM_OFFSET = 5
NUM_OFFSET = (1, 3)

NUMBERS = []
for i in xrange(10):
    try:
        NUMBERS.append(Image.open('n%d.png' % i).load())
    except IOError:
        print "I do not know the pattern for the number %d." % i
        NUMBERS.append(None)

def magic(fname):
    captcha = ImageOps.grayscale(Image.open(fname))
    im = captcha.load()

    # Split numbers
    num = []
    for n in xrange(NUMS):
        x1, y1 = (FIRST_NUM_OFFSET + n * (NUM_OFFSET[0] + PAT_SIZE[0]),
                NUM_OFFSET[1])
        num.append(captcha.crop((x1, y1, x1 + PAT_SIZE[0], y1 + PAT_SIZE[1])))

    # If you want to save the split numbers:
    #for i, n in enumerate(num):
    #    n.save('%d.png' % i)

    def sqdiff(a, b):
        if None in (a, b): # XXX This is here just to handle missing pattern.
            return float('inf')

        d = 0
        for x in xrange(PAT_SIZE[0]):
            for y in xrange(PAT_SIZE[1]):
                d += (a[x, y] - b[x, y]) ** 2
        return d

    # Calculate a dummy sum of squared differences between the patterns
    # and each number. We assume the smallest diff is the number in the
    # "captcha".
    result = []
    for n in num:
        n_sqdiff = [(sqdiff(p, n.load()), i) for i, p in enumerate(NUMBERS)]
        result.append(min(n_sqdiff)[1])
    return result

print magic(sys.argv[1])

rawDescription: python captcha decoder library

description: Python captcha decoder library


code:
#   a  b      c
#0  1  S   Blue
#1  2  M  Black
#2  2  L   Blue
#3  1  L  Green

#get first rows of groups, sort them and reset index; delete redundant col index
df1 = df.groupby('a').head(1).sort('a').reset_index()
del df1['index']

#get last rows of groups, sort them and reset index; delete redundant col index
df2 = df.groupby('a').tail(1).sort('a').reset_index()
del df2['index']
print df1
#   a  b      c
#0  1  S   Blue
#1  2  M  Black
print df2
#   a  b      c
#0  1  L  Green
#1  2  L   Blue

#if value in col c in df1 is 'Blue' replace this row with row from df2 (indexes are same)
df1.loc[df1['c'].isin(['Blue'])] = df2
print df1
#   a  b      c
#0  1  L  Green
#1  2  M  Black

rawDescription: removing duplicate rows in pandas DataFrame based on a condition

description: Removing duplicate rows in pandas DataFrame based on a condition


code:
def readFunction(self, input):
    for i, char in enumerate(input):
        if input[i] == '(' and input[i+1] != ')':
            print input[i+1:-1]
            self.readFunction(input[i+1:-1])
            # No return - but like return this EXITS THE LOOP
            # when the termination condition is met.
            break
    # Breaks to here with an implicit "return None" at the end

rawDescription: python - Why is it mandatory to use return statements in recursion?

description: Python - Why is it mandatory to use return statements in recursion


code:
d = {'str1': 'before', 'str2': 'before'}
for i in d:
    print d[i]
    d[i] = "after"

rawDescription: python update outer passed value from within a for loop

description: Python update outer passed value from within a for loop


code:
import os
from urllib2 import urlopen, URLError, HTTPError

def dlfile(url):
    # Open the url
    try:
        f = urlopen(url)
        print "downloading " + url

        # Open our local file for writing
        with open(os.path.basename(url), "wb") as local_file:
            local_file.write(f.read())

    #handle errors
    except HTTPError, e:
        print "HTTP Error:", e.code, url
    except URLError, e:
        print "URL Error:", e.reason, url

def main():
    # Iterate over image ranges
    for index in range(150, 151):
        url = ("http://www.archive.org/download/"
               "Cory_Doctorow_Podcast_%d/"
               "Cory_Doctorow_Podcast_%d_64kb_mp3.zip" %
               (index, index))
        dlfile(url)

if __name__ == '__main__':
    main()

rawDescription: How do I download a zip file in python using urllib2?

description: Download a zip file in python using urllib2


code:
d = ws.cell(row = 4, column = 2)
print d.value

rawDescription: how to find the excel value from row, col names in python?

description: Find the excel value from row, col names in python


code:
import urllib
import base64
import httplib

CONSUMER_KEY = 'my_key'
CONSUMER_SECRET = 'my_secret'

encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)

concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET

host = 'api.twitter.com'
url = '/oauth2/token/'
params = urllib.urlencode({'grant_type' : 'client_credentials'})
req = httplib.HTTPSConnection(host)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "gzip")

req.endheaders()
req.send(params)

resp = req.getresponse()
print resp.status, resp.reason

rawDescription: Issuing application-only requests in Twitter 1.1 using Python


code:
def pick_one():
    print '''PROPERTIES OF SOLIDS OF REVOLUTION
    Pick a solid to analyse:
    1: Ball
    2: Bowling Pin
    3: Ellipse
    4: Table Leg'''

    silhouette = None
    choice = int(raw_input('Enter the number for your choice: '))
    while choice not in [1, 2, 3, 4]:
        choice = int(raw_input('Enter the number for your choice: '))

    if choice == 1:
        silhouette = ball
    elif choice == 2:
        silhouette = bowling_pin
    elif choice == 3:
        silhouette = ellipse
    elif choice == 4:
        silhouette = table_leg

    tempinput = raw_input('Enter the minimum and maximum number of points to use (e.g. 2 1000) ').split()
    min_num, max_num = [int(n) for n in tempinput]

    return silhouette, min_num, max_num

rawDescription: python menu, how to make this menu work

description: Python menu, how to make this menu work


code:
class Foo(object):
    def __del__(self):
        print "Bye bye!"

spam = Foo()
bar = spam
del spam
del bar

rawDescription: Python object deletion detection

description: Python object deletion detection


code:
from collections import defaultdict

lookup = defaultdict(dict)
lookup['name']['John'] = 1
lookup['name']['Jane'] = 2
lookup['name']['Joe'] = 3
lookup['gender']['Male'] = 1
lookup['gender']['Female'] = 2
lookup['country']['Japan'] = "jp"
lookup['country']['China'] = "ch"

print lookup['name']['Jane']
print lookup['gender']['Female']
print lookup['country']['China']

rawDescription: How to initialize a Multi-Dimensional Array in Python?

description: Initialize a Multi-Dimensional Array in Python


code:
import gtk

def print_size(widget, data=None):
    print window.get_size()

def delete_event(widget, data=None):
    print window.get_size()
    return False

def destroy(widget, data=None):
    gtk.main_quit()

window = gtk.Window()
window.connect('delete_event', delete_event)
window.connect('destroy', destroy)

button = gtk.Button(label='Print size')
button.connect('clicked', print_size)
window.add(button)

window.show_all()

gtk.main()

rawDescription: How do I get the size of a pygtk window?

description: Get the size of a pygtk window


code:
import pickle

class TestObj(object):
    def __init__(self, one=1, two=2, three=3):
        self.one = one
        self.two = two
        self.three = three

    def save(self):
        with open('D:\\test.pickle', 'wb') as f:
            pickle.dump((self.one,self.two,self.three),f,-1)

    @staticmethod
    def load():
        with open('D:\\test.pickle', 'rb') as f:
            one,two,three = pickle.load(f)
        test_obj = TestObj(one, two, three)
        return test_obj

test_obj = TestObj() #Init with defaults
test_obj.save()
print 'after save: one: %s, two: %s, three: %s' % (test_obj.one,test_obj.two,test_obj.three)
test_obj = test_obj.load()
print 'after load: one: %s, two: %s, three: %s' % (test_obj.one,test_obj.two,test_obj.three)

rawDescription: Why is my unpickled sequence different than when it was pickled?


code:
import wx

class landing_frame(wx.Frame):

    def __init__(self, parent, title):
        super(landing_frame, self).__init__(parent, title=title,
                                            size=(450, 350))
        self.font1 = wx.Font(18, wx.DECORATIVE, wx.ITALIC, wx.BOLD)
        self.InitUI()
        self.Centre()
        self.Show()

    def InitUI(self):

        self.panel = wx.Panel(self)
        self.sizer = wx.GridBagSizer(5, 5)

        self.text1 = wx.StaticText(self.panel, label="Welcome!")
        self.sizer.Add(
            self.text1, pos=(0, 0),
            flag=wx.TOP | wx.LEFT | wx.BOTTOM, border=15)

        line = wx.StaticLine(self.panel)
        self.sizer.Add(
            line, pos=(1, 0), span=(1, 5),
            flag=wx.EXPAND | wx.BOTTOM, border=10)

        self.text2 = wx.StaticText(self.panel, label="First Level Dropdown")
        self.sizer.Add(self.text2, pos=(2, 0), flag=wx.LEFT, border=10)

        self.sampleList = ['', 'Op1_1', 'Op1_2']
        self.combo1 = wx.ComboBox(self.panel, choices=self.sampleList)
        self.combo1.Bind(wx.EVT_COMBOBOX, self.on_combo1)
        self.sizer.Add(
            self.combo1, pos=(2, 1), span=(1, 2), flag=wx.TOP | wx.EXPAND,
            border=5)

        self.combo2 = wx.ComboBox(self.panel)
        self.combo2.Bind(wx.EVT_COMBOBOX, self.on_combo2)
        self.sizer.Add(
            self.combo2, pos=(3, 1), span=(1, 2), flag=wx.TOP | wx.EXPAND,
            border=5)

        self.panel.SetSizer(self.sizer)
        self.Layout()
        wx.CallAfter(self.combo2.Show, False)

    def on_combo1(self, event):
        self.user_choice = event.GetString()
        if self.user_choice == '':
            self.combo2.Show(False)
            self.combo2.Clear()
            return
        self.combo2.Show(True)

        if self.user_choice == "Op1_1":
            self.combo2.SetItems(('Op2_1_1', 'Op2_1_2', 'Op2_1_3'))

        elif self.user_choice == "Op1_2":
            self.combo2.SetItems(('Op2_2_1', 'Op2_2_2', 'Op2_2_3'))

    def on_combo2(self, event):
        print '2nd combo choice: {}'.format(event.GetString())

if __name__ == '__main__':
    app = wx.App(redirect=False)
    landing_frame(None, title="Test")
    app.MainLoop()

rawDescription: wxPython conditionally display and hide

description: WxPython conditionally display and hide


code:
import simplejson as sj
print sj.dumps('What\'s your name?') # => '"What\'s your name?"'

rawDescription: generating javascript string in python

description: Generating javascript string in python


code:
import urllib2

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req = urllib2.Request('http://www.google.com')
response = urllib2.urlopen(req)
page_source = response.read()

print page_source

rawDescription: Python synchronous urllib2 result

description: Python synchronous urllib2 result


rawDescription: Python regex bad character range.

description: Python regex bad character range.


code:
def walk_dir(directory, extensions=""):
    for path, dirs, files in os.walk(directory):
        for name in files:
            if name.endswith(extensions):
                yield os.path.join(path, name)

whitespace  = re.compile(r'\s+')
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
    result = regex.search(whitespace.sub('', line))
    if result:
        template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
        output = template.format(fileinput.filelineno(),
                                 fileinput.filename(),
                                 result.group())
        print output
        temp.write(output)

rawDescription: Search is printing results and "string not found" condition


code:
import subprocess

proc = subprocess.Popen('ls | awk "{print $1}"', shell=True, stdout=subprocess.PIPE)
stdout_value = proc.communicate()[0]
for item in stdout_value.split('\n'):
    print item

rawDescription: How to load a column generated by awk into a python list

description: Load a column generated by awk into a python list


code:
import random, timeit

def main():
    tries = 0
    NUMBER_OF_RANDOMS = 4
    stored_numbers = []
    start = timeit.default_timer()

    while len(stored_numbers) != NUMBER_OF_RANDOMS:
        current = random.randint(1,10)
        tries += 1
        if current not in stored_numbers:
            stored_numbers.append(current)

    stop = timeit.default_timer() - start
    print 'Number of tries:', tries
    print 'Time elapsed:', stop
    print stored_numbers

if __name__ == '__main__':
    main()

rawDescription: Random number generator, how to get random numbers that are not the same


code:
import random

def get_random_and_pop(lst):
    value = random.choice(lst)
    lst = list(set(lst) - set([value]))
    return value,lst

lst = ['english','math','science','computer science','history']
while (len(lst)):
    v,lst = get_random_and_pop(lst)
    print v,lst
    if (len(lst) == 0):
        lst = ['english','math','science','computer science','history']

rawDescription: Python-Returning to a specific point in the code


code:
import numpy as np

def Spread_Ratios(ratios,sizes):
    if np.dot(ratios,sizes)/np.sum(sizes)>3.:
        print 'There is no solution!\n'
        return None

    if np.any(ratios>3.):
        score = np.dot(sizes,ratios)
        ratios_reduced = np.where(ratios>3.,3.,ratios)
        score_reduced = np.dot(sizes,ratios_reduced)

        delta_ratios = (score - score_reduced) / np.sum(sizes[ratios<3.])
        new_ratios = ratios_reduced + np.where(ratios<3.,delta_ratios,0.)

        return Spread_Ratios(new_ratios,sizes)
    else:
        return ratios,sizes

rawDescription: Limiting a sequence of ratios to a range whilst maintaining overall increase/decrease of values they are multiplying


code:
from django import forms

def MonkeyPatchDjangoFormsBoundField():
    def prepare_widget_render(self, widget=None, attrs=None, only_initial=False):
        """
        Prepare the data needed for the widget rendering.
        """
        if not widget:
            widget = self.field.widget

        attrs = attrs or {}
        auto_id = self.auto_id
        if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
            if not only_initial:
                attrs['id'] = auto_id
            else:
                attrs['id'] = self.html_initial_id

        if not only_initial:
            name = self.html_name
        else:
            name = self.html_initial_name

        return widget, name, attrs

    def as_widget(self, widget=None, attrs=None, only_initial=False):
        """
        Renders the field by rendering the passed widget, adding any HTML
        attributes passed as attrs.  If no widget is specified, then the
        field's default widget will be used.
        """
        widget, name, attrs = self.prepare_widget_render(widget, attrs, only_initial)
        return widget.render(name, self.value(), attrs=attrs)

    def __iter__(self):
        """
        Check if current widget has a renderer and iterate renderer.
        """
        widget, name, attrs = self.prepare_widget_render()
        if not hasattr(widget, 'get_renderer'):
            raise Exception, "Can not iterate over widget '%s'" % widget.__class__.__name__
        renderer = widget.get_renderer(name, self.value(), attrs=attrs)
        for entry in renderer:
            yield entry

    def __getitem__(self,idx):
        """
        Tries to use current widget's renderer, and then check attribute.
        """
        widget, name, attrs = self.prepare_widget_render()
        try:
            renderer = widget.get_renderer(name, self.value(), attrs=attrs)
            return renderer[idx]
        except Exception:
            return getattr(self,idx)

    forms.forms.BoundField.prepare_widget_render = prepare_widget_render
    forms.forms.BoundField.as_widget = as_widget
    forms.forms.BoundField.__iter__ = __iter__
    forms.forms.BoundField.__getitem__ = __getitem__

rawDescription: django form radio input layout

description: Django form radio input layout


code:
s1 = 'BREAKFAST IN ["Rolled Oats","Cornflakes","French Toast"]'
s2 = 'COPIES_FOR_EXTERNAL > "0"'

print s1.split(None, 2) # ['BREAKFAST', 'IN', '["Rolled Oats","Cornflakes","French Toast"]']
print s2.split(None, 2) # ['COPIES_FOR_EXTERNAL', '>', '"0"']

rawDescription: Python Shlex splitting with brackets

description: Python Shlex splitting with brackets


rawDescription: How do I regex match with grouping with unknown number of groups

description: Regex match with grouping with unknown number of groups


code:
from datetime import datetime

class Sms_store:
    store = []
    message_count = 0

    def __init__(self):
        pass

    def add_new_arrival(self,number,time,text):
        Sms_store.store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        Sms_store.message_count += 1

newsms1 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms1.add_new_arrival("23456",time, "hello, how are you?")

newsms2 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms2.add_new_arrival("23456",time, "hello, how are you?")

print Sms_store.store

rawDescription: Python class instances stored in a list to store seperate instances


code:
import subprocess
proc = subprocess.Popen(['ipcs'],stdout=subprocess.PIPE)
for line in iter(proc.stdout.readline,''):
    line=line.strip().split()
    try:
        r = int(line[1])
    except:
        continue
    if line[0] == "m":
        op = subprocess.check_output(['ipcrm','-m',str(r)])
    elif line[0] == "s":
        op = subprocess.check_output(['ipcrm','-s',str(r)])
    print op
proc.wait()

rawDescription: How to process the output from a command invoked by python

description: Process the output from a command invoked by python


code:
import xlrd

book = xlrd.open_workbook('myfile.xls')

print book.nsheets
print book.sheet_names()

sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols

rawDescription: Recommend a Python library to read Excel XLS files


code:
mylist = [['dog', 'animal'],['daisy','flower'],['cat','animal']]
x = mylist[2][1]
print x

rawDescription: How to Retrieve a Specific value from a Specific List inside a Larger List?


code:
def worker(procnum, return_dict):
    '''worker function'''
    print str(procnum) + ' represent!'
    return_dict[procnum] = procnum

if __name__ == '__main__':
    manager = Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print return_dict.values()

rawDescription: How can I recover the return value of a function passed to multiprocessing.Process?

description: Recover the return value of a function passed to multiprocessing.Process


code:
from matplotlib import pyplot as plt
import numpy

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(numpy.random.rand(10))

def ondraw(event):
    # print 'ondraw', event
    # these ax.limits can be stored and reused as-is for set_xlim/set_ylim later
    print ax.get_xlim(), ax.get_ylim()

cid = fig.canvas.mpl_connect('draw_event', ondraw)

plt.show()

rawDescription: Figure Size & Position after Matplotlib Zoom


rawDescription: Global Variable Not Defined

description: Global Variable Not Defined


code:
qs = Data.objects.filter(hair='brown')
objects = dict()
for obj in qs:
   objects.setdefault(obj.haircolour, []).append(obj)

for (k, v) in objects.items():
    print "Objects for colour '%s':" % k
    for obj in v:
        print "- %s" % obj

rawDescription: Efficient way to use filter() twice in Django


code:
@sa.models_committed.connect_via(app)
def on_models_committed(sender, changes):
    for obj, change in changes:
        print 'SQLALCHEMY - %s %s' % (change, obj)

rawDescription: Using Flask-SQLAlchemy Event API to broadcast to Flask-SocketIO?


code:
import csv

counter=1
fieldnames=["var1", "var2","var3","var4","var5", "var6", "var7"]

with open('file.csv', 'wb') as f:
    my_writer = csv.DictWriter(f, fieldnames)
    my_writer.writeheader()

    for thepage in newpages:
        web_page = urllib2.urlopen(thepage)
        soup = BeautifulSoup(web_page.read())

        variables={ele:"MISSING" for ele in fieldnames}
        variables['var1']=str(counter)
        variables['var2']=soup.find_all('strong')[0].text
        variables['var3']=soup.find_all('p')[1].text[0]
        variables['var4']=soup.find_all('p')[1].text[1]
        variables['var4']=soup.find_all('p')[2].text
        variables['var6']=soup.find_all('p')[6].text
        variables['var7']=soup.find_all('p')[7].text
        print variables
        my_writer.writerow(variables)
        counter+=1

rawDescription: Appending rows to csv using dict_writer

description: Appending rows to csv using dict_writer


code:
import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text

rawDescription: How can I retrieve the page title of a webpage using Python?

description: Retrieve the page title of a webpage using Python


code:
valid = ["Yes", "yes", "y", "ok"]

if answer in valid:
    print "You said yes"
else:
    print "You did not say yes"

rawDescription: Efficient way of checking similar possible inputs?


code:
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
from skimage import color
from skimage import io

im = plt.imread('dice.jpg')
gray_img = color.rgb2gray(im)

print im.max()

# make some kind of kernel, there are many ways to do this...
t = 1 - np.abs(np.linspace(-1, 1, 16))
kernel = t.reshape(16, 1) * t.reshape(1, 16)
kernel /= kernel.sum()   # kernel should sum to 1!  :)

im_out =scipy.signal.convolve2d(gray_img,  kernel, mode = 'same')

im_out = im_out / im_out.max() * 255

print im_out.max()

plt.subplot(2,1,1)
plt.imshow(im)
plt.subplot(2,1,2)
plt.imshow(im_out)
plt.show()

rawDescription: How to normalize scipy's convolve2d when working with images?

description: Normalize scipy's convolve2d when working with images


code:
#!/usr/bin/env python

from Tkinter import *
import tkMessageBox
import ttk

#---------------------------------------------------------------------
class MyTab(Frame):

    def __init__(self, root, name):
        Frame.__init__(self, root)

        self.root = root
        self.name = name

        self.entry = Entry(self)
        self.entry.pack(side=TOP)

        self.entry.bind('<FocusOut>', self.alert)
        self.entry.bind('<Key>', self.printing)

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

    def alert(self, event):
        print 'FocusOut event is working for ' + self.name + '  value: ' + self.entry.get()
        #tkMessageBox.showinfo('alert', 'FocusOut event is working for ' + self.name + '  value: ' + self.entry.get())

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

    def printing(self, event):
        print event.keysym + ' for ' + self.name

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

class Application():

    def __init__(self):

        self.tabs = {'ky':1}

        self.root = Tk()
        self.root.minsize(300, 300)
        self.root.geometry("1000x700")

        self.notebook = ttk.Notebook(self.root, width=1000, height=650)

#       self.all_tabs = []

        self.addTab('tab1')

        self.button = Button(self.root, text='generate', command=self.start_generating).pack(side=BOTTOM)

        self.notebook.pack(side=TOP)

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

    def addTab(self, name):
        tab = MyTab(self.notebook, name)
        self.notebook.add(tab, text=name)
#       self.all_tabs.append(tab)

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

    def start_generating(self):
        if self.tabs['ky'] < 4:
            self.tabs['ky'] += 1
            self.addTab('tab'+ str(self.tabs['ky']))

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

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

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

Application().run()

rawDescription: how to make instances of event for every single tab on multi tab GUI tkinter( notebook widget)

description: Make instances of event for every single tab on multi tab GUI tkinter( notebook widget)


rawDescription: regular exp in python to get values

description: Regular exp in python to get values


code:
import re
response = '''id="this_id">
blah

(.*)
\s*<div\ id="another_id"'

for found in re.findall(descriptionRegex, response, re.DOTALL ) :
   print found

rawDescription: Maximum capacity on re module? Python

description: Maximum capacity on re module? Python


code:
import json
print json.dumps({'AAA': 1, 'BBB': 2, 'CCC': 3})

rawDescription: pprint(): how to use double quotes to display strings?

description: Pprint(): how to use double quotes to display strings


code:
from itertools import permutations

for arrangement in permutations('abcdefghi', 9):
    print ''.join(arrangement)

rawDescription: Python Reduce conditional expression

description: Python Reduce conditional expression


code:
import sys
import time

while 1:
    print 'someoutput'
    sys.stdout.flush()
    time.sleep(1)

rawDescription: Popen stdout reading pipe, deadlock using sleep


code:
quickList = ["string1", "string2"]
anotherList = {"string1": ["another1a", "another1b"],
               "string2": ["another2a", "another2b"]}

for i in range(1):
    quick = random.choice(quickList)
    print quick
    print random.choice(anotherList[quick])

rawDescription: Using random.choice in conjuction with if statements


code:
d = {}
for item in items:
    d[item.id] = item
print d.keys()

rawDescription: Get unique list of ids from object list

description: Get unique list of ids from object list


code:
#!/usr/bin/python

# open a microphone in pyAudio and listen for taps

import pyaudio
import struct
import math

INITIAL_TAP_THRESHOLD = 0.010
FORMAT = pyaudio.paInt16
SHORT_NORMALIZE = (1.0/32768.0)
CHANNELS = 2
RATE = 44100
INPUT_BLOCK_TIME = 0.05
INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)
# if we get this many noisy blocks in a row, increase the threshold
OVERSENSITIVE = 15.0/INPUT_BLOCK_TIME
# if we get this many quiet blocks in a row, decrease the threshold
UNDERSENSITIVE = 120.0/INPUT_BLOCK_TIME
# if the noise was longer than this many blocks, it's not a 'tap'
MAX_TAP_BLOCKS = 0.15/INPUT_BLOCK_TIME

def get_rms( block ):
    # RMS amplitude is defined as the square root of the
    # mean over time of the square of the amplitude.
    # so we need to convert this string of bytes into
    # a string of 16-bit samples...

    # we will get one short out for each
    # two chars in the string.
    count = len(block)/2
    format = "%dh"%(count)
    shorts = struct.unpack( format, block )

    # iterate over the block.
    sum_squares = 0.0
    for sample in shorts:
        # sample is a signed short in +/- 32768.
        # normalize it to 1.0
        n = sample * SHORT_NORMALIZE
        sum_squares += n*n

    return math.sqrt( sum_squares / count )

class TapTester(object):
    def __init__(self):
        self.pa = pyaudio.PyAudio()
        self.stream = self.open_mic_stream()
        self.tap_threshold = INITIAL_TAP_THRESHOLD
        self.noisycount = MAX_TAP_BLOCKS+1
        self.quietcount = 0
        self.errorcount = 0

    def stop(self):
        self.stream.close()

    def find_input_device(self):
        device_index = None
        for i in range( self.pa.get_device_count() ):
            devinfo = self.pa.get_device_info_by_index(i)
            print( "Device %d: %s"%(i,devinfo["name"]) )

            for keyword in ["mic","input"]:
                if keyword in devinfo["name"].lower():
                    print( "Found an input: device %d - %s"%(i,devinfo["name"]) )
                    device_index = i
                    return device_index

        if device_index == None:
            print( "No preferred input found; using default input device." )

        return device_index

    def open_mic_stream( self ):
        device_index = self.find_input_device()

        stream = self.pa.open(   format = FORMAT,
                                 channels = CHANNELS,
                                 rate = RATE,
                                 input = True,
                                 input_device_index = device_index,
                                 frames_per_buffer = INPUT_FRAMES_PER_BLOCK)

        return stream

    def tapDetected(self):
        print "Tap!"

    def listen(self):
        try:
            block = self.stream.read(INPUT_FRAMES_PER_BLOCK)
        except IOError, e:
            # dammit.
            self.errorcount += 1
            print( "(%d) Error recording: %s"%(self.errorcount,e) )
            self.noisycount = 1
            return

        amplitude = get_rms( block )
        if amplitude > self.tap_threshold:
            # noisy block
            self.quietcount = 0
            self.noisycount += 1
            if self.noisycount > OVERSENSITIVE:
                # turn down the sensitivity
                self.tap_threshold *= 1.1
        else:
            # quiet block.

            if 1 <= self.noisycount <= MAX_TAP_BLOCKS:
                self.tapDetected()
            self.noisycount = 0
            self.quietcount += 1
            if self.quietcount > UNDERSENSITIVE:
                # turn up the sensitivity
                self.tap_threshold *= 0.9

if __name__ == "__main__":
    tt = TapTester()

    for i in range(1000):
        tt.listen()

rawDescription: Detect tap with pyaudio from live mic

description: Detect tap with pyaudio from live mic


code:
import bitio  # see http://stackoverflow.com/a/10691412/355230

# hash function configuration
BW = 8, 8, 4  # bit widths of each integer
HW = sum(BW)  # total bit width of hash

def myhash(a, b, c):
    return (((((a & (2**BW[0]-1)) << BW[1]) |
                b & (2**BW[1]-1)) << BW[2]) |
                c & (2**BW[2]-1))

hashed = myhash(60, 113, 5)
print '{:0{}b}'.format(hashed, HW)  # --> 00111100011100010101

with open('test.bits', 'wb') as outf:
    bw = bitio.BitWriter(outf)
    bw.writebits(hashed, HW)
    bw.flush()

with open('test.bits', 'rb') as inf:
    br = bitio.BitReader(inf)
    val = br.readbits(HW)

print '{:0{}b}'.format(val, HW)  # --> 00111100011100010101

rawDescription: How to store and write/load to/from file an arbitrary number of bits in Python?

description: Store and write/load to/from file an arbitrary number of bits in Python


code:
print network[0] # 0, 2, 4, 1, 6, 0, 0

print network[0][0] # 0
print network[0][1] # 2
print network[0][2] # 4

for x in network[0]:
   print x
# 0
# 2
# 4
# 1
# 6
# 0
# 0

print sum(network[0]) # 13

rawDescription: How to get individual numbers inside list which is inside another list in Python?

description: Get individual numbers inside list which is inside another list in Python


code: print event.parsed[0]['msg']

rawDescription: Not being able to convert list or string into dict


code:
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver

__author__="smota"
__date__ ="$30/10/2009 17:17:50$"

class SquitterClient(LineReceiver):
    def connectionMade(self):
        self.messageCount = 0
        # The factory provides a reference to itself, we'll use it to enumerate the clients
        self.factory.n += 1
        self.name = "Client %d" %self.factory.n

        # Send initial message, and more messages a bit later
        self.sendLine("Client %s starting!" % self.name);
        reactor.callLater(0.5, self.sendMessage, "Message %d" %self.messageCount)

    def connectionLost(self, reason):
        print "connection lost"

    def sendMessage(self, msg):
        for m in [ "a", "b", "c", "d", "e"]:
            self.sendLine("Copy %s of message %s from client %s!" % (m, msg, self.name))
        if self.factory.stop:
            self.sendLine("Client %s disconnecting!" % self.name)
            self.transport.loseConnection()
        else:
            self.messageCount += 1
            reactor.callLater(0.5, self.sendMessage, "Message %d" %self.messageCount)

class SquitterClientFactory(protocol.ClientFactory):
    protocol = SquitterClient

    def __init__(self):
        self.n = 0
        self.stop = False

    def stopTest():
        self.stop = True

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"

# this connects the protocol to a server running on port 8000
def main():
    # Create 10 clients

    f = SquitterClientFactory()
    for i in range(10):
        reactor.connectTCP("localhost", 8000, f)

    # Schedule end of test in 10 seconds
    reactor.callLater(10, f.stopTest)

    # And let loose the dogs of war
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

rawDescription: Testing twisted application - Load client


code:
def create_file_numbers_old(filename, size):
    start = time.clock()
    value = 0
    written = 0 # number of bytes written so far
    with open(filename, "w") as f:
        while written < size:
            s = str(value) + '\n'
            written += len(s) # add how many bytes are in this write()
            f.write(s)
            value += 1

    end = time.clock()
    print "time taken to write a file of size", size, " is ", (end -start), "seconds \n"

rawDescription: Python optimizing the cose using cProfile


code:
def firstThing():  # this could be your 'cd' task
    print 'ran first task'

def secondThing(): # another task you would want to run
    print 'ran second task'

def showCommands(): # a task to show available commands
    print functionDict.keys()

# a dictionary mapping commands to functions (you could do the same with classes)
functionDict = {'f1': firstThing, 'f2': secondThing, 'help': showCommands}

# the actual function that gets the input
def main():
    cont = True
    while(cont):
        selection = raw_input('enter your selection ')
        if selection == 'q': # quick and dirty way to give the user a way out
            cont = False
        elif selection in functionDict.keys():
            functionDict[selection]()
        else:
            print 'my friend, you do not know me. enter help to see VALID commands'

if __name__ == '__main__':
    main()

rawDescription: Create a raw input with commands inside a Python script


code:
import hashlib, base64
print base64.b85encode(hashlib.sha256(b"hello world").digest())
# output: b'xlJdzlTAJdr7lv}+I_3~#DwqTdQ*VzkcjuJ;_uDr'

rawDescription: Generate password from input string

description: Generate password from input string


code:
#!/usr/bin/python

class Employee:
    def __init__(self, salary, age, name, sex):
            self.salary =   salary
            self.age=       age
            self.name=      name
            self.sex=       sex
            #Employee.empCount += 1 #don't do this. you should count instances OUTSIDE

    def __str__(self):
            return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)

def getAge():
    while True:
        try:
            s=raw_input("How old are you? ")
            age = int(s)
            if age > 100:
                print "Please enter a sensible age"
            elif age<=10:
                print "Please enter an age greater than 10"
            else:
                return age
        except ValueError:
            print "You entered " + s + " Please enter a number"

def getName():
    return raw_input("What is your name? ")

def getSex():
    while True:
        sex = str(raw_input("Are you a man or a woman? "))
        if not sex in ("man", "woman"):
            print "Please enter man or woman "
        else:
            return sex

age= getAge()
name= getName()
sex= getSex()
salary=100000

employee = Employee(salary, age, name, sex)
print employee

rawDescription: Python Modules, passing values to args

description: Python Modules, passing values to args


code:
with open(file_path, 'r') as fp:
    result = []
    while True:
        # 1.
        s = fp.read(2)
        if not s:
            break

        # 2.
        number = int(s, 16) # No need for '0x' prefix!

        # 3.
        number = number ^ 0x91  # '91' needs '0x' prefix!

        # 4.
        result.append(format(number, '02x'))

print ''.join(result)

rawDescription: how to read two digit from a file, XOR it with (0x91) and print to screen?

description: Read two digit from a file, XOR it with (0x91) and print to screen


code:
import tensorflow as tf

f = ["f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8"]
l = ["l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8"]

fv = tf.constant(f)
lv = tf.constant(l)

rsq = tf.RandomShuffleQueue(10, 0, [tf.string, tf.string], shapes=[[],[]])
do_enqueues = rsq.enqueue_many([fv, lv])

gotf, gotl = rsq.dequeue()

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    tf.train.start_queue_runners(sess=sess)
    sess.run(do_enqueues)
    for i in xrange(2):
        one_f, one_l = sess.run([gotf, gotl])
        print "F: ", one_f, "L: ", one_l

rawDescription: Accessing filename from file queue in Tensor Flow


code:
def printList(l, dict1):
    for l1 in l:
        if dict1.has_key(l1):
            print "withinrange"
        else:
            print "outsiderange"

file = open("test1.txt")
textfile = file.readlines()
dict={'sca4': [['BM1', 17], ['BM2', 33]], 'sca6': [['GM2', 46], ['GM2', 67], ['BM',17]]}
dict1 = {}
l =[]
key = ''
for line in textfile:
    if not line.strip():
        continue
    col1, col2, col3 = line.strip().split(" ")
    if not (key == col1):
        printList(l, dict1)
        l =[]
        key = col1
        dict1 = {}
    for value_list in dict.get(col1, []):
        #print value_list[1]
        if not (value_list[1] in l):
            l.append(value_list[1])
        if ((int(col2) <= value_list[1]) and (value_list[1] <= int(col3))):
            dict1[value_list[1]] = 'correct'
printList(l, dict1)

rawDescription: Check if complex values of dict matches certain criteria


code:
class MyTest(unittest.TestCase):
    def setUp(self):
        self.stream = StringIO()
        self.handler = logging.StreamHandler(self.stream)
        self.log = logging.getLogger('mylogger')
        self.log.setLevel(logging.INFO)
        for handler in self.log.handlers:
            self.log.removeHandler(handler)
        self.log.addHandler(self.handler)
    def testLog(self):
        self.log.info("test")
        self.handler.flush()
        print '[', self.stream.getvalue(), ']'
        self.assertTrue(self.stream.getvalue(), 'test')

    def tearDown(self):
        self.log.removeHandler(self.handler)
        self.handler.close()

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

rawDescription: Python logging to StringIO handler

description: Python logging to StringIO handler


code:
#!/usr/bin/env python
import json
import urllib2

try:
    r = urllib2.urlopen("https://push.geckoboard.com/v1/send/" + widget_key,
                        json.dumps(nested_dict))
except IOError as e:
    if hasattr(e, 'reason'):
       print "connection error:", e.reason
    elif hasattr(e, 'code'):
       print "http error:", e.code
       print e.read()
    else:
       print "error:", e
else: # success
    assert json.load(r)["success"]

rawDescription: How to output JSON in python so it can be used for Geckoboard's Highcharts plugin

description: Output JSON in python so it can be used for Geckoboard's Highcharts plugin


code:
import re
s = "api('randomkey123xyz987', 'key', 'text')"
match = re.search(r"api\('([^']*)'", s).group(1)
print match

rawDescription: Python Regex Get String Between Two Substrings


code:
#!/usr/bin/python

def histogram( anarray ):
        "A Histogram Function"
        for x in range(0,len(anarray)):
                print 'X' * anarray[x];
        return;

histogram([4,2,5]);

rawDescription: How can I make a function that prints a histogram based on the indexes of a list (more detalis inside)?

description: Make a function that prints a histogram based on the indexes of a list (more detalis inside)


rawDescription: Merging rows from .csv files with different lengths (python 3.x)


code:
import optparse

parser = optparse.OptionParser()

parser.add_option("-d", "--directory", metavar="DIR",
    help="Directory to scan for big files")
parser.add_option("-e", "--email", metavar='EMAIL',
    help='email to send the list to')

opts, args = parser.parse_args()

print 'scanning', opts.directory

if opts.email is None:
    print 'not sending the email'

rawDescription: Order of command line arguments in a Python script


code:
import inspect
inspect.getmembers(a)
inspect.getargspec(a.methodA)
inspect.getargspec(getattr(a, 'methodA'))
print inspect.getargspec.__doc__
print inspect.getmembers.__doc__

rawDescription: Finding out which functions are available from a class instance in python?


code:
from imdb import IMDb
ia = IMDb('sql', uri='mysql://username:password@localhost/imdb')
inglorious = ia.search_movie('Inglorious Basterds')[0]
ia.update(inglorious)
print inglorious['soundtrack']

rawDescription: does imdbpy2sql.py export soundtracks to mysql?

description: Does imdbpy2sql.py export soundtracks to mysql


code:
for tag in tags:
  print tag.name

rawDescription: Imgur TagVote issue python

description: Imgur TagVote issue python


code:
shape = input("Please enter your choice of shape? ")

nthTime = ["second","third","fourth","fifth","sixth"]
undesired_shapes = ["octagon","heptagon","hexagon"]

indx = 0

while shape.lower() not in undesired_shapes:
    print("Please select a shape from the list!")
    shape = input("Pick a shape, for the " + nthTime[indx] + " time! ")
    indx += 1
    if indx >= len(nthTime):
        print 'Giving up !!'
        break

rawDescription: Python: How can you iterate over a list that is nested inside a while-loop?


code:
class ref:
    def __init__(self, obj): self.obj = obj
    def get(self):    return self.obj
    def set(self, obj):      self.obj = obj

a = ref([1, 2])
b = a
print a.get()  # => [1, 2]
print b.get()  # => [1, 2]

b.set(2)
print a.get()  # => 2
print b.get()  # => 2

rawDescription: Simulating Pointers in Python

description: Simulating Pointers in Python


code:
import random

# List of donuts
Donuts = ['Apple Cinnamon',
          'Strawberry',
          'Custard',
          'Sugar Ring',
          'Chocolate Caramel',
          'Lemon Circle',
          'Blueberry Blaster',
          'Strawberry Surprise',
          'Simple Sugar']

# Function - Random Selection of Donuts
def Generate_Random(list, num):
    return random.sample(list, num)

# Print out randomly selected donuts using the above function
for element in Generate_Random(Donuts, 6):
    print element

rawDescription: unique values from a list

description: Unique values from a list


code:
from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)

rawDescription: python ISO 8601 date format

description: Python ISO 8601 date format


code:
for c in reversed(string):
     print c

rawDescription: Best way to loop over a python string backwards

description: Loop over a python string backwards


code:
L = ['a','b','c']

if len(L)>2:
    print ', '.join(L[:-1]) + ", and " + str(L[-1])
elif len(L)==2:
    print ' and '.join(L)
elif len(L)==1:
    print L[0]

rawDescription: Python string.join ( list ) last entry with "and"