code:
class GameStart:
    def __init__(self):
        self.life = 405
        self.bg = pygame.image.load(picPath + 'bg.jpg')
        self.lf = pygame.image.load(picPath + 'life.jpg')
        self.player1 = pygame.sprite.Group()
        self.player2 = pygame.sprite.Group()
        self.cB = Ball()
        self.cS = Stone()
        self.player1.add(self.cB)
        self.player2.add(self.cS)
    def update(self):
        if pygame.sprite.groupcollide(self.player1, self.player2, 1, 0):
            print 'Yoshi!'
        screen.blit(self.bg, (0, 0))
        self.cB.update((x, y))
        self.cS.update()
        screen.blit(self.lf, (150, self.life))

rawDescription: The method for the use of about pygame.sprite.groupcollide


code:
def readTowns(text):
    input = open(text, 'r')
    file = input.readlines()
    dict2town = {}
    town2dict = {}
    for line in file:
        tmp = line.split()
        dict2town[tmp[0]] = tmp[1]
        town2dict[tmp[1]]  = town2dict.get(tmp[1]) or []
        town2dict.get(tmp[1]).append(tmp[0])
    return dict2town, town2dict

dict2town, town2dict = readTowns('file.txt')
print town2dict['Anzegem']

rawDescription: Python: dictionary to collection

description: Python: dictionary to collection


code:
class testDec(object):

    @property
    def x(self):
        print 'called getter'
        return self._x

    @x.setter
    def x(self, value):
        print 'called setter'
        self._x = value

rawDescription: Why does @foo.setter in Python not work for me?


code:
x.voidField = 123
print repr(x.voidField)

rawDescription: Python Ctypes converts void pointer to nonetype and long. What are the implications? What does this mean?


code:
import imp, os.path
filename=os.path.split(pathname)[-1]
modulename = os.path.splitext(filename)[0]
try:
    module = imp.load_source(modulename, pathname)
    plugin = module.create()
except ImportError, e:
    print "Error importing plugin '%s': %s" % (filename, str(e))

rawDescription: does anybody know a simple base for a plug in python application?

description: Does anybody know a simple base for a plug in python application


code:
import Database
Database.connect()
print Database.data

rawDescription: Confusion over how to share and modify class level data between instances.


code:
def readRows():
    rows = [ sh1.row_values(idx, 4, 6) for idx in range(sh1.nrows) ]
    # using list comprehension
    return dict([ [row[4], (row[5], row[6])] for row in rows ])

D1 = readRows()
print D['Bob']
('sdfadfadf',23)

import pprint

pprint.pprint(D1)
{'Bob': ('sdafdfadf',23),
 'Cat': ('asdfa',24),
 'Dog': ('fadfasdf',24)}

rawDescription: Help with Excel, Python and XLRD

description: Help with Excel, Python and XLRD


code:
import multiprocessing, time, sys
import pandas as pd

NR_ROWS = 10000
i = 0
def getDf():
    global i, NR_ROWS
    myheader = ["name", "test2", "test3"]
    myrow1 =   [ i,  i+400, i+250]
    df = pd.DataFrame([myrow1]*NR_ROWS, columns = myheader)
    i = i+1
    return df

def f_put(q):
    print "f_put start"
    j = 0
    while(j < 5):
        data = getDf()
        q.put(data)
        print "P:", data["name"].iloc[0]
        sys.stdout.flush()
        j += 1

def f_get(q):
    print "f_get start"
    while(1):
        data = pd.DataFrame()
        loop = 0
        while not q.empty():
            data = q.get()
            print "get (loop: %s)" %loop
            time.sleep(0)
            loop += 1
        time.sleep(1.)

if __name__ == "__main__":

    q = multiprocessing.Queue()
    p = multiprocessing.Process(target=f_put, args=(q,))
    p.start()
    while(1):
        f_get(q)
    p.join()

rawDescription: Multiprocessing and Queue with Dataframe


code:
import urllib2
url = "http://www.gravatar.com/avatar/92fb4563ddc5ceeaa8b19b60a7a172f4"
req = urllib2.Request(url)
r = urllib2.urlopen(req)
# you can check the returned header and find where the filename is loacated
print r.headers.dict
s = r.headers.getheader('content-disposition')
# just parse the filename
filename = s[s.index('"')+1:s.rindex('"')]
f = open(filename, 'wb')
f.write(r.read())
f.close()

rawDescription: How to grab the output from python subprocess

description: Grab the output from python subprocess


code:
valobj = lldb.frame.FindVariable("mystr")
address = valobj.GetChildMemberWithName('AllocatorInstance').GetChildMemberWithName('Data').GetValueAsUnsigned()
size = valobj.GetChildMemberWithName('AllocatorInstance').GetChildMemberWithName('len').GetValueAsUnsigned()
print address
print size
err = lldb.SBError()
print err
membuf = lldb.process.ReadMemory (address, size, err)
print err
membuf

rawDescription: Pointer arithmetic in LLDB Python scripts


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup

soup = BeautifulSoup(urlopen('http://www.processorstore.nl/product/476816/category-212194/intel-core-i7-4790k.html'))

for spec in soup.select('div.product-specs dl.product-specs--list > dt.product-specs--item-title'):
    name = spec.span
    if not name:
        continue

    value = spec.find_next_sibling('dd', class_='product-specs--item-spec')
    print name.get_text(strip=True), value.get_text(strip=True)

rawDescription: Python Crawler Beatifulsoup decompose() function


code:
for event, elem in iterparse('xml/test.xml'):
        if elem.tag == "properties":
            print elem.text

rawDescription: How to scrape xml urls with scrapy

description: Scrape xml urls with scrapy


code:
import itertools as it, operator as op

# some dummy data so the example runs
observednumber_1 = 1
observednumber_2 = 2
observednumber_3 = 3
calculatedvalue = None

trees=[
  ['species_1', observednumber_1, calculatedvalue, calculatedvalue],
  ['species_2', observednumber_2, calculatedvalue, calculatedvalue],
  ['species_1', observednumber_3, calculatedvalue, calculatedvalue], ]

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

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

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


code:
Combining
import re
with open("filename") as origin_file:
    for line in origin_file:
        line = re.findall(r'something', line)
        if line:
           line = line[0].split('"')[1]
        print line

rawDescription: cat, grep and cut - translated to python

description: Cat, grep and cut - translated to python


code:
from guppy import hpy
h = hpy()
print h.heap()

rawDescription: Track variables in Python subprocesses

description: Track variables in Python subprocesses


code:
import optparse, sys

# Assume your CSV data is read into a list of dictionaries
sheet = [
    {'StudentId': 1, 'StudentFirstName': 'John', 'StudentLastName': 'Doe', 'StudentZipCode': '12345', 'StudentCommuteMethod': 'Bus'},
    {'StudentId': 2, 'StudentFirstName': 'Bob', 'StudentLastName': 'Chen', 'StudentZipCode': '12345', 'StudentCommuteMethod': 'Bus'},
    {'StudentId': 3, 'StudentFirstName': 'Jane', 'StudentLastName': 'Smith', 'StudentZipCode': '12345', 'StudentCommuteMethod': 'Train'},
    {'StudentId': 4, 'StudentFirstName': 'Dave', 'StudentLastName': 'Burns', 'StudentZipCode': '45467', 'StudentCommuteMethod': 'Bus'},
]

# Options parsing
parser = optparse.OptionParser()
parser.add_option('--filter', type='string', dest='filter')
options, args = parser.parse_args()

# Filter option is required
if options.filter is None:
    print >> sys.stderr, 'error: no filter expression given'
    sys.exit(1)

# Process rows and build result set
result = []
for row in sheet:
    # Bind each column to a local variable (StudentId, StudentFirstName, etc.);
    # this allows evaluating Python expressions on a row, for example:
    # 'StudentCommuteMethod = "Bus" and StudentZipCode = "12345"'
    for col, val in row.iteritems():
        exec '%s = %s' % (col, repr(val))

    # Apply filter to the row
    if eval(options.filter):
        result.append(row)

# Print out result set
for row in result:
    print row

rawDescription: Specifying a boolean filter expression to a python script


code:
import fileinput
for line in fileinput.input(inplace=1):
    print line + "foobar"

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

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


code:
import socket
print socket.gethostbyname('www.google.com')

rawDescription: Ping a website address to return an IP

description: Ping a website address to return an IP


code:
import json
mydict = json.loads(content)
print mydict

rawDescription: Httplib2 : Processing Response String

description: Httplib2 : Processing Response String


code:
import pandas as pd

csvfile = "C:/Users/Simon/Desktop/test.csv"

data = pd.read_csv(csvfile, header=None, names=['time','cpu','energy'])

times = list(pd.unique(data.time.ravel()))

print times

cpuList = data.groupby(['cpu'])

cpuEnergy = {}

for i in range(len(cpuList)):
    curCPU = 'CPU' + str(i+1)
    cpuEnergy[curCPU] = list(cpuList.get_group('CPU' + str(i+1))['energy'])

for k, v in cpuEnergy.items():
    print k, v

rawDescription: Getting data arrays from CSV with loops

description: Getting data arrays from CSV with loops


code:
lst = []
for line in fread:
    line = line.rstrip()
    lst.extend(line.split())

print lst

rawDescription: python variable contains three lists not one

description: Python variable contains three lists not one


code:
import operator

def apply(f,a,b):
  return f(a,b)

print apply(operator.add,1,1)

rawDescription: How to use infix operators as higher order functions?

description: Use infix operators as higher order functions


code:
import pyqrcode
qr = pyqrcode.create("HORN O.K. PLEASE.")
qr.png("horn.png", scale=6)
import qrtools
qr = qrtools.QR()
qr.decode("horn.png")
print qr.data

rawDescription: How to decode a QR-code image in (preferably pure) Python?

description: Decode a QR-code image in (preferably pure) Python


code:
from lxml import etree

data = """
<detection-run>
    <wireless-network>
        <SSID>
            <encryption>WEP</encryption>
        </SSID>
    </wireless-network>
    <wireless-network>
        <SSID>
            <encryption>WPA-PSK</encryption>
        </SSID>
    </wireless-network>
    <wireless-network>
        <SSID>
            <encryption>WPA2-PSK</encryption>
        </SSID>
    </wireless-network>
</detection-run>
"""

root = etree.fromstring(data)
print root.xpath('//encryption[text()!="WPA-PSK"]/text()')

rawDescription: Selecting text nodes with text not equal to a value


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

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


code:
def main(infodoc):
    with open(infodoc,'r') as infile:
        incsv = DictReader(infile)
        for row in incsv:
            print row['Publisher']
            DocIn = row['DocIn']
            DocOut = row['DocOut']
            WebAddy = row['WebAddy']
            moo(DocIn, DocOut, WebAddy)

rawDescription: Python, need to input csv file into a loop


code:
from bs4 import BeautifulSoup

html_object = """
<o:p></o:p>
hello world
"""
soup = BeautifulSoup(html_object, "lxml")

for x in soup.find_all():
    if len(x.text) == 0:
        x.extract()

print soup

rawDescription: How to remove tags that have no content

description: Remove tags that have no content


code:
from itertools import chain

def trav(node):
    if 'children' in node:
        return [node['name']] + list(chain.from_iterable([trav(child) for child in node['children']]))
    else:
        return [node['name']]

print trav(x)

rawDescription: Extract the object names from different nesting levels in JSON


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

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


code:
# define the appropriate labels:
TableValues = ['Class', 'Letter']

# and create the dictionary based on these tags:
# this uses a dictionary comprehension in a dictionary
# comprehension. Comprehensive stuff.
new_root = {
    'body': {
        label: {
            key: value
            for key, value in mydict.iteritems()
            if label.lower() in key.lower()
        }
        for label in TableValues
     }
}

print xmltodict.unparse(new_root, pretty=True)

rawDescription: Parsing text to XML format

description: Parsing text to XML format


code:
import os,time

def get_information(directory):
    file_list = []
    for i in os.listdir(directory):
        a = os.stat(os.path.join(directory,i))
        file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
    return file_list

print get_information("/")

rawDescription: Python: Get a list of all files and folders in a directory, the time of creation, the time of last modification. System independent solution?


code:
for rel in graph_db.match("KNOWS"):
    print rel.start_node["name"] + " knows " + rel.end_node["name"]

rawDescription: py2neo: performance and return values of various commands

description: Py2neo: performance and return values of various commands


code:
from bs4 import BeautifulSoup
import urllib

page3 = urllib.urlopen("https://angel.co/uber").read()
soup3 = BeautifulSoup(page3)

desc = soup3.findAll(attrs={"name":"description"})
print desc[0]['content'].encode('utf-8')

rawDescription: Extracting contents from specific meta tags that are not closed using BeautifulSoup


code:
import pandas as pd
from cStringIO import StringIO

# Create fake DataFrame... you can read this in however you like
df = pd.read_table(StringIO('''
name     surname       middle
Frank    Doe           NaN
John     NaN           Wood
Jack     Putt          NaN
Frank    NaN           Joyce'''), sep='\s+')

print 'Original DataFrame:'
print df
print

# Assign the middle name to any surname with a NaN
df.loc[pd.isnull(df['surname']), 'surname'] = df[pd.isnull(df['surname'])]['middle']

print 'Manipulated DataFrame:'
print df
print

rawDescription: Fill empty values from a row with the value of next column on the same row on csv file with pandas


code:
price = float(input("Enter the product price: "))

# declare begin and end variables as empty strings to start
begin = ""
end = ""

# the while loops are to make sure the user inputs a tax rate that
# is more than 0 and less than 10
while begin <= 0 or begin > 10:
    begin = int(input("Enter tax rate: "))

while end <= 0 or end > 10:
    end = int(input("Enter end tax rate: "))

# does the math for every integer between beginning and end, prints a 'table'
for x in range(begin,end+1):
    total = price + price * x/100
    print "Price: "+str(price)+"\tTax: "+str(x)+"\tTotal: "+str(total)
    x += 1

raw_input ("Enter to exit")

rawDescription: Homework: Sales Tax python program

description: Homework: Sales Tax python program


code:
import json
with open('events.json') as f:
    events = json.load(f)
    event = max(events['away_team_events'], key=lambda ev: ev['id'])
    print event

rawDescription: How to find which item in a JSON list has the greatest value for a given attribute in Python?

description: Find which item in a JSON list has the greatest value for a given attribute in Python


code:
def mazeDetector(row, col, solution):
    solution.append((row, col))
    if m[row][col] == "F": return True, solution
    m[row][col] = "V"
    neighbors = [(row, col - 1), (row + 1, col), (row - 1, col), (row, col + 1)]
    neighbors = filter(lambda (r, c): r >= 0 and c >= 0 and r < len(m) and c < len(m) and m[r][c] not in ("V", "W"), neighbors)
    for r, c in neighbors:
        t, sol = mazeDetector(r, c, list(solution))
        if t: return True, sol
    return False, []

print mazeDetector(1, 5, [])[1]

rawDescription: how to make my maze function print out the solution

description: Make my maze function print out the solution


code:
if hasattr(TheFrame, snowDIR):
   print 'snowDIR', TheFrame.snowDIR
else:
   print 'User did not set snowDIR'

rawDescription: call a variable created in an event function in wx python

description: Call a variable created in an event function in wx python


code:
b = ndimage.binary_closing(a) - a
b = ndimage.binary_dilation(b.astype(bool))

c = ndimage.distance_transform_cdt(a == 0) == 1

e = c.astype(numpy.int) * b + c

print e

rawDescription: Adjacent cells of multiple cell patches in a numpy array


code:
class MyBase(object):
    def p(self):
        print vars(self)

rawDescription: How to access a class field values in its base class?

description: Access a class field values in its base class


code:
from bs4 import BeautifulSoup

html = """

<title>title</title>

division

    passage in division
    bold in passage

"""

soup = BeautifulSoup(html)
for element in soup.find_all(text=True):
    text = element.string.strip()
    if text:
        element.replace_with("cool " + text)

print soup.prettify()

rawDescription: Edit all strings in a html doc with beautifulsoup 4 in python


rawDescription: printing and formatted list in python

description: Printing and formatted list in python


code:
import struct

lsof_list = """\
COMMAND     PID       USER   FD      TYPE DEVICE  SIZE/OFF   NODE NAME
init          1       root  cwd   unknown                         /proc/1/cwd (readlink: Permission denied)
init          1       root  rtd   unknown                         /proc/1/root (readlink: Permission denied)
python    30077      user1  txt       REG    8,1   2617520 461619 /usr/bin/python2.6
""".splitlines()

# note: variable-length NAME field at the end intentionally omitted
base_format = '8s 1x 6s 1x 10s 1x 4s 1x 9s 1x 6s 1x 9s 1x 6s 1x'
base_format_size = struct.calcsize(base_format)

for line in lsof_list:
    remainder = len(line) - base_format_size
    format = base_format + str(remainder) + 's'  # append NAME field format
    fields = struct.unpack(format, line)
    print fields

rawDescription: Splitlines in Python a table with empty spaces


code:
import os
from win32com.client import GetObject

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

for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'):
    print "Killing PID:", p.Properties_('ProcessId').Value
    os.system("taskkill /pid "+str(p.Properties_('ProcessId').Value))

rawDescription: How to close a cmd window using python 2.7

description: Close a cmd window using python 2.7


rawDescription: preferred way to filter data models.objects.all().exclude() or models.objects.filter()

description: Preferred way to filter data models.objects.all().exclude() or models.objects.filter()


code: print k+"\t", v

rawDescription: Python: Print dictionary using column formatting?


code:
phonenum=soup.select(".phone-content")
# set comprehension will remove the duplicate phone numbers
unique_phonenum = {p.text.strip().encode("utf-8") for p in phonenum}

for a in unique_phonenum:
    print a

rawDescription: Webscrapping using beautiful soup giving multiple results


code:
import time
import sys

print "Doing subprocess testing stuff"
time.sleep(2)
print "Doing more subprocess testing stuff"

# simulate error
time.sleep(2)
print "Error, jump out of the process"
sys.exit(1)

# finish
time.sleep(2)
print "done"

# this can be left out since it is called implicitely
# on successful step out of a process
# sys.exit(0)

rawDescription: teminate subprocess.call( 'python script") and continure with next test script query

description: Teminate subprocess.call( 'python script") and continure with next test script query


code:
import sys
import visit

def main():
    visit.Launch()

    # Loop through the locals that were just imported
    # and assign the names to the visit module
    loc = locals()
    for key in loc:
        setattr(visit, key, loc[key])

    return 0

if __name__=="__main__":
    ret = main()
    print dir(visit)
    sys.exit(ret)

rawDescription: Importing a shared library and the global namespace


code: print '\n'.join([''.join(inner) for inner in mlist])

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

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


code:
print delta.total_seconds()  # 2.7
print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7

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


code:
for title in titles:
    if any(word in title for word in word_list):
        print title

rawDescription: Check RSS feed titles for words. Print only titles that contain word


rawDescription: Solving Puzzle in Python

description: Solving Puzzle in Python


code:
#!/usr/bin/env python

data = [ #top-left
         [0,0,1,1,0,0],
         [0,0,1,1,0,0],
         [1,1,0,0,1,1],
         [1,1,0,0,1,1],
         [0,0,1,1,0,0],
         [0,0,1,1,0,0],
         [1,1,0,0,1,1],
         [1,1,0,0,1,1],
       ]             # bottom-right

d = {} # point --> clid
dcl = {} # clid --> [point1,point2,...]

def process_point(t):
    global clid # cluster id
    val = data[t[0]][t[1]]
    above = (t[0]-1, t[1])
    abovevalid = 0 <= above[0] < maxX and 0 <= above[1] < maxY
    #below = (t[0]+1, t[1]) # We do not need that because we scan from top-left to bottom-right
    left = (t[0], t[1]-1)
    leftvalid = 0 <= left[0] < maxX and 0 <= left[1] < maxY
    #right = (t[0], t[1]+1) # We do not need that because we scan from top-left to bottom-right

    if not val: # for zero return
        return
    if left in d and above in d and d[above] != d[left]:
        # left and above on different clusters, merge them
        prevclid = d[left]
        dcl[d[above]].extend(dcl[prevclid]) # update dcl
        for l in dcl[d[left]]:
            d[l] = d[above] # update d
        del dcl[prevclid]
        dcl[d[above]].append(t)
        d[t] = d[above]
    elif above in d and abovevalid:
        dcl[d[above]].append(t)
        d[t] = d[above]
    elif left in d and leftvalid:
        dcl[d[left]].append(t)
        d[t] = d[left]
    else: # First saw this one
        dcl[clid] = [t]
        d[t] = clid
        clid += 1

def print_output():
    for k in dcl: # Print output
        print k, dcl[k]

def main():
    global clid
    global maxX
    global maxY
    maxX = len(data)
    maxY = len(data[0])
    clid = 0
    for i in xrange(maxX):
        for j in xrange(maxY):
            process_point((i,j))
    print_output()

if __name__ == "__main__":
    main()

rawDescription: Python 2D-cluster finder

description: Python 2D-cluster finder


code:
def f(x, n):
    words = x.split()
    d = {}
    for word in words:
        if word in d:
            d[word] += 1
        else:
            d[word] = 1
    print [i for i,j in d.items() if d[i] >= n]

f("the apple the banana the apple", 2)

rawDescription: Returning the words from a string that occur a number of times or more in python 3?


code:
def nested_pattern(s):
    if s:
        return '(?:' + s[0] + nested_pattern(s[1:]) + ')?'
    else:
        return ''

import re
regex = re.compile(r'.U.E' + nested_pattern(r'.E..') + '$')

for word in ('TUB', 'TUBE', 'TEBU', 'TUBES', 'PURETE', 'TUBELEX', 'TUBELESS', 'SURELY'):
    print word, bool(regex.match(word))

rawDescription: Regular expression where part of the pattern is optional.


code:
class ndim:
    def __init__(self):
        self.dimensions=[8,9,10]
        self.numdimensions=3
        self.gridsize=8*9*10

    def getcellindex(self, location):
        cindex = 0
        cdrop = self.gridsize
        for index in xrange(self.numdimensions):
            cdrop /= self.dimensions[index]
            cindex += cdrop * location[index]
        return cindex

    def getlocation(self, cellindex):
        res = []
        for size in reversed(self.dimensions):
            res.append(cellindex % size)
            cellindex /= size
        return res[::-1]

n=ndim()
print n.getcellindex((0,0,0))
print n.getcellindex((0,0,1))
print n.getcellindex((0,1,0))
print n.getcellindex((1,0,0))

print n.getlocation(90)
print n.getlocation(10)
print n.getlocation(1)
print n.getlocation(0)

rawDescription: Python Multidimensional Array as a single List


code:
for i in range(7):
    print -(8-i), -(6-i)
    print test[-(8-i):-(6-i)]
    print i

rawDescription: Python string slicing, special case if end of string included?


code:
from tkinter import *

def overlaps((x1, y1, x2, y2)):
    '''returns overlapping object ids in ovals dict'''
    oval_list = [] # make a list to hold overlap objects
    c_object = table.find_overlapping(x1, y1, x2, y2)
    for k,v in ovals.items():  # iterate over ovals dict
        if v in c_object:      # if the value of a key is in the overlap tuple
            oval_list.append(k)# add the key to the list
    return oval_list

a = Tk()

# make a dictionary to hold object ids
ovals = {}

table = Canvas(a, width=500, height=300, bg='white')
table.pack()

# create oval_a and assign a name for it as a key and
# a reference to it as a value in the ovals dict.
# the key can be whatever you want to call it
# create the other ovals as well, adding each to the dict
# after it's made
oval_a = table.create_oval(40, 40, 80, 80)
ovals['oval_a'] = oval_a

oval_b = table.create_oval(60, 60, 120, 120)
ovals['oval_b'] = oval_b

oval_c = table.create_oval(120, 120, 140, 140)
ovals['oval_c'] = oval_c

# draw a rectangle
rectangle = table.create_rectangle(30, 30, 70, 70)

# print the return value of the overlaps function
# using the coords of the rectangle as a bounding box
print(overlaps(table.coords(rectangle)))

a.mainloop()

rawDescription: Python tkinter find_overlapping tuple?

description: Python tkinter find_overlapping tuple


code:
def main():
    print "In sub_main"

rawDescription: How can I import a python file through a command prompt?

description: Import a python file through a command prompt


code:
def make_printer(msg):
    def printer():
        print msg
    return printer

printer('a message')()

rawDescription: lambda in python

description: Lambda in python


code:
def find_range(a,b):
    print range(*sorted((a,b)))

rawDescription: Range between two unsorted numbers

description: Range between two unsorted numbers


code:
import numpy as np

rows = 20
cols = 10
n = 3

def running_view(arr, window, axis=-1):
    """
    return a running view of length 'window' over 'axis'
    the returned array has an extra last dimension, which spans the window
    """
    shape = list(arr.shape)
    shape[axis] -= (window-1)
    assert(shape[axis]>0)
    return np.lib.index_tricks.as_strided(
        arr,
        shape + [window],
        arr.strides + (arr.strides[axis],))

#fixed number of ones per row in random contiguous place
data = np.zeros((rows, cols), np.uint8)

I = np.arange(rows)
J = np.random.randint(0,cols-n+1, rows)

running_view(data, n)[I,J,:] = 1
print data

rawDescription: Numpy array creation with patterns

description: Numpy array creation with patterns


code:
print links
#  [u'http://en.wikipedia.com/wiki/Thomas_Jefferson&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFggUMAA&usg=AFQjCNG6INz_xj_-p7mpoirb4UqyfGxdWA',
#   u'http://www.wikipedia.com/wiki/Jefferson%25E2%2580%2593Hemings_controversy&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFggeMAE&usg=AFQjCNEjCPY-HCdfHoIa60s2DwBU1ffSPg',
#   u'http://en.wikipedia.com/wiki/Sally_Hemings&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFggjMAI&usg=AFQjCNGxy4i7AFsup0yPzw9xQq-wD9mtCw',
#   u'http://en.wikipedia.com/wiki/Monticello&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFggoMAM&usg=AFQjCNE4YlDpcIUqJRGghuSC43TkG-917g',
#   u'http://en.wikipedia.com/wiki/Thomas_Jefferson_University&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFggtMAQ&usg=AFQjCNEDuLjZwImk1G1OnNEnRhtJMvr44g',
#   u'http://www.wikipedia.com/wiki/Jane_Randolph_Jefferson&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFggyMAU&usg=AFQjCNHmXJMI0k4Bf6j3b7QdJffKk97tAw',
#   u'http://en.wikipedia.com/wiki/United_States_presidential_election,_1800&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFgg3MAY&usg=AFQjCNEqsc9jDsDetf0reFep9L9CnlorBA',
#   u'http://en.wikipedia.com/wiki/Isaac_Jefferson&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFgg8MAc&usg=AFQjCNHKAAgylhRjxbxEva5IvDA_UnVrTQ',
#   u'http://en.wikipedia.com/wiki/United_States_presidential_election,_1796&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFghBMAg&usg=AFQjCNHviErFQEKbDlcnDZrqmxGuiBG9XA',
#   u'http://en.wikipedia.com/wiki/United_States_presidential_election,_1804&sa=U&ved=0ahUKEwj4p5-4zI_LAhXCJCYKHUEMCjQQFghGMAk&usg=AFQjCNEJZSxCuXE_Dzm_kw3U7hYkH7OtlQ']

rawDescription: Pull Data/Links from Google Searches using Beautiful Soup


code:
import csv

def save(self, filepath):
    with open(filepath, 'w') as fout:
        outfile = csv.writer(fout, delimiter=":")
        for k,v in self.bok.iteritems():
            outfile.writerow([v,k])

def load(self, filepath):
    if not os.path.isfile(filepath):
        print "No file was found"
        return
    with open(filepath) as infile:
        for v,k in csv.reader(infile, delimiter=":"):
            self.bok[k] = v

rawDescription: Python 2.7.8 - Dictionary to file and back with style


code:
class MyDNSServerFactory(server.DNSServerFactory):

    def handleQuery(self, message, protocol, address):
        if protocol.transport.socket.type == socket.SOCK_STREAM:
            self.peer_address = protocol.transport.getPeer()
        elif protocol.transport.socket.type == socket.SOCK_DGRAM:
            self.peer_address = IPv4Address('UDP', *address)
        else:
            print "Unexpected socket type %r" % protocol.transport.socket.type

        print "Got message from : %r" % self.peer_address

        # Make peer_address available to resolvers that support that attribute
        for resolver in self.resolver.resolvers:
            if hasattr(resolver, 'peer_address'):
                resolver.peer_address = self.peer_address

        return server.DNSServerFactory.handleQuery(self, message, protocol, address)

rawDescription: Python Twisted Custom DNS

description: Python Twisted Custom DNS


code:
import ijson
f = open('json.txt')
objects = ijson.items(f, 'articles.item')
for obj in objects:
    print obj["abstractText"]

rawDescription: How can I use ijson

description: Use ijson


code:
u"česnakas"
print u"česnakas"

rawDescription: How to scrap data with special characters?

description: Scrap data with special characters


code:
from ast import literal_eval

with open('test.txt', 'rb') as f:
    data = [literal_eval(line) for line in f]

print data

rawDescription: Load lists from a text file

description: Load lists from a text file


code:
for i in range(0,len(root)):
    #retrieve data from post
    if root[i].tag == "post":
        #recursively retrieve quote
        quotes = root[i].findall('.//quote')
        for quote in quotes:
            print quote.get("orig_author")
            print get_text(quote)

rawDescription: Recursive traversal of xml tags is not printing the value of the (sub tags) Ref.tail


rawDescription: Extracting data from a list of tuples

description: Extracting data from a list of tuples


code:
from sqlalchemy import create_engine
engine = create_engine('mysql://test:test@localhost/test1', echo=True)

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)

session = Session()

from sqlalchemy import Column, Integer, Unicode

class Foo(Base):
    __tablename__ = 'tblfoo'
    __table_args__ = {'mysql_engine':'InnoDB'}

    ModelID = Column(Integer, primary_key=True, autoincrement=True)
    ModelName = Column(Unicode(255), nullable=True, index=True)
    ModelMemo = Column(Unicode(255), nullable=True)

Base.metadata.create_all(engine)

f = Foo(ModelName='Bar', ModelMemo='Foo')
session.add(f)
session.flush()

print "ID :", f.ModelID

rawDescription: Get last inserted value from MySQL using SQLAlchemy


code:
def index(self, username):
    print username

rawDescription: How are POST and GET variables handled in Python?


code:
new_list = ['partiye', 'oy', 'vermeyecegimi', 'bilerek', 'sandiga', 'gidecegim']
print [i[:6] for i in new_list]

rawDescription: Script Slicing in Python

description: Script Slicing in Python


code:
import pygame
pink = (255, 64, 64)
w = 640
h = 480
ud = 0
ld = 0
screen = pygame.display.set_mode((w, h))
running = 1
def key_event(event):
    global ud
    if event.key == pygame.K_UP:
        ud -= 10
        print 'ud',ud

def setup_background():
    screen.fill((pink))

while running:

    setup_background()
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             running = False
        elif event.type == pygame.KEYDOWN:
             key_event(event)

rawDescription: How do I add key commands to sprite?

description: Add key commands to sprite


code:
import wx
app = wx.App(redirect=False)
top = wx.Frame(None)
top.SetSize((320, 280))
sizer = wx.GridBagSizer()

def on_char(event):
    event.Skip()
    getValue = searchExpectedResults.GetValue() # get the entered string in TextCtrl with GetValue method
    print getValue
    search_items = sorted(['test', 'entry']) # Create a list of all searchable items in a list
    textareaExpectedResults.Clear()
    for item in search_items:
        if getValue in item:
            print item
            textareaExpectedResults.Append(item) # Clear the ListBox and append the matching strings in search_items to the ListBox

searchExpectedResults = wx.TextCtrl(top, -1, "", size=(175, -1))
sizer.Add(searchExpectedResults, (2, 8), (2, 14), wx.EXPAND)
searchExpectedResults.Bind(wx.EVT_KEY_UP, on_char) # Bind an EVT_CHAR event to your TextCtrl
search_items = sorted(['test', 'entry'])
textareaExpectedResults = wx.ListBox(top, choices=search_items, size=(270, 250))
sizer.Add(textareaExpectedResults, (6, 8), (2, 14), wx.EXPAND)
top.Sizer = sizer
top.Sizer.Fit(top)
top.Show()
app.MainLoop()

rawDescription: How can I update a wxPython ListBox based on some search string?

description: Update a wxPython ListBox based on some search string


code:
#!/usr/bin/env python

grid = [range(i, i+3) for i in range(0, 9, 3)]

for row in grid:
    print row
print

def xy_to_i(x, y): return 3 * (y % 3) + (x % 3)

def samerow(i):
    y, x = divmod(i, 3)
    return [xy_to_i(x + j, y) for j in (0, 1, 2)]

def samecol(i):
    y, x = divmod(i, 3)
    return [xy_to_i(x, y + j) for j in (0, 1, 2)]

for i in range(9):
    print i, samerow(i), samecol(i)

rawDescription: To find same row in tic tac toe using a formula


code:
from selenium import webdriver
import time
from selenium.webdriver.support.select import Select

url = "http://shop.uclastore.com/courselistbuilder.aspx"

driver = webdriver.Firefox()
driver.get(url)
time.sleep(1)

departments = Select(driver.find_element_by_id('clDeptSelectBox'))
for department in departments.options:
    # select department
    departments.select_by_value(department.get_attribute('value'))
    time.sleep(1)

    cources = Select(driver.find_element_by_id('clCourseSelectBox'))
    for cource in cources.options:
        # select course
        cources.select_by_value(cource.get_attribute('value'))
        time.sleep(1)

        sections = Select(driver.find_element_by_id('clSectionSelectBox'))
        for section in sections.options:
            print {'department': department.text,
                   'course': cource.text,
                   'section': section.text}

driver.close()

rawDescription: Can Selenium WebDriver click on all combinations from drop down menu


code:
import json
from pyparsing import *

data = """var txns = [
   { apples: '100', oranges: '20', type: 'SELL'},
   { apples: '200', oranges: '10', type: 'BUY'}]"""

def js_grammar():
    key = Word(alphas).setResultsName("key")
    value = QuotedString("'").setResultsName("value")
    pair = Group(key + Literal(":").suppress() + value)
    object_ = nestedExpr("{", "}", delimitedList(pair, ","))
    array = nestedExpr("[", "]", delimitedList(object_, ","))
    return array + StringEnd()

JS_GRAMMAR = js_grammar()

def parse(js):
    return JS_GRAMMAR.parseString(js[len("var txns = "):])[0]

def to_dict(object_):
    return dict((p.key, p.value) for p in object_)

result = [
    {"transaction": to_dict(object_)}
    for object_ in parse(data)]
print json.dumps(result)

rawDescription: Hacking JavaScript Array Into JSON With Python


code:
import heapq
y = {'a':55, 'b':33, 'c':67, 'd':12}
print heapq.nlargest(n=3, iterable=y, key=y.get)[-1]
# b

rawDescription: Obtain x'th largest item in a dictionary


code:
import requests

target_url = "http://xmlgw.companieshouse.gov.uk/v1-0/xmlgw/Gateway"
headers={'Content-type': 'text/xml'}
print requests.post(target_url, data=xml, headers=headers).text

rawDescription: Python: Making a request with suds

description: Python: Making a request with suds


code:
def get_entries( infile ):
    with open( infile, 'rt') as file:
        for line in file:
            name, nums = line.split(':', 1)
            yield name, tuple(int(x) for x in nums.split(','))

# dict takes a sequence of  `(key, value)` pairs and turns in into a dict
print dict(get_entries( infile ))

rawDescription: Python: Build a dictionary from a file's contents


code:
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.scatter import Scatter
from kivy.graphics import Color, Rectangle, Canvas

class Avatar(Scatter):
    def __init__(self, **kwargs):
        super(Avatar, self).__init__(size_hint=(None,None), **kwargs)

        with self.canvas:
            Color(0, 0, 0)
            Rectangle(pos=(self.x, self.y), size=(self.width, self.height))

        #self.lbl = Label(text='Test', size_hint_x=1, size_hint_y=1)
        self.lbl = Label(text='Test', width=self.width, height=self.height)
        self.add_widget(self.lbl)

        # Scatter size is 30% of the GameBackground
        # ISSUE: After resize my Scatter, the objects inside is not resized as well.
        # self.size_hint_x, self.size_hint_y = 0.3, 0.3
        self.scale = 0.3

class GameBackground(FloatLayout):
    def __init__(self, **kwargs):
        super(GameBackground, self).__init__(**kwargs)

        with self.canvas:
            Color(0, 0, 1)
            Rectangle(pos = (0, 0), size = (Window.width,Window.height))

        self.elf = Avatar()
        self.add_widget(self.elf)
        self.elf.x = 200
        self.elf.y = 300

        # Get the X, Y position of the Scatter and the label inside the Scatter relative to the parent.
        print self.elf.pos      #<-- This works.
        print self.elf.lbl.pos  #<-- ISSUE: This not working.
        print self.elf.to_parent(*self.elf.lbl.pos)

class GameApp(App):
    def build(self):
        return GameBackground()

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

rawDescription: Issues with Scatter size and position

description: Issues with Scatter size and position


code:
con = sqlite3.connect(dbpath, factory=sqlite3.Row)
cur = con.execute('SELECT * FROM Config')
config_params = cur.fetchone()
print config_params['hostname']

rawDescription: Get value from dict

description: Get value from dict


code:
from django.utils import simplejson

def gen_groups(lines):
   """ Returns contiguous groups of lines in a file """

   group = []

   for line in lines:
      line = line.strip()
      if not line and group:
         yield group
         group = []
      elif line:
         group.append(line)

def gen_albums(groups):
   """ Given groups of lines in an album file, returns albums  """

   for group in groups:
      title    = group.pop(0)
      songinfo = zip(*[iter(group)]*2)
      songs    = [dict(title=title,url=url) for title,url in songinfo]
      album    = dict(title=title, songs=songs)

      yield album

input = open('albums.txt')
groups = gen_groups(input)
albums = gen_albums(groups)

print simplejson.dumps(list(albums))

rawDescription: What is the correct way to generate a json from file in GoogleAppEngine?


code:
from PIL import Image

im = Image.open('a.png')
pixels = list(im.getdata())
width, height = im.size

pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]

for idx, y in enumerate(pixels):
    if y[0] == (255, 255, 255):
        print "Line {} is white.".format(idx)

rawDescription: How should I select a colored line in a picture using Python?


code:
#! /usr/bin/env python

null_stream = (None, None)

def reduce(f, result, stream):
    if stream is null_stream: return result
    return reduce(f, f(result, head(stream)), tail(stream))

def take(N, stream):
    if N <= 0 or stream is null_stream: return null_stream
    return (head(stream), lambda: take(N-1, tail(stream)))

def filter(pred, stream):
    if stream is null_stream: return null_stream
    if pred(head(stream)):
        return (head(stream), lambda: filter(pred, tail(stream)))
    return filter(pred, tail(stream))

def integers_from(N): return (N, lambda: integers_from(N+1))
def head((H, _)): return H
def tail((_, T)): return T()
def to_array(stream): return reduce(lambda a, x: a + [x], [], stream)

def sieve(stream):
    if stream is null_stream: return null_stream
    h = head(stream)
    return (h, lambda: sieve(filter(lambda x: x%h != 0, tail(stream))))

def primes(): return sieve(integers_from(2))

print to_array(take(10, primes()))

rawDescription: python delayed execution

description: Python delayed execution


code:
import string
for c in string.printable:
    print c, hex(ord(c))

rawDescription: Generate a list of hex bytes in Python

description: Generate a list of hex bytes in Python


code:
import numpy as np

ARRAY_LENGTH = 500000
INTERVAL_LENGTH = 15
close = np.arange(ARRAY_LENGTH, dtype=np.float)
volume = np.arange(ARRAY_LENGTH, dtype=np.float)

def old_function(close, volume, INTERVAL_LENGTH):
    results = []
    for i in xrange(len(close) - INTERVAL_LENGTH):
        for j in xrange(i+1, i+INTERVAL_LENGTH):
            ret = close[j] / close[i]
            vol = sum( volume[i+1:j+1] )
            if (ret > 1.0001) and (ret < 1.5) and (vol > 100):
                results.append( (i, j, ret, vol) )
    return results

def new_function(close, volume, INTERVAL_LENGTH):
    results = []
    for i in xrange(close.size - INTERVAL_LENGTH):
        vol = volume[i+1:i+INTERVAL_LENGTH].cumsum()
        ret = close[i+1:i+INTERVAL_LENGTH] / close[i]

        filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100)
        j = np.arange(i+1, i+INTERVAL_LENGTH)[filter]

        tmp_results = zip(j.size * [i], j, ret[filter], vol[filter])
        results.extend(tmp_results)
    return results

def new_function2(close, volume, INTERVAL_LENGTH):
    vol, ret = [], []
    I, J = [], []
    for k in xrange(1, INTERVAL_LENGTH):
        start = k
        end = volume.size - INTERVAL_LENGTH + k
        vol.append(volume[start:end])
        ret.append(close[start:end])
        J.append(np.arange(start, end))
        I.append(np.arange(volume.size - INTERVAL_LENGTH))

    vol = np.vstack(vol)
    ret = np.vstack(ret)
    J = np.vstack(J)
    I = np.vstack(I)

    vol = vol.cumsum(axis=0)
    ret = ret / close[:-INTERVAL_LENGTH]

    filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100)

    vol = vol[filter]
    ret = ret[filter]
    I = I[filter]
    J = J[filter]

    output = zip(I.flat,J.flat,ret.flat,vol.flat)
    return output

results = old_function(close, volume, INTERVAL_LENGTH)
results2 = new_function(close, volume, INTERVAL_LENGTH)
results3 = new_function(close, volume, INTERVAL_LENGTH)

# Using sets to compare, as the output
# is in a different order than the original function
print set(results) == set(results2)
print set(results) == set(results3)

rawDescription: How to speed-up python nested loop?

description: Speed-up python nested loop


code:
list1 = [0,0,0,0,0,1,2]
count = 0
for item in list1:
    if item != 0: break
    count = count + 1

print count

rawDescription: While in a for loop

description: While in a for loop


code:
def rot13(entry):
    for each_word in entry:
        print each_word
    return entry

rawDescription: Very basic Q regarding for Loops in Python


code:
import threading

# called by each thread
def do_task(f) :
  with open(f,'r') as fi:
     lines = fi.read().splitlines()
     print len(lines)

threads = []
files = glob.glob('*.txt') # 5 files
for f in files:
    t = threading.Thread(target=do_task, args = (f))
    threads.append(t)
    t.start()

for t in threads :
    t.join()

rawDescription: Running multiple programs from the for loop


code:
from re import sub, match

def match_string(input, pattern, valid_words, date_format):
    errors = []

    # makes sure that input and pattern are compatible
    regex_pattern = sub(r'#{1,3}', '(.+?)', pattern)
    if not match(regex_pattern, input):
        return 'Error: Input doesn\'t match pattern!'

    # converts the data_format to a regex
    date_regex = sub(r'%d', '(?P<day>\d+)', date_format)
    date_regex = sub(r'%m', '(?P<month>\d+)', date_regex)
    date_regex = sub(r'%y', '(?P<year>\d+)', date_regex)

    # extracts the dates
    regex_pattern = sub(r'###', '(.+?)', pattern)
    regex_pattern = sub(r'##', '(?:.+?)', regex_pattern)
    regex_pattern = sub(r'#', '(?:.+?)', regex_pattern)
    for date in match(regex_pattern, input).groups():
        m = match(date_regex, date)
        if not m:
            errors.append('Error: %s is not a valid date!' % date)
        else:
            if int(m.group('day')) < 1 or 31 < int(m.group('day')):
                errors.append('Error: %s is not a valid day!' % m.group('day'))
            if int(m.group('month')) < 1 or 12 < int(m.group('month')):
                errors.append('Error: %s is not a valid month!' % m.group('month'))

    # extracts the generic words
    regex_pattern = sub(r'###', '(?:.+?)', pattern)
    regex_pattern = sub(r'##', '(.+?)', regex_pattern)
    regex_pattern = sub(r'#', '(?:.+?)', regex_pattern)
    for word in match(regex_pattern, input).groups():
        if not word.strip() in valid_words:
            errors.append('Error: %s is not a valid word!' % word)

    # extracts the numbers
    regex_pattern = sub(r'###', '(?:.+?)', pattern)
    regex_pattern = sub(r'##', '(?:.+?)', regex_pattern)
    regex_pattern = sub(r'#', '(.+?)', regex_pattern)
    for number in match(regex_pattern, input).groups():
        if not match(r'\d+', number):
            errors.append('Error: %s is not a valid number!' % number)

    if len(errors) == 0:
        return True
    else:
        return '\n'.join(errors)

print match_string('1 and 2 are numbers foo and bar are strings 12-1-2013 is a date', '# and # are numbers ## and ## are strings ### is a date', ['foo', 'bar'], '%m-%d-%y')
print
print match_string('1 is a number foo is a string 12-1-2013 is a date', '# is a number ## is a string ### is a date', ['foo'], '%m-%d-%y')
print
print match_string('foo is a number bar is a string 12-1-2013 is a date', '# is a number ## is a string ### is a date', ['foo'], '%m-%d-%y')
print
print match_string('1 is a number bar is a string 12-1-2013 is a date', '# is a number ## is a string ### is a date', ['foo'], '%m-%d-%y')
print
print match_string('1 is a number foo is a string January is a date', '# is a number ## is a string ### is a date', ['foo'], '%m-%d-%y')

rawDescription: Python: matching strings against pattern strings with number, string, and date placeholders with good error catching


code:
a = ['foo', 'bar', 'foorbar']
for i, name in enumerate(a):
    print 'item %d is %s' % (i, name)

rawDescription: Python: Iterating on the lines and columns of an array


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

GPIO.setmode(GPIO.BCM)
GPIO.setup(10, GPIO.IN)

class PersamaanKuadrat:
    def __init__(self, parent, title):
        self.parent = parent

        #self.parent.geometry("1280x560")
        self.parent.title(title)
        self.parent.protocol("WM_DELETE_WINDOW")

        self.aturKomponen()

        self.parent.after(10, self.atur)
        self.parent.after(500, self.change_color)

    def aturKomponen(self):

        self.customFont = tkFont.Font(family="Helvetica", size=18)

        mainCanvas = Canvas(self.parent, width=1300, height=600, bg="grey")
        mainCanvas.pack(fill=BOTH, expand=YES)

        self.kanvas = mainCanvas

        self.btnCariAkar = Button(mainCanvas, text="ENTER!",
            command=exit)
        self.btnCariAkar.place(relx=.25, rely=.25)

        self.btn1= Button(mainCanvas, padx=30, pady=30, text="A1", bg="white")
        self.btn1.place(relx=.65, rely=.25)

        self.btn2 = Button(mainCanvas, padx=30, pady=30, text="A2", bg="white")
        self.btn2.place(relx=.80, rely=.25)

        self.btn3 = Button(mainCanvas, padx=30, pady=30, text="B1", bg="white")
        self.btn3.place(relx=.65, rely=.55)

        self.btn4 = Button(mainCanvas, padx=30, pady=30, text="B2", bg="white")
        self.btn4.place(relx=.80, rely=.55)

    def atur(self):
        print "test push-button"
        inputValue = GPIO.input(10)
        if(inputValue == True):
            self.btn1.configure(bg="yellow")
        else:
            self.btn1.configure(bg="red")
        self.parent.after(10, self.atur)

    def change_color(self):
        print "change_color"
        if self.btn2['bg'] == 'yellow':
            self.btn2['bg'] = 'red'
        else:
            self.btn2['bg'] = 'yellow'
        self.parent.after(500, self.change_color)

if __name__ == '__main__':
    root = Tk()

    aplikasi = PersamaanKuadrat(root, "T")

    root.mainloop()

rawDescription: Change the color widget by using GPIO in Raspberry


rawDescription: Can you split a set into equal parts?

description: Split a set into equal parts


code:
import re
p = re.compile(r'(?P<l>\d+)x(?P<w>\d+)x(?P<h>\d+)')
test_str = "340x9x20"
m = p.search(test_str)
if (m):
    print m.group("w") # => prints "9" (width)

rawDescription: python regular expression "12x4x67" match only the second group of numbers

description: Python regular expression "12x4x67" match only the second group of numbers


code:
import struct
mybigvalue = "69dda8455c7dd4254bf353b773304eec".decode('hex')
lastInt = struct.unpack('<I', mybigvalue[-4:])[0]
lastInt += 1
mybigvalue = mybigvalue[:-4] + struct.pack('<I', lastInt & ((1 << 32) - 1))
print mybigvalue.encode('hex')

rawDescription: How do I convert raw ascii values in string to integer?

description: Convert raw ascii values in string to integer


code: print "['{}']".format("', '".join(map(str.rstrip, sentence_List)))

rawDescription: readlines() function and unicodes

description: Readlines() function and unicodes


code:
N = 128
n = 2

for i in range(N):
    m = n
    s = []
    for j in range(N - i):
        s.append(m)
        m += (j + 1) + (i + 1)

    print i + 1, s
    n += i + 1

rawDescription: Newbie algorithm design

description: Newbie algorithm design


code:
from lxml.html import fragments_fromstring, fromstring, tostring
from re import compile
def markup_aware_sub(pattern, repl, text):
    exp = compile(pattern)
    root = fromstring(text)
    els = [el for el in root.getiterator() if el.text]
    els = [el for el in els if el.text.strip()]

    if len(els) == 1:
      el = els[0]
      text = exp.sub(repl, el.text)
      parent = el.getparent()
      new_el = fromstring(text)
      new_el.tag = el.tag
      for k, v in el.attrib.items():
          new_el.attrib[k] = v
      return tostring(new_el)

    for el in els:
      text = exp.sub(repl, el.text)
      if text == el.text:
        continue
      parent = el.getparent()
      new_el = fromstring(text)
      new_el.tag = el.tag
      for k, v in el.attrib.items():
          new_el.attrib[k] = v
      parent.replace(el, new_el)
    return tostring(root)

print markup_aware_sub('keyword', 'blah', '
Text with keyword here
')

rawDescription: Regex replace text nodes in an html document


code:
for indexTag in (0, 1):
    print 'indexTag:', indexTag
    print 'boolean not:', not indexTag
    print 'subtraction:', 1 - indexTag
    print 'conditional expression:', 0 if indexTag else 1
    print

rawDescription: What would be a compact way to return 1 if a variable is 0 and to return 0 if it is 1?


code:
f(a, 2, 3)
f(b, 1, a)
print b

rawDescription: How can you output a varying argument in Python?

description: Output a varying argument in Python


code:
import base64
import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        """
        if input object is a ndarray it will be converted into a dict holding dtype, shape and the data base64 encoded
        """
        if isinstance(obj, np.ndarray):
            data_b64 = base64.b64encode(obj.data)
            return dict(__ndarray__=data_b64,
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder(self, obj)

def json_numpy_obj_hook(dct):
    """
    Decodes a previously encoded numpy ndarray
    with proper shape and dtype
    :param dct: (dict) json encoded ndarray
    :return: (ndarray) if input was an encoded ndarray
    """
    if isinstance(dct, dict) and '__ndarray__' in dct:
        data = base64.b64decode(dct['__ndarray__'])
        return np.frombuffer(data, dct['dtype']).reshape(dct['shape'])
    return dct

# Overload dump/load to default use this behavior.
def dumps(*args, **kwargs):
    kwargs.setdefault('cls', NumpyEncoder)
    return json.dumps(*args, **kwargs)

def loads(*args, **kwargs):
    kwargs.setdefault('object_hook', json_numpy_obj_hook)
    return json.loads(*args, **kwargs)

def dump(*args, **kwargs):
    kwargs.setdefault('cls', NumpyEncoder)
    return json.dump(*args, **kwargs)

def load(*args, **kwargs):
    kwargs.setdefault('object_hook', json_numpy_obj_hook)
    return json.load(*args, **kwargs)

if __name__ == '__main__':

    data = np.arange(3, dtype=np.complex)

    one_level = {'level1': data, 'foo':'bar'}
    two_level = {'level2': one_level}

    dumped = dumps(two_level)
    result = loads(dumped)

    print '\noriginal data', data
    print '\nnested dict of dict complex array', two_level
    print '\ndecoded nested data', result

rawDescription: Json Encoder AND Decoder for complex numpy arrays


code:
tic = time.time()
new_result = np.zeros(im.shape)
coords = np.array([yy,xx])
for d in range(im.shape[2]):
    ndimage.map_coordinates(im[:,:,d],
                            coords,order=1,
                            prefilter=False,
                            output=new_result[:,:,d] )
toc = time.time()

print "interpolation time:",toc-tic

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


code:
import zipfile

def isdir(z, name):
    return any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist())

f = zipfile.ZipFile("sample.zip", "r")
print isdir(f, "a")
print isdir(f, "a/b")
print isdir(f, "a/X")

rawDescription: Check if a directory exists in a zip file with Python


code:
bookdict = {'Dickens,Charles': ['Hard Times', '7', '27.00'],
 'Shakespeare,William': [['Rome And Juliet', '5', '5.99'], ['Macbeth', '3', '7.99']]}

def changeQuantity(authorlast,authorfirst,bookname,newquant):
    bookfound = False
    author = str(authorlast)+','+str(authorfirst)
    if not author in bookdict:
        return "Author not in inventory"
    temp = bookdict.values()
    if type(bookdict[author][0]) == list:
        for entry in bookdict[author]:
            if entry[0] == bookname:
                entry[1] = newquant
                bookfound = True
    else:
        if bookdict[author][0] == bookname:
            bookdict[author][1] = newquant
            bookfound = True
    if bookfound == False:
        return "Book not in author inventory"
    return bookdict

def sumInventory():
    sum = 0
    for key in bookdict.keys():
        if type(bookdict[key][0]) == list:
            for entry in bookdict[key]:
                sum += int(entry[1])
        else:
            sum += int(bookdict[key][1])
    return sum

print changeQuantity("Dickens","Charles","Hard Times",2)
print changeQuantity("a","b","Hard Times",2)
print changeQuantity("Shakespeare", "William", "a", 7)
print sumInventory()

rawDescription: Mutate a list within a dictionary

description: Mutate a list within a dictionary


code:
def work(name):
    qlock.acquire()
    acqorder.append(name)

from time import sleep
if 0:
    qlock = threading.Lock()
else:
    qlock = QLock()
qlock.acquire()
acqorder = []
ts = []
for name in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    t = threading.Thread(target=work, args=(name,))
    t.start()
    ts.append(t)
    sleep(0.1) # probably enough time for .acquire() to run
for t in ts:
    while not qlock.locked():
        sleep(0)  # yield time slice
    qlock.release()
for t in ts:
    t.join()
assert qlock.locked()
qlock.release()
assert not qlock.locked()
print "".join(acqorder)

rawDescription: How Do I Queue My Python Locks?

description: How Do I Queue My Python Locks


code:
def fast_iter(context, func, *args, **kwargs):
    """
    http://lxml.de/parsing.html#modifying-the-tree
    Based on Liza Daly's fast_iter
    http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
    See also http://effbot.org/zone/element-iterparse.htm
    """
    for event, elem in context:
        func(elem, *args, **kwargs)
        # It's safe to call clear() here because no descendants will be
        # accessed
        elem.clear()
        # Also eliminate now-empty references from the root node to elem
        for ancestor in elem.xpath('ancestor-or-self::*'):
            while ancestor.getprevious() is not None:
                del ancestor.getparent()[0]
    del context

def process_element(elem):
    print elem.xpath( 'description/text( )' )

context = etree.iterparse( MYFILE, tag='item' )
fast_iter(context,process_element)

rawDescription: Using Python Iterparse For Large XML Files


code: print ''.join([etree.tostring(child) for child in root.iterdescendants()])

rawDescription: Equivalent to InnerHTML when using lxml.html to parse HTML


code:
from itertools import chain

x = xrange(3)
y = xrange(3, 7)
z = chain(x, y) # pass this to your template
for i in z:
    print i

rawDescription: Concatenate lists in JINJA2

description: Concatenate lists in JINJA2


code:
from bs4 import BeautifulSoup

data = """

  Post Primary
 school

 Roll number: b>
 "60000"

 Principal
 "Paul Ince"

 Enrolment:
 "Boys; 123 Girls: 102   (2012/13)"

 Ethos:
 "Catholic  &nbsp "
 Catchment:
 "North Inner CIty "

 Fees:
 " No "
"""

soup = BeautifulSoup(data)

keys = ['Enrolment', 'Ethos', 'Fees']

for element in soup('b'):
    if element.text[:-1] in keys:
        print element.text + element.next_sibling.strip()

rawDescription: Parsing an html page using beautifulsoup/python


code:
from collections import defaultdict

input_ = '''dir/file
dir/dir2/file2
dir/file3
dir2/alpha/beta/gamma/delta
dir2/alpha/beta/gamma/delta/
dir3/file4
dir3/file5'''

FILE_MARKER = '<files>'

def attach(branch, trunk):
    '''
    Insert a branch of directories on its trunk.
    '''
    parts = branch.split('/', 1)
    if len(parts) == 1:  # branch is a file
        trunk[FILE_MARKER].append(parts[0])
    else:
        node, others = parts
        if node not in trunk:
            trunk[node] = defaultdict(dict, ((FILE_MARKER, []),))
        attach(others, trunk[node])

def prettify(d, indent=0):
    '''
    Print the file tree structure with proper indentation.
    '''
    for key, value in d.iteritems():
        if key == FILE_MARKER:
            if value:
                print '  ' * indent + str(value)
        else:
            print '  ' * indent + str(key)
            if isinstance(value, dict):
                prettify(value, indent+1)
            else:
                print '  ' * (indent+1) + str(value)

main_dict = defaultdict(dict, ((FILE_MARKER, []),))
for line in input_.split('\n'):
    attach(line, main_dict)

prettify(main_dict)

rawDescription: Construct a tree from list os file paths (Python) - Performance dependent


code:
def updatePlotAdd(self):
    print "updatePlotAdd"
    rax = plt.axes([0.01, 0.7, 0.08, 0.1], axisbg='grey')
    self.radioDim = RadioButtons(rax, ("2D", "3D","> 3D"), active=self.add_dim-2)
    self.radioDim.on_clicked(self.click_dim)
    self.fig2.canvas.draw()

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


code:
from bs4 import BeautifulSoup
from itertools import takewhile
soup = BeautifulSoup('''\

Game1. How to get all listings below and assign to class"game"?

Game2. How to get all listings below and assign to class"game?

Game3. How to get all listings below and assign to class"game?

''')
div = soup.find('div', class_='layout4-background')
for header in div.find_all('h6'):
    print header.get_text()
    listings = takewhile(lambda t: t.name == 'ul',
                         header.find_next_siblings(text=False))
    print 'Listings found:', len(list(listings))

rawDescription: python BeautifulSoup how get values between tags?

description: Python BeautifulSoup how get values between tags


code:
while True:
    l = sys.stdin.readline()
    if not l: break
    l = l.decode('utf-8', 'replace')
    print l

rawDescription: delays in reading stdin with codecs

description: Delays in reading stdin with codecs


code:
variables = ['piece', 'date_in', 'date_out', 'time_int', 'time_out', 'num', 'op', 'urg', 'worked_time']

for arr, typ in zip(arrays, types):
    print typ
    for col in zip(*arr):
        #if you want variables here then use:
        # piece, date_in ,.... = col
        d = dict(zip(variables, col))
        #Do something with the variables or dict here
    print

rawDescription: Print a python array on a specific format


code:
print "Changing current directory to %s" % os.path.dirname(os.path.realpath(__file__))
os.chdir(os.path.dirname(os.path.realpath(__file__)))

rawDescription: Reading multiple lines from an external text file in Python


code:
if __name__ == '__main__':
    imcv = cv2.imread('ocrtest.png')
    height, width, depth = imcv.shape

    tess = Tesseract()
    tess.set_image(imcv.ctypes, width, height, depth)
    text = tess.get_text()

    print text.strip()

rawDescription: Using C API of tesseract 3.02 with ctypes and cv2 in python


code:
import urllib2
from bs4 import BeautifulSoup

data = urllib2.urlopen('http://www.cofemersimir.gob.mx/mirs/38656')

data = data.read()

soup = BeautifulSoup(data, 'html.parser')

print soup.find('div',{'name':"Pregunta_459Respuesta_841"})

rawDescription: Look for text with BeautifulSoup in a web page with multiple html tags?


code:
import re

def splitRawString(s):
    return map(lambda x: re.sub('^"?([^"]*)"?$', r'\1', x),
        re.split('"\s*"', s))

a='"Hello" "World" "String 1" "String 2" "String 3" "Sting 4" "Hello" "World" "String 5" "String 6" "String 7" "String 8" "Hello" "World" "String 9" "String 10" "String 11" "String 12"'
print splitRawString(a)

rawDescription: Python Manipulating String

description: Python Manipulating String


code:
import random
rows = [[None] * 10 for i in xrange(10)] # or numpy matrix
for i, row in enumerate(rows):
    for j, _ in enumerate(row):
        available = set(xrange(256))
        if j > 0:
            available.discard(row[j-1])
        if i > 0:
            available.difference_update(rows[i-1][max(0,j-1):j+2])
        row[j] = random.choice(tuple(available))
print '\n'.join(map(str, rows))

rawDescription: Filling a 2D matrix so that no two neighbouring values are the same


code:
import ast
data = ast.literal_eval("{'y': 0.02, 'x': -1.0188, 'z': 2.026}")
print type(data)

rawDescription: Extract variables from string in python

description: Extract variables from string in python


code:
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-b', '--bucket', dest='bucketname', action='store')
    parser.add_argument('-f', '--folder', dest='folder', action='store')
    args = parser.parse_args('-b foo'.split())
    print args
    args = parser.parse_args('-b foo -f /foo'.split())
    print args

rawDescription: implementation of command line arg passing in python, doesn't work

description: Implementation of command line arg passing in python, doesn't work


code:
import random # instead of numpy
import time
timer_func = time.clock # better on Windows, use time.time on *x platform

class Person(object):
    def __init__(self, util):
        self.utility = util
        self.customer = 0

class Population(object):
    def __init__(self, numpeople):
        random.seed(1)
        self.people = [Person(random.uniform(0, 300)) for i in xrange(numpeople)]
        self.cus = []
        self.noncus = []

def f_w_append(popn):
    '''Function with append'''
    P = 75
    cus = []
    noncus = []
    for per in popn.people:
        if  per.utility >= P:
            per.customer = 1
            cus.append(per)
        else:
            per.customer = 0
            noncus.append(per)
    popn.cus = cus # omitted from OP's code
    popn.noncus = noncus # omitted from OP's code
    return len(cus)

def f_w_append2(popn):
    '''Function with append'''
    P = 75
    popn.cus = []
    popn.noncus = []
    cusapp = popn.cus.append
    noncusapp = popn.noncus.append
    for per in popn.people:
        if  per.utility >= P:
            per.customer = 1
            cusapp(per)
        else:
            per.customer = 0
            noncusapp(per)
    return len(popn.cus)

def f_wo_append(popn):
    '''Function without append'''
    P = 75
    for per in popn.people:
        if  per.utility >= P:
            per.customer = 1
        else:
            per.customer = 0

    numcustomers = 0
    for per in popn.people:
        if per.customer == 1:
            numcustomers += 1
    return numcustomers

def f_wo_append2(popn):
    '''Function without append'''
    P = 75
    numcustomers = 0
    for person in popn.people:
        person.customer = iscust = person.utility >= P
        numcustomers += iscust
    return numcustomers

if __name__ == "__main__":
    import sys
    popsize, which, niter = map(int, sys.argv[1:4])
    pop = Population(popsize)
    func = (f_w_append, f_w_append2, f_wo_append, f_wo_append2)[which]
    t0 = timer_func()
    for _unused in xrange(niter):
        nc = func(pop)
    t1 = timer_func()
    print "popsize=%d func=%s niter=%d nc=%d seconds=%.2f" % (
        popsize, func.__name__, niter, nc, t1 - t0)

rawDescription: Increasing speed of python code

description: Increasing speed of python code


code:
import sys

x = 2
if x > 1:
    print "x > 1"
    sys.exit()
else:
    print x

rawDescription: How to remove exit(0) pop-up in Python IDLE?

description: Remove exit(0) pop-up in Python IDLE


code:
import numpy as np
import scipy.optimize as optimize
import textwrap

funcstr=textwrap.dedent('''\
def func(x, {p}):
    return x * 2*a + 4*b - 5*c
''')
def make_model(**kwargs):
    params=set(('a','b','c')).difference(kwargs.keys())
    exec funcstr.format(p=','.join(params)) in kwargs
    return kwargs['func']

func=make_model(a=3, b=1)

xdata = np.array([1,3,6,8,10])
ydata = np.array([  0.91589774,   4.91589774,  10.91589774,  14.91589774,  18.91589774])
popt, pcov = optimize.curve_fit(func, xdata, ydata)
print(popt)
# [ 5.49682045]

rawDescription: Dynamically define a function

description: Dynamically define a function


code:
from multiprocessing import Process
f = None

def child():
    print f

if __name__ == '__main__':
    f = open('mp.py', 'r')
    p = Process(target=child)
    p.start()
    p.join()

rawDescription: multiprocessing Programming guidelines unclear

description: Multiprocessing Programming guidelines unclear


code:
search_list =[{'Chr':'chr1','St':'2345','End':'2456'},{'Chr':'chr2','St':'3457','End':'4567'}]
database = [{'Chr':'chr1','St':'2348','End':'2348'},{'Chr':'chr2','St':'190','End':'190'}]

print [record for record in database for lookup in search_list
       if record['Chr'] == lookup['Chr'] if lookup['St'] <= record['St'] <= lookup['End']]

rawDescription: Using list comprehension to match values of dictionaries which are stored in lists


code:
crypt.put_CryptAlgorithm("des")
crypt.put_CipherMode("cbc")
crypt.put_KeyLength(64)
crypt.put_PaddingScheme(0)
crypt.put_EncodingMode("hex")
ivHex = "0001020304050607"
crypt.SetEncodedIV(ivHex,"hex")
keyHex = "0001020304050607"
crypt.SetEncodedKey(keyHex,"hex")
encStr = crypt.encryptStringENC("The quick brown fox jumps over the lazy dog.")
print encStr
decStr = crypt.decryptStringENC(encStr)
print decStr

rawDescription: using DES/3DES with python

description: Using DES/3DES with python


code:
import pytz
from datetime import datetime, time, timedelta

tz = pytz.timezone('Europe/London')
start_datetime = tz.localize(datetime(2014, 03, 30, 0, 0, 0))

# Increment using timedelta
print 'This works:'
d = start_datetime
for i in range(5):
    print str(d) + ' ' + d.tzname()
    d = tz.normalize(d + timedelta(minutes=30))  # Add 30 minutes

# Increment by adding seconds to epoch
print 'This works too:'
epoch = datetime.fromtimestamp(0, pytz.utc)
timestamp = (start_datetime - epoch).total_seconds()
for i in range(5):
    d = datetime.fromtimestamp(timestamp, pytz.utc).astimezone(tz)
    print str(d) + ' ' + d.tzname()
    timestamp += 30 * 60  # Add 30 minutes

rawDescription: Dates and time zone codes around a DST change


code:
with open("file1.txt", "r") as fd:
    keys = fd.readlines()
keys = [k.strip() for k in keys]
for k in keys:
    print "%s %s" % (k, dict[k])

rawDescription: compare diferent files and get things in common

description: Compare diferent files and get things in common


code:
import argparse

class PositionalAction(argparse.Action):
    def __call__(self,parser,namespace,values,option_string=None):
        lst = getattr(namespace,self.dest)
        lst.append(values)
        parser.last_positional_values = lst
        all_positional = getattr(namespace,'all_positional',[])
        all_positional.append(lst)
        namespace.all_positional = all_positional

class AssociateAction(argparse.Action):
    def __call__(self,parser,namespace,values,option_string=None):
        try:
            parser.last_positional_values.append(values)
        except AttributeError:
            pass

parser = argparse.ArgumentParser()
parser.add_argument('-o',action=AssociateAction,dest=argparse.SUPPRESS)
junk,unknown = parser.parse_known_args()

for i,_ in enumerate(unknown):
    parser.add_argument('arg%d'%i,action=PositionalAction,default=[])

print parser.parse_args()

rawDescription: Optional argument for each positional argument


code:
import sys
import numpy as np

print sys.argv

print np.random.random((int(sys.argv[1]), int(sys.argv[2])))

rawDescription: Using numpy via command line

description: Using numpy via command line


code:
class MainHandler(webapp2.RequestHandler):
    def get(self):
        p = Page()

        if self.request.GET:
            thing1 = self.request.GET['thing1']
            thing2 = self.request.GET['thing2']

            self.response.write(p.print_final(thing1, thing2))
            # --------------------------------^^^^^^  ^^^^^^
            print thing1 + thing2
        else:
            self.response.write(p.print_this())

rawDescription: Use variables from another class

description: Use variables from another class


code:
import os, os.path

dupnames={}
for root, dirs, files in os.walk('myfolder'):
    for file in files:
        fulpath=os.path.join(root,file)
        if file in dupnames:
            dupnames[file].append(fulpath)
        else:
            dupnames[file]=[fulpath]

for name in sorted(dupnames):
    print name, len(dupnames[name])

rawDescription: Scanning duplicate file names

description: Scanning duplicate file names


code:
if __name__ == "__main__":
    dialog = MyBrowser(None)
    print dialog.dlg_val

rawDescription: Get user input from a dialog before showing the mainframe


rawDescription: Parsing OrderedDict to Python list

description: Parsing OrderedDict to Python list


rawDescription: List cross-identification

description: List cross-identification


code:
import itertools

mystr='ABCDABCDAABCD'
optional_letter='A'

indices=[i for i,char in enumerate(list(mystr)) if char==optional_letter]

def remover(combination,mystr):

    mylist=list(mystr)

    for index in combination[::-1]:
        del mylist[index]

    return ''.join(mylist)

all_strings=[remover(combination,mystr)
             for n in xrange(len(indices)+1)
             for combination in itertools.combinations(indices,n)]

for string in all_strings: print string

rawDescription: Python help: generating all possible strings given optional character


rawDescription: Setting DataFrame values with enlargement


code:
if backData == USER:
    f = open("/mnt/lock_logs/lock_log.csv", "a");
    print f
    value = ('\n') + uname
    myString = str(value)
    f.write(myString)
    f.close()
    break

rawDescription: Why is my Python Dictionary only returning the last value?


code:
#!/usr/bin/env python

import cgitb
import subprocess
import sys

cgitb.enable()

sys.stdout.write("Content-type: text/plain\r\n\r\n")

p = subprocess.Popen("/usr/games/fortune",stdout=subprocess.PIPE)
data = p.stdout.read()
p.wait()

print data

rawDescription: Run a .exe file serverside by a CGI python script


code:
#!/grid/common/bin/python
import sys, time
import subprocess
import cgi, cgitb
cgitb.enable()

print 'Content-Type: text/html;charset=utf-8\r\n\r\n'

print '<html><body>'

PIPE = subprocess.PIPE
pd = subprocess.Popen(['abc.py'],
                        stdout=PIPE, stderr=PIPE)
while True:
    output = pd.stdout.read(1)
    if output == '' and pd.poll() != None:
      break
    if output != '':
      sys.stdout.write(output)
      sys.stdout.flush()

rawDescription: Python cgi script displays output in the browser only after its completion


rawDescription: python file iteration to change the formatting of output (going from a column to line)

description: Python file iteration to change the formatting of output (going from a column to line)


rawDescription: How can I turn random matrix into a table?

description: Turn random matrix into a table


code:
data_file = 'my_file.10.4.5.6.csv'
parts = data_file.split('.')
print parts[0] + '.' + parts[-1]

rawDescription: Python regex to extract substring at start and end of string


code:
from collections import deque

def window(iterable, n=3):
    it = iter(iterable)
    d = deque(maxlen = n)
    for elem in it:
        d.append(elem)
        yield tuple(d)

print [x for x in window([1, 2, 3, 4, 5])]
# [(1,), (1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]

rawDescription: Iterator with memory?

description: Iterator with memory


code:
x = 0
while True:
    print x
    x += 1

rawDescription: Print numbers from 1 to x where x is infinity in python


code:
import os
cdir=os.getcwd().split(os.sep)[-1]
print cdir

rawDescription: copy directory name and placing it into a variable (python)

description: Copy directory name and placing it into a variable (python)


rawDescription: deleting semicolons in a column of csv in python

description: Deleting semicolons in a column of csv in python


code:
test = mmatrix(3,3)
for row in test:
    print row

rawDescription: Inserting a new line in a 2D matrix

description: Inserting a new line in a 2D matrix


code:
def luhn_checksum(card_number):
    def digits_of(n):
        return [int(d) for d in str(n)]
    digits = digits_of(card_number)
    odd_digits = digits[-1::-2]
    even_digits = digits[-2::-2]
    checksum = 0
    checksum += sum(odd_digits)
    for d in even_digits:
        checksum += sum(digits_of(d*2))
    return checksum % 10

def is_luhn_valid(card_number):
    return luhn_checksum(card_number) == 0

result = is_luhn_valid(4532015112830366)
print 'Correct:' + str(result)
result = is_luhn_valid(6011514433546201)
print 'Correct:' + str(result)
result = is_luhn_valid(6771549495586802)
print 'Correct:' + str(result)

rawDescription: Implementation of Luhn Formula

description: Implementation of Luhn Formula


code:
mystring="""
    qwertyuiop
    asdfghjkl
    zxcvbnm
    token qwerty
    asdfghjklñ
"""
for item in mystring.split("\n"):
 if "token" in item:
    print item.strip()

rawDescription: Search and get a line in Python

description: Search and get a line in Python


code:
group1 = ["Steve", "Mark", "Tom"]
group2 = ["Brett", "Mick", "Foo"]
group3 = ["Dan", "Phil"]
for x in itertools.product(group1, group2, group3):
    print x

rawDescription: Python combinatorials w/o repetition - Pyncomb?


code:
for group, items in itertools.groupby('aabbbccdddee'):
    print group, list(items)

rawDescription: Regarding the correct usage of groupby(): Python 3


code:
import wx

class GameFrame(wx.Frame):

    def __init__(self,parent,id):

        self.shutdown_showing = False
        wx.Frame.__init__(self, parent, id, "Project - Map", size=(860, 640))
        wx.Frame.CenterOnScreen(self)
        self.SetBackgroundColour("green")
        self.wndwsbtn = wx.Bitmap("Your Image")
        self.wbtn = wx.StaticBitmap(self, -1, self.wndwsbtn)
        self.wbtn.SetPosition((2, 585))
        self.wbtn.Bind(wx.EVT_LEFT_DOWN, self.wstart)
        self.wbtn.SetToolTip(wx.ToolTip("Start"))

    def wstart(self, event):
        if self.shutdown_showing:
            self.wstdwnbtn.Destroy()# Destroy self.wstdwnbtn
            self.Layout()
            print "Destroyed"
            self.shutdown_showing = False
        # if not self.shutdown_showing: This was wrong.
        else:
            self.shutdownbtn = wx.Bitmap("Your image")
            # Create self.wstdwnbtn on self.wbtn instead.
            self.wstdwnbtn = wx.StaticBitmap(self.wbtn, -1, self.shutdownbtn)
            self.wstdwnbtn.SetPosition((0, 550))
            self.wstdwnbtn.Bind(wx.EVT_LEFT_DOWN, self.wexit)
            self.wstdwnbtn.SetToolTip(wx.ToolTip("Exit to main menu."))
            self.shutdown_showing = True

    def wexit(self, event):
        print "Exit"

if __name__=='__main__':
    app=wx.App(redirect=False)
    frame=GameFrame(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

rawDescription: wxPython - Bitmap button won´t be destroyed

description: WxPython - Bitmap button won´t be destroyed


code:
print intersection('Today I am fine'.split(),
                   'Hello How a re you TODAY'.split(),
                   key=str.lower)
# -> [(['Today'], ['TODAY'])]

rawDescription: Case-insensitive comparison of sets in Python


rawDescription: Pandas and NumPy default width change on startup


code:
text = u'''我今天的心情不好。
 I'm feeling blue today.'''
import regex
print u''.join(regex.findall(r'\p{Han}+', text, flags=regex.UNICODE))

rawDescription: Converting unicode to Chinese

description: Converting unicode to Chinese


rawDescription: why does python new york time zone display 4:56 instead 4:00?

description: Why does python new york time zone display 4:56 instead 4:00


code:
n = 0

def numberofdays ():
    total = 0
    for i in range (1901, 2000):
        if i%4 == 0:
            total = total + 366
        else:
            total = total + 365
    return total

n = numberofdays() + 365 #to account for year 2000.

print n

rawDescription: Simple For loop confusion

description: Simple For loop confusion


code: print 'Date: {0}   Avg Price: {1}'.format(dt, avg_price)

rawDescription: Trouble parsing API JSON output with python using 'requests'


rawDescription: Numpy: Is there an array size limit?

description: Numpy: Is there an array size limit


code:
response, addr = s.recvfrom(65535)
response_id = struct.unpack('!H', response[4:6])
print response_id

rawDescription: Using raw socket in Python

description: Using raw socket in Python


code:
from amazon.api import AmazonAPI
amazon = AmazonAPI(ACCESS_KEY, SECRET, ASSOC)
results = amazon.search(Keywords = "book name", SearchIndex = "Books")
for item in results:
    print item.title, item.isbn, item.price_and_currency

rawDescription: Searching for books with the Amazon Product Advertising API - Python


code:
from string import ascii_lowercase
from random import choice
from StringIO import StringIO

buf = ''.join(choice(ascii_lowercase) for _ in range(50))
print buf

sio_buf = StringIO(buf) # make it a bit more like a stream object
first16 = sio_buf.read(16)
print first16

from collections import deque
last16 = deque(iter(lambda: sio_buf.read(1), ''), 16) # read(1) may look bad but it's buffered anyway - so...
print ''.join(last16)

rawDescription: Is there a Python module for transparently working with a file-like object as a buffer?


code:
# even though this is a small example, it's usually preferred
# to import the modules from a readability standpoint [1]
import sys

# we'll import time so we can get todays date, so you can record
# when you worked out
import time

# you'll likely want to check that the user provided arguments
if len(sys.argv) != 2:
    # we'll print a nice message that will show the user
    # how to use the script
    print "usage: {} <workout_file>".format(sys.argv[0])

    # after printing the message, we'll exit with an error-code
    # because we can't do anything else!
    sys.exit(1)

# `sys.argv[1]` should contain the first command line argument,
# which in this case is the name of the data file we want
# to write to (and subsequently read from when we're plotting)
# therefore, the type of `f` below is `str` (string).
#
# Note: I changed the name from `file` to `filename` because although `file`
# is not a reserved word, it's the name of a built-in type (and constructor) [2]
filename = sys.argv[1]

# in Python, it's recommended to use a `with` statement
# to safely open a file. [3]
#
# Also, note that we're using 'a' as the mode with which
# to open the file, which means `append` rather than `write`.
# `write` will overwrite the file when we call `f.write()`, but
# in this case we want to `append`.
#
# Lastly, note that `target_file` is the name of the file object,
# which is the object to which you'll be able to read or write or append.
with open(filename, 'a') as target_file:

    # you'd probably want the csv-form to look like
    #
    #   benchpress,2,5,225
    #
    # so for the general case, let's build this up
    workout = raw_input("Enter what workout you did today: ")
    num_sets = raw_input("Enter the number of sets you did today")
    num_reps = raw_input("Enter the number of reps per set you did today")
    weight = raw_input("Enter the weight you lifted today")

    # you might also want to record the day and time you worked out [4]
    todays_date = time.strftime("%Y-%m-%d %H:%M:%S")

    # this says "join each element in the passed-in tuple/list
    # as a string separated by a comma"
    workout_entry = ','.join((workout, num_sets, num_reps, weight, todays_date))

    # you don't need to save all the entries to a list,
    # you can simply write the workout out to the file obj `target_file`
    target_file.write(workout_entry)

    # Note: I removed the `target_file.close()` because the file closes when the
    # program reaches the end of the `with` statement.

rawDescription: python: write input to file and save it

description: Python: write input to file and save it


code:
import random
import timeit

def random_date_tuple():
    s1 = '{0}-{1:02}-{2:02}'.format(random.randint(2000, 2050),
                                    random.randint(1, 12),
                                    random.randint(1, 31))
    e2 = random.randint(1,50)
    return (s1, e2)

def my_cmp(a, b):
    result = cmp(a[0], b[0])   # comparing the date part of the tuple
    if result == 0:
        return cmp(a[1], b[1]) # comparint the other part of the tuple
    return result

def my_insort_left(a, x, cmp=my_cmp, lo=0, hi=None):
    """The bisect.insort_left() modified for comparison of tuples."""

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if cmp(a[mid], x) < 0:
            lo = mid+1
        else:
            hi = mid
    a.insert(lo, x)

def bisect_solution3(size=1000):
    lst = []
    for n in xrange(size):
        value = random_date_tuple()
        my_insort_left(lst, value)
    return lst

def sort_solution(size=1000):
    lst = []
    for n in xrange(size):
        value = random_date_tuple()
        lst.append(value)
        lst.sort(cmp=my_cmp)
    return lst

t = timeit.timeit('bisect_solution3()', 'from __main__ import bisect_solution3', number = 10)
print "bisect_solution3: ", t

t = timeit.timeit('sort_solution()', 'from __main__ import sort_solution', number = 10)
print "sort_solution: ", t

print bisect_solution3()[:10]

rawDescription: Fastest way to sort list of dates when adding to the list


code:
import numpy as np
strc = np.zeros(3, dtype=[('x', int), ('y', float), ('z', int), ('t', "i8")])

def fields_view(arr, fields):
    dtype2 = np.dtype({name:arr.dtype.fields[name] for name in fields})
    return np.ndarray(arr.shape, dtype2, arr, 0, arr.strides)

v1 = fields_view(strc, ["x", "z"])
v1[0] = 10, 100

v2 = fields_view(strc, ["y", "z"])
v2[1:] = [(3.14, 7)]

v3 = fields_view(strc, ["x", "t"])

v3[1:] = [(1000, 2**16)]

print strc

rawDescription: How to return a view of several columns in numpy structured array

description: Return a view of several columns in numpy structured array


code:
#! /usr/bin/env python

''' Merge lists in a dict

    Lists are merged if they have any element in common,
    so that in the resulting dict no list element will be
    associated with more than one key.

    The key of the merged item is selected from the sub-dict with the lowest
    value of oldest_node.

    Written by PM 2Ring 2014.11.21

    From http://stackoverflow.com/q/26972204/4014959
'''

#Some test data

groups = {
    'group1': {'IDs': ['a','b','c','d'], 'oldest_node': 'node_30'},
    'group2': {'IDs': ['c','d','e'], 'oldest_node': 'node_40'},
    'group3': {'IDs': ['h','k'], 'oldest_node': 'node_2'},
    'group4': {'IDs': ['z','w','x','j'], 'oldest_node': 'node_6'},
    'group5': {'IDs': ['h','z'], 'oldest_node': 'node_9'},
}

def merge_lists(d):
    #Convert IDs to a set and oldest_node to an int
    src = {}
    for k, v in d.iteritems():
        src[k] = {
            'IDs': set(v['IDs']),
            'oldest_node': int(v['oldest_node'][5:])
        }
    #print_dict(src)

    while True:
        dest = {}
        count = 0
        while src:
            k1, temp = src.popitem()
            if temp is None:
                continue
            for k2, v in src.iteritems():
                if v is None:
                    continue
                if temp['IDs'] & v['IDs']:
                    #Merge IDs
                    temp['IDs'] |= v['IDs']

                    #Determine key of merge from oldest_node
                    if v['oldest_node'] < temp['oldest_node']:
                        k1 = k2
                        temp['oldest_node'] = v['oldest_node']
                    src[k2] = None
                    count += 1
            dest[k1] = temp

        src = dest

        #Exit loop if no changes occured
        if count == 0:
            break
        else:
            #print count
            #print_dict(src)
            pass

    #Convert dict back to original form
    dest = {}
    for k, v in src.iteritems():
        dest[k] = {
            'IDs': sorted(list(v['IDs'])),
            'oldest_node': 'node_%d' % v['oldest_node']
        }
    return dest

def print_dict(d):
    for k in sorted(d.keys()):
        print "%s: %s" % (k, d[k])
    print

def main():
    print_dict(groups)
    print 20*'-'

    dest = merge_lists(groups)
    print_dict(dest)

if __name__ == '__main__':
    main()

rawDescription: Combine dictionary entries by common elements


code:
import numpy as np
x = np.arange(10, dtype=np.int)
print 'The original int array:', x

# We would have just used y = x.astype(np.float), but it makes a copy.
# This doesn't. If we're worried about memory consumption, it's handy!
y = x.view(np.float)
y[:] = x

print 'The new float array:', y
print 'But, the old int array has been modified in-place'
print x
print "They're both views into the same memory buffer!"

rawDescription: Numpy: Permanent changes to using numpy.ndarray.view?


code:
import re

input = ['asdgaf1_hsg534', 'asdfh23_hsjd12', 'dgshg_jhfsd86']

for s in input:
    print re.sub('.*?([0-9]*)$',r'\1',s)

rawDescription: How can I detect last digits in python string

description: Detect last digits in python string


code:
import functools

class A(type):
    def __call__(cls, *args, **kwargs):
        r = super(A, cls).__call__(*args, **kwargs)
        print "%s was instantiated" % (cls.__name__, )
        print "the new instance is %r" % (r, )
        return r

class B(type):
    def __init__(cls, name, bases, dct):
        super(B, cls).__init__(name, bases, dct)
        if '__init__' not in dct:
            return
        old_init = dct['__init__']
        @functools.wraps(old_init)
        def __init__(self, *args, **kwargs):
            old_init(self, *args, **kwargs)
            print "%s (%s) was instantiated" % (type(self).__name__, cls.__name__)
            print "the new instance is %r" % (self, )
        cls.__init__ = __init__

class T1:
    __metaclass__ = A

class T2:
    __metaclass__ = B
    def __init__(self):
        pass

class T3(T2):
    def __init__(self):
        super(T3, self).__init__()

rawDescription: Metaclasses in Python: a couple of questions to clarify


code:
class State(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

class Automaton(object):
    def __init__(self, instance, start):
        self._state = start
        self.transitions = instance.transitions()

    def get_state(self):
        return self._state

    def set_state(self, target):
        transition = self.transitions.get((self.state, target))
        if transition:
            action, condition = transition
            if condition:
                if condition():
                    if action:
                        action()
                    self._state = target
            else:
                self._state = target
        else:
            self._state = target

    state = property(get_state, set_state)

class Door(object):
    open = State('open')
    closed = State('closed')

    def __init__(self, blocked=False):
        self.blocked = blocked

    def close(self):
        print 'closing door'

    def do_open(self):
        print 'opening door'

    def not_blocked(self):
        return not self.blocked

    def transitions(self):
        return {
            (self.open, self.closed):(self.close, self.not_blocked),
            (self.closed, self.open):(self.do_open, self.not_blocked),
        }

if __name__ == '__main__':
    door = Door()
    automaton = Automaton(door, door.open)

    print 'door is', automaton.state
    automaton.state = door.closed
    print 'door is', automaton.state
    automaton.state = door.open
    print 'door is', automaton.state
    door.blocked = True
    automaton.state = door.closed
    print 'door is', automaton.state

rawDescription: How to implement a Decorator with non-local equality?

description: Implement a Decorator with non-local equality


code: print post.title

rawDescription: Feedparser newbie questions

description: Feedparser newbie questions


code:
class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        # use new style signals
        self.ui.buttonBox.accepted.connect(self.accept)
        self.ui.buttonBox.rejected.connect(self.reject)

    def accept(self):
        if self.ui.radioButton.isChecked(): # no need to do ==True
            #Call continuous grabber
            print "Grabbing continuously"
        else:
            #Call trigger server
            print "Grabbing triggered"
        super(MyDialog, self).accept()  # call the accept method of QDialog.
                                           # super is needed
                                           # since we just override the accept method

rawDescription: PyQt4 - closing a dialog window, exec_() not working


code:
import StringIO
from xml.etree import ElementTree

xml_str = "<root><something></something><application></application></root>"
permission_str = "<permission></permission>"

tree = ElementTree.parse(StringIO.StringIO(xml_str))
perm_element = ElementTree.fromstring(permission_str)

# insert our permission element as the first child
tree.getroot().insert(0, perm_element)

print ElementTree.tostring(tree.getroot())

rawDescription: Python ElementTree insertBefore command

description: Python ElementTree insertBefore command


code:
visitor = ParentlessChildlessVisitor()
results = visitor.start(data)
print results
# prints [{'fun': 'funZ', 'name': 'Z'}]

rawDescription: create different list of dicts from master list of dict

description: Create different list of dicts from master list of dict


code:
from collections import Counter
c = Counter(['hello', 'hello', 1])
print c
c.update(['hello'])
print c

rawDescription: Counting unique words in python

description: Counting unique words in python


code:
def tokens(filename):
    with open(filename) as infile:
        for line in infile:
            for item in line.split():
                yield int(item)

def ballots(tokens):
    ballot = []
    for t in tokens:
        if t:
            ballot.append(t)
        else:
            yield ballot
            ballot = []

t = tokens("datafile.txt")

for b in ballots(t):
    print b

rawDescription: reading very large file where format is newline independent

description: Reading very large file where format is newline independent


code:
import urllib
d = urllib.urlopen('http://www.google.com/')
try:
    if d.info()['content-type'].startswith('text/html'):
            print 'its html'
    else:
            print 'its not html'
except KeyError:
    print 'its not html'

rawDescription: using python urllib how to avoid non HTML content

description: Using python urllib how to avoid non HTML content


code:
# Sets GPIO's to HIGH = Relays OFF
try:
    import RPi.GPIO as GPIO
except RuntimeError:
    print("Error importing RPi.GPIO!!")

print "Setting up GPIO"
GPIO.state = 'initialized'
print "Done setting up"

rawDescription: Python: How to use variables acros modules


code:
from Bio import pairwise2

for seq in seqs:
    print pairwise2.align.globalxx(ref_seq, seq)

rawDescription: Total Mismatches between two strings

description: Total Mismatches between two strings


code:
import json  # pprint doesn't handled OrderedDict :-(
print json.dumps(sort_dict(dictionary1), indent=4)

rawDescription: how to sort all levels of a Python OrderedDict

description: Sort all levels of a Python OrderedDict


code:
from bs4 import BeautifulSoup
from urllib2 import urlopen

data = """your html goes here"""

depth = 5
soup = BeautifulSoup(data)
for tag in soup.find_all():
    if len(list(tag.parents)) == depth:
        tag.extract()

print soup.prettify()

rawDescription: Removing all children tags past a specific depth


code:
class Node:
    def __init__(self, val):
        self.l_child = None
        self.r_child = None
        self.data = val

def binary_insert(root, node):
    if root is None:
        root = node
    else:
        if root.data > node.data:
            if root.l_child is None:
                root.l_child = node
            else:
                binary_insert(root.l_child, node)
        else:
            if root.r_child is None:
                root.r_child = node
            else:
                binary_insert(root.r_child, node)

def in_order_print(root):
    if not root:
        return
    in_order_print(root.l_child)
    print root.data
    in_order_print(root.r_child)

def pre_order_print(root):
    if not root:
        return
    print root.data
    pre_order_print(root.l_child)
    pre_order_print(root.r_child)

rawDescription: Implementing binary search tree in python


rawDescription: Use matplotlib to set the x-axis

description: Use matplotlib to set the x-axis


rawDescription: All permutation of number with replacement


code:
import string

s = "This is a string with 123456 []!@#$%^& stuff"
s = s.translate(None, string.digits + string.punctuation)
print s

rawDescription: pass two arguments into translate()

description: Pass two arguments into translate()


code: print Photo.objects.filter(Q(tags__name='holiday') & Q(tags__name='summer')).query

rawDescription: Django filter queryset __in for *every* item in list


code:
main = []

for x,y in zip(list1, list2):
    mid = []
    for i in values:
        if x<i<y:
            mid.append(i)
    main.append(mid)

print main

rawDescription: Grouping values into lists based on parent list


code:
from __future__ import division
import numpy as np
from sklearn.datasets import make_classification
from sklearn.neural_network import MLPClassifier

#Creating an imaginary dataset
input, output = make_classification(1000, 30, n_informative=10, n_classes=2)
input= input / input.max(axis=0)
N = input.shape[0]
train_input = input[0:N/2,:]
train_target = output[0:N/2]

test_input= input[N/2:N,:]
test_target = output[N/2:N]

#Creating and training the Neural Net
# 1. Disable verbose (verbose is annoying with partial_fit)

clf = MLPClassifier(activation='tanh', algorithm='sgd', learning_rate='constant',
 alpha=1e-4, hidden_layer_sizes=(15,), random_state=1, batch_size=1,verbose= False,
 max_iter=1, warm_start=True)

# 2. Set what the classes are
clf.classes_ = [0,1]

for j in xrange(0,100):
    for i in xrange(0,train_input.shape[0]):
       input_inst = train_input[[i]]
       target_inst= train_target[[i]]

       clf=clf.partial_fit(input_inst,target_inst)

    # 3. Monitor progress
    print "Score on training set: %0.8f" % clf.score(train_input, train_target)
#Testing the Neural Net
y_pred = clf.predict(test_input)
print y_pred

# 4. Compute score on testing set
print clf.score(test_input, test_target)

rawDescription: partial_fit Sklearn's MLPClassifier

description: Partial_fit Sklearn's MLPClassifier


code:
# removing returns by row
column = 0
while column < sheet.ncols:
    new_value = remove_returns1(34, column)
    column += 1
    print new_value,

# printing the edits
print "\n\n", edits_returns

rawDescription: How do I iterate through more than just one variable in a loop in Python?

description: Iterate through more than just one variable in a loop in Python