code:
class stringer(type):
    esc_statuses = {
        "RETURNED": "Returned",
        "SUBMITTED": "Submitted",
        "DRAFT": "Draft",
        "CANCELED": "Canceled",
        "ESCALATED": "Escalated"
        }

    NewEscFieldText = {
        "customer_name": "The name of the customer who encountered this bug.",
        "summary": "A brief summary of the bug.",
        "request": "The request.",
        "customer_impact": "How the customer is impacted.",
        "severity": "The severity of the bug.",
        "component": "The component of this bug.",
        "related_bugs": "Bugs which are related to this one.",
        "logs": "The logs assosciated with this bug.",
        "description": "A detailed discription of the problem and any work \
                put into reproducting it.",
        "documentation": "Documentation consulted before escalation.",
        }

def __getattr__(self, name):
    if name in stringer.NewEscFieldText:
        return stringer.NewEscFieldText[name]
    else:
        return stringer.esc_statuses[name]

class strings:
    __metaclass__ = stringer

print strings.customer_name

rawDescription: constant string file in python

description: Constant string file in python


code:
from collections import Counter
available_letters = Counter({'a':1,'i':2,'g':3,'n':1,'z':1,'e':3})
for word in ('zazzing', 'grunt', 'zig', 'egg'):
    if Counter(word) - available_letters:
         print word, 'cannot be made with the letters'
    else:
         print word, 'can be made with the letters'

rawDescription: check if letters can be used to build word

description: Check if letters can be used to build word


code:
dir = 'C:\Users\Shankar\Documents\Other'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)

rawDescription: Python - Overwriting Folder If It Already Exists


code:
p = 2
for i in range(10):
    if p <= 0:
        break
    print i+1 , p
    p-=1

rawDescription: Python: Why does this code execute?

description: Python: Why does this code execute


code:
def list_subwindows():
    import gc
    gc.collect()
    print 'Subwindows: ',
    for subwindow in subwindows:
        sw = subwindow()
        if sw:
            print sw,
    print ''

rawDescription: Destroy does not destroy

description: Destroy does not destroy


code:
while teamScore not in range (1,501):
    print "The score is not in the valid range!"
    teamScore=int(raw_input("Please enter the team score (1-500): "))

rawDescription: why can't I validate user input in this way? Python

description: Why can't I validate user input in this way? Python


code:
def count(word, letter):
  count = 0
  for l in word:
    if l == letter:
      count = count + 1
  return count

word = raw_input('Enter a string:')
letter = raw_input('Enter a character:')
print count(word, letter)

rawDescription: function with arguments in python

description: Function with arguments in python


code:
from Tkinter import *

def callback(sv):
    print sv.get()

root = Tk()
sv = StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))
e = Entry(root, textvariable=sv)
e.pack()
root.mainloop()

rawDescription: How do I get an event callback when a Tkinter Entry widget is modified?

description: Get an event callback when a Tkinter Entry widget is modified


code:
from struct import *
f = open('file', 'rb')
print unpack('<i', f.read(4))[0]
f.close()

rawDescription: Read integer from binary file in Python

description: Read integer from binary file in Python


code:
for f,t in A._fields_:
 a = getattr(A,f)
 print a,a.offset,a.size,t

rawDescription: How to get 'type' field descriptor from ctypes Structure or Union field

description: Get 'type' field descriptor from ctypes Structure or Union field


code:
import sys

if old_version:
    print 'hey, upgrade.'
    sys.exit(1)  # A non-zero code indicates failure, on Unix (sys.exit() exits too, but it returns a 0 [=success] exit code)

# main body of whole script

rawDescription: How can I elegantly implement version checking in Python without throwing off indentation?

description: Elegantly implement version checking in Python without throwing off indentation


code:
# myvariables.py
name = 'Steve'

# main.py
import myvariables
print myvariables.name

rawDescription: Changing variables in separate Python files


code:
from Tkinter import *

def super_function():
    out = map(Entry.get, entr)
    fen1.destroy()
    print out

fen1 = Tk()
entr = []
for i in xrange(10):
    entr.append(Entry(fen1))
    entr[i].grid(row=i+1)

Button(fen1, text = 'store everything in a list', command = super_function).grid()

fen1.mainloop()

rawDescription: Python/Tkinter. A button that stores all Entry's in a list


code:
import csv

file  = open('names.csv', "rb") #Open CSV File in Read Mode
reader = csv.reader(file)      #Create reader object which iterates over lines

class Object:                   #Object to store unique data
    def __init__(self, name, produce, amount):
        self.name = name
        self.produce = produce
        self.amount = amount

rownum = 0 #Row Number currently iterating over
list = []  #List to store objects

def checkList(name, produce, amount):

    for object in list:  #Iterate through list
        if object.name == name and object.produce == produce:  #Check if name and produce combination exists
            object.amount += int(amount) #If it does add to amount variable and break out
            return

    newObject = Object(name, produce, int(amount)) #Create a new object with new name, produce, and amount
    list.append(newObject)  #Add to list and break out

for row in reader:  #Iterate through all the rows
    if rownum == 0:  #Store header row seperately to not get confused
        header = row
    else:
        name = row[0]  #Store name
        produce = row[1]  #Store produce
        amount = row[2]  #Store amount

        if len(list) == 0:  #Default case if list = 0
            newObject = Object(name, produce, int(amount))
            list.append(newObject)
        else:  #If not...
            checkList(name, produce, amount)

rownum += 1

for each in list: #Print out result
    print each.name, each.produce, each.amount

file.close() #Close file

rawDescription: Python Sum excel file

description: Python Sum excel file


code:
import pyte

screen = pyte.Screen(80, 24)
stream = pyte.ByteStream()
stream.attach(screen)
stream.feed('xyzzz\by\rfoo')
print ''.join(c.data for c in screen[0]).rstrip()
# prints foozy

rawDescription: How to print terminal formatted output to a variable

description: Print terminal formatted output to a variable


code:
def method():
    cards_string = "8H,3S,4H,7D,5C,JH,AS"
    cards = cards_string.split(',')
    card_numbers_count = {'A':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0, '10':0, 'J':0, 'Q':0, 'K':0}

    for card in cards:
        card_number = card[:-1]
        card_numbers_count[card_number] += 1

    print card_numbers_count

if __name__ == "__main__":
    method()

rawDescription: Python Help: How to find if 3 or 4 strings are the same in a list of 7 strings?


code:
string = "baggage"
count = [0] * 256  # This should be big enough to hold counters for every 8 bit character

for x in string:
    num_value = ord(x)
    count[num_value] += 1

for i in range(256):  # loop through all the possible 8 numbers
    if count[i]:
        print chr(i)*count[i]

# you can join them all back into a string like this
newstr = ''.join(chr(i)*c for i,c in enumerate(count))

rawDescription: sorts in python

description: Sorts in python


rawDescription: how to increment inside tuple in python?

description: Increment inside tuple in python


code:
for word in poem.split():
    print d[word]

rawDescription: How do I match a word in a string with a key in a dict?

description: Match a word in a string with a key in a dict


code:
storage = [] # Empty list to store all the circuits
for n in range(10):
    circuit = TorCircuit(ssl_sock)
    create_circuits(circuit, hops_in_circ)
    print "circuit", circuit
    storage.append(circuit) # Add the circuit to the list

rawDescription: Efficient way to create 10 instances of Tor circuit


code:
try:
  wait.until(lambda driver: driver.find_element_by_partial_link_text('Ticket Request'))
except:
  print "Did not find the element, I can now do what I want"
  #break #if you really want to break out of something

rawDescription: How can I break a loop in Python/selenium when text on a page is not found?

description: Break a loop in Python/selenium when text on a page is not found


code:
for wclass in word_class_dict[most_ambigious_word]:
    for sent in brown_sents:
        if (most_ambigious_word.lower(), wclass) in ((word[0].lower(),word[1]) for word in sent) :
            print most_ambigious_word,"-",wclass
            print " ".join(tuple[0] for tuple in sent)
            break

rawDescription: Simpler way to ignore cases in python?

description: Simpler way to ignore cases in python


code:
for line in f:
  names = line.split()
  print names[0].split(',')[0:3]

rawDescription: How to split a section in a list?

description: Split a section in a list


code:
# these are supposed to overwrite methods
def foo(self):
    return "foo"

def bar(self):
    return "bar"

def variants(base, methods):
    """
        given a base class and list of dicts like [{ foo = <function foo> }]
         returns types T(base) where foo was overwritten
    """
    for d in methods:
        yield type('NodeVariant', (base,), d)

from itertools import combinations
def subdicts(**fulldict):
    """ returns all dicts that are subsets of `fulldict` """
    items = fulldict.items()
    for i in range(len(items)+1):
        for subset in combinations(items, i):
            yield dict(subset)

# a list of method variants
combos = subdicts(slow_method=foo, dumb_method=bar)

# base class
class Node(object):
        def dumb_method(self):
            return "dumb"
        def slow_method(self):
            return "slow"

# use the base and our variants to make a number of types
types = variants(Node, combos)

# instantiate each type and call boths methods on it for demonstration
print [(var.dumb_method(), var.slow_method()) for var
          in (cls() for cls in types)]

# [('dumb', 'slow'), ('dumb', 'foo'), ('bar', 'slow'), ('bar', 'foo')]

rawDescription: Most elegant way to configure a class in Python?


code:
from argparse import ArgumentParser

parser = ArgumentParser()
subparsers = parser.add_subparsers()

install = subparsers.add_parser('install')
install.add_argument('-b')
install.add_argument('-a')
install.set_defaults(subparser='install')

lst = subparsers.add_parser('list')
lst.set_defaults(subparser='list')

update = subparsers.add_parser('update')
update.set_defaults(subparser='update')

print parser.parse_args()

rawDescription: Python's argparse choose one of several optional parameter


code:
class Test(object):
    def __init__(self):
        self.hi()

    def hi(self):
        print "Hi!"

rawDescription: where should I define functions that i use in __init__

description: Where should I define functions that i use in __init__


code:
for key, value in dct.iteritems():
    if 'players' in value:
        for name, player in value['players'].iteritems():
            print name, player

rawDescription: Iterating nested Python dictionaries

description: Iterating nested Python dictionaries


code:
import sympy
a,b,c,d,e,f=sympy.symbols('abcdef')
e=a+b #equation
print e.subs([(a,c),(b,d)])
# c + d
print e.subs([(a,d),(b,f)])
# d + f

rawDescription: how to assign new values to variables in predefined equation?

description: Assign new values to variables in predefined equation


rawDescription: formating string in a particular order

description: Formating string in a particular order


code:
aa = ''
ab = 23
out_str = ''.join(('%6.0f' % var if var!='' else ' '*6) for var in (aa, ab))
print out_str

rawDescription: Python formatted output as float of empty string


code:
for func in (something, something1, something2):
    try:
        func()
    except Keyerror as e:
        print e

rawDescription: a cleaner way to approach try except in python

description: A cleaner way to approach try except in python


code:
def FindUptime(soup):
    link = soup.find(text=re.compile("Uptime"))
    if link:
        myLink = link.parent
        myLink = myLink.next_sibling
        if myLink.string == "Up:":
            myLink = myLink.next_sibling
            myLink = myLink.next_element
        else:
            print "Can't find Up: term"
        uptime = str(myLink.string) # added
        return uptime
    else:
        print "Can't find Uptime"
    return ""

rawDescription: Why does this Python function not release memory after execution?


code:
import threading

def hello():
    t = threading.Timer(10.0, hello)
    t.start()
    print "hello, world"

t = threading.Timer(10.0, hello)
t.start()

rawDescription: Non blocking event scheduling in python

description: Non blocking event scheduling in python


code:
import cookielib, urllib2

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# default User-Agent ('Python-urllib/2.6') will *not* work
opener.addheaders = [
    ('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11'),
    ]

stylesheets = [
    'https://www.idcourts.us/repository/css/id_style.css',
    'https://www.idcourts.us/repository/css/id_print.css',
]

home = opener.open('https://www.idcourts.us/repository/start.do')
print cj
sessid = cj._cookies['www.idcourts.us']['/repository']['JSESSIONID'].value
# Note the +=
opener.addheaders += [
    ('Referer', 'https://www.idcourts.us/repository/start.do'),
    ]
for st in stylesheets:
    # da trick
    opener.open(st+';jsessionid='+sessid)
search = opener.open('https://www.idcourts.us/repository/partySearch.do')
print cj
# perhaps need to keep updating the referer...

rawDescription: Python - urllib2 & cookielib

description: Python - urllib2 & cookielib


code:
#akin to a bucket fill in paint, finds the area instead
def floodcount (x,y,array,value,count=0):
    nrows = len(array)-1          #rows of the image
    ncols = len(array[0])-1       #columns of the image
    if x < 0 or y < 0 or x > nrows or y > ncols:
        return count

    diff = array[x][y] - value
    # the base case, finding a diff more than 0.05 or less than 0 is like finding a boundary
    if (diff < 0.00) or (diff > 0.05):
        return count

    count = count +1
    print 'count1 ',count

    array[x][y] = -5 # so we do no calculate this pixel again
    #print "[",x,",",y,"]"

    count = floodcount (x-1,y,array,value,count)
    count = floodcount (x,y+1,array,value,count)
    count = floodcount (x+1,y,array,value,count)
    count = floodcount (x,y-1,array,value,count)

    count = floodcount (x-1,y-1,array,value,count)
    count = floodcount (x+1,y+1,array,value,count)
    count = floodcount (x+1,y-1,array,value,count)
    count = floodcount (x-1,y+1,array,value,count)

    print 'count2 ',count
    return count

rawDescription: Counter in a Recursive function

description: Counter in a Recursive function


code:
from multiprocessing import Queue, Process, Lock,Value

def do_sum(id, counter, lock):
    MAX = 50
    while counter.value < MAX:

        lock.acquire()
        counter.value += 1

        file = open('mytext.txt','a')
        file.write(str(counter.value))
        file.write("\n")
        file.close()

        lock.release()

def main():

    counter = Value('d', 0.0)
    lock = Lock()

    #f = open('mytext.txt','w')
    #f.close()
    print 'atat'
    q = Queue()
    p1 = Process(target=do_sum, args=(0, counter, lock,) )
    p2 = Process(target=do_sum, args=(1,counter, lock,) )
    p1.start()
    p2.start()
    r1 = q.get()
    r2 = q.get()
    print r1+r2

if __name__=='__main__':
    main()

rawDescription: Use all cpu core in a python script for one process


code:
from random import uniform
learning_rate = 0.0001
N = 100
k, k0 = uniform(-100, 100), uniform(-100, 100)
for _ in range(N):
    x = uniform(-100, 100)
    k = k - learning_rate * x * (k * x - k0 * x)
    print k, k0

rawDescription: Why won't this simple linear regression with gradient descend works?


code:
import json

class Friend(object):
    def __init__(self, name, phone_num):
        self.name = name
        self.phone_num = phone_num

def serialize_friend(obj):
   if isinstance(obj, Friend):
       serial = obj.name + "-" + str(obj.phone_num)
       return serial
   else:
       raise TypeError ("Type not serializable")

paul = Friend("Paul", 1234567890)
john = Friend("John", 1234567890)

friends_dict = {"paul": paul, "john": john}
print json.dumps(friends_dict, default=serialize_friend)

rawDescription: Easiest way to serialize object in a nested dictionary


code:
class main(object): # use new-style classes!
    def __init__(self):
        self.params = {}

class a(main):
    def __init__(self):
        super(a, self).__init__()
        self.params['test'] = "111aa"
        print self.params

class b(main):
    def __init__(self):
        super(b, self).__init__()
        self.params['be'] = "222bbb"
        print self.params

rawDescription: Python: Class and Subclass issue

description: Python: Class and Subclass issue


code:
import csv

class CsvImport():
    resultFormat = "{{location: new google.maps.LatLng({lat},{lng}), weight: {weight}}}"

    def Run(self, filename):
        # Get the formatted rows from CSV file
        rows = self.readCsv(filename)
        print ",\n".join(rows)

    def readCsv(self, fileName):
        with open(fileName, 'rU') as csvfile:
            reader = csv.DictReader(csvfile)
            # Keys may or may not be pulled in with extra space by DictReader()
            # The next line simply creates a small dict of stripped keys to original padded keys
            keys = { key.strip(): key for (key) in reader.fieldnames }
            # Format each row into the final string
            rows = [ self.makeRow(row, keys) for row in reader ]
            return rows;

    def makeRow(self, row, keys):
        # Account for extra spaces in keys
        return self.resultFormat.format(
            lat=row[keys["lat"]].strip(),
            lng = row[keys["lng"]].strip(),
            weight=row[keys["weight"]].strip()
        )

if __name__ == "__main__":
    CsvImport().Run("./Test.csv")

rawDescription: CSV field import formatting issue

description: CSV field import formatting issue


code:
class Ship(object):
    def __init__(self, type):
        self.fixed = define_direction()

        self.row = random_row(board, self)
        self.col = random_col(board, self)
        self.type = type
        print "Type:", str(self.type)

    @property
    def type(self):
        return {
            "Patrol boat": 0,
            "Destroyer": 1,
            "Submarine": 2,
            "Battleship": 3,
            "Aircraft carrier": 4,
        }.get(self._type, 0)

    @type.setter
    def type(self, type):
        self._type = {
            0: "Patrol boat",
            1: "Destroyer",
            2: "Submarine",
            3: "Battleship",
            4: "Aircraft carrier",
        }.get(type, "Patrol boat")

    def __repr__(self):
        return "Ship. Type: " + self._type

rawDescription: Setters and Getters python

description: Setters and Getters python


code:
from weakref import ref

pointers = set()

class Pointer(object):
    def __init__(self, cfun, ptr):
        pointers.add(self)
        self.ref = ref(ptr, self.cleanup)
        self.data = cast(ptr, c_void_p).value # python cast it so smart, but it can't be smarter than this.
        self.cfun = cfun

    def cleanup(self, obj):
        print 'cleanup 0x%x' % self.data
        self.cfun(self.data)
        pointers.remove(self)

def cleanup(cfun, ptr):
    Pointer(cfun, ptr)

rawDescription: How to do cleanup reliably in python?

description: Do cleanup reliably in python


code:
#!/usr/bin/env python

# this is more readable since there are actual names rather than array locations
def order_name(first, second, third, first_name, middle_name, last_name=None):
        if not last_name:
                # if there is no last name we got the last name in middle name (5 arguments)
                last_name = middle_name
        else:
                # if there is a middle name add it to the first name to format as needed
                first_name = "%s %s" % (first_name, middle_name)
        return ("%s, %s" % (last_name, first_name), first, third, second)

with open('studs.txt') as o:
        # this is a more standard way of iterating file rows
        for line in o.readlines():
                # strip line of \n
                line = line.strip()
                print "parsing " + line
                # you can unpack a list to function arguments using the star operator.
                print "ordered: " + str(order_name(*line.split()))

rawDescription: Import a file and putting it inside a tuple in a particular format (python)


code:
dictionary={}
for i in range(201):
    #the loop make the list.__init__() (i.e. the []) being called 200 times
    dictionary[i] = []

dictionary[1].append("foo")
print dictionary

rawDescription: Strange behaviour when appending items to lists inside dictionaries in python


code:
import threading

print "start"
th = threading.Thread(target=tester)
th.daemon = False
print "thread start"
th.start()
print "executing other code"

rawDescription: how to do async in python?

description: Do async in python


code:
import urllib2, os, zipfile
from lxml import etree

def xmlSplitter(data,separator=lambda x: x.startswith('<?xml')):
  buff = []
  for line in data:
    if separator(line):
      if buff:
        yield ''.join(buff)
        buff[:] = []
    buff.append(line)
  yield ''.join(buff)

def first(seq,default=None):
  """Return the first item from sequence, seq or the default(None) value"""
  for item in seq:
    return item
  return default

datasrc = "http://commondatastorage.googleapis.com/patents/grantbib/2011/ipgb20110104_wk01.zip"
filename = datasrc.split('/')[-1]

if not os.path.exists(filename):
  with open(filename,'wb') as file_write:
    r = urllib2.urlopen(datasrc)
    file_write.write(r.read())

zf = zipfile.ZipFile(filename)
xml_file = first([ x for x in zf.namelist() if x.endswith('.xml')])
assert xml_file is not None

count = 0
for item in xmlSplitter(zf.open(xml_file)):
  count += 1
  if count > 10: break
  doc = etree.XML(item)
  docID = "-".join(doc.xpath('//publication-reference/document-id/*/text()'))
  title = first(doc.xpath('//invention-title/text()'))
  assignee = first(doc.xpath('//assignee/addressbook/orgname/text()'))
  print "DocID:    {0}\nTitle:    {1}\nAssignee: {2}\n".format(docID,title,assignee)

rawDescription: Python to parse non-standard XML file

description: Python to parse non-standard XML file


code:
def reverse(string, output = ""):
    if string == "":
        print "winner: ", output
        return output
    output = output + string[-1]
    string = string[:-1]
    return reverse(string, output=output)

rawDescription: Python: My return variable is always None


code:
class Dog:
  def say(self):
    print "hau"

class Cat:
  def say(self):
    print "meow"

pet = Dog()
pet.say() # prints "hau"
another_pet = Cat()
another_pet.say() # prints "meow"

my_pets = [pet, another_pet]
for a_pet in my_pets:
  a_pet.say()

rawDescription: Python - how to implement virtual methods?


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

ignore_f = sys.argv[1]
loci_f = sys.argv[2]

with open(ignore_f) as f:
    ignore = set(x.strip() for x in f)

with open(loci_f) as f:
    for n, line in enumerate(f, start=1):
        if line.split()[0] not in ignore:
            print n

rawDescription: get non-matching line numbers python

description: Get non-matching line numbers python


code:
exit_status = 0
for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])
        if exit_status < 1: exit_status = 1

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])
        exit_status = 2

sys.exit(exit_status)

rawDescription: Using sys.exit in for loops

description: Using sys.exit in for loops


code:
class UDPSocket(DatagramProtocol):
    def __init__(self, mainreactor):
        self._reactor = mainreactor

    def startListenUDP(self):
        try :
            self._reactor.listenUDP(KeepAlive.PORT, self)
        except Exception, e :
            pass

    def startProtocol(self) :
        self.transport.connect(self.host, self.port)

    def stopProtocol(self):
        print "Transport disconnected !"
        self._reactor.callLater(0.1, self.startListenUDP)

    def raise_timeout(self) :
        print "Timeout !"

    def datagramReceived(self, datagram, host):
        try :
            if self.timeout_id.active():
                self.timeout_id.cancel()
        except Exception, e :
            pass
        print datagram

    def sendDatagram(self):
        datagram = "Some Data"
        try :
            self.transport.write(datagram)
            self.timeout_id = self._reactor.callLater(TIMEOUT,
                self.raise_timeout)
        except Exception, e :
            self._reactor.callLater(0.1, self.startListenUDP)

def main():
    protocol = UDPSocket(reactor)
    t = reactor.listenUDP(PORT, protocol)
    l = task.LoopingCall(protocol.sendDatagram)
    l.start(60)
    reactor.run()

#MAIN
if __name__ == '__main__':
    main()

rawDescription: Set a timeout for an UDP socket with Twisted (python)


code:
class TestListCtrl( wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin ) :

    def __init__( self, parent, ID, pos=wx.DefaultPosition,
              size=wx.DefaultSize, style=0 ) :

        wx.ListCtrl.__init__( self, parent, ID, pos, size, style )

        listmix.ListCtrlAutoWidthMixin.__init__( self )
        listmix.CheckListCtrlMixin.__init__(self)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnCheckItem)
        self.Binf(wx.EVT_LIST_COL_CLICK, self.GetSortedOrder)

    def OnCheckItem(self, data, flag):
        print(data, flag)

    def GetSortedOrder(self, event):
        count = self.GetItemCount()
        self.sorted_artists = [self.GetItem(itemId=row, col=0).GetText() for row in xrange(count)]
        print self.sorted_artists

rawDescription: wxPython - How to get what data checked after sorting (listmix.ColumnSorterMixin)

description: WxPython - How to get what data checked after sorting (listmix.ColumnSorterMixin)


code:
import os, sys
import xml.etree.ElementTree as et
from PyQt4 import QtGui, QtCore, uic

class uiControlTest(QtGui.QMainWindow):
    def __init__(self):
        super(uiControlTest, self).__init__()
        self.ui = uic.loadUi('uiControlTest.ui')
        self.ui.show()

        for i in range(0,300):
            wid = animItemWidget()
            wid.label_2.setText('Last edited by chrise @2014.06.21:23:17')
            wid.label.setText('Animation ' + str(i) + '       ')

            wid2 = QtGui.QListWidgetItem()
            wid2.setSizeHint(QtCore.QSize(100, 40))
            self.ui.list.addItem(wid2)
            self.ui.list.setItemWidget(wid2, wid)

        def awesomeButtonPressed():
            print 'awesome!'

class animItemWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(animItemWidget, self).__init__()
        self.horizontalLayout_4 = QtGui.QHBoxLayout(self)
        self.horizontalLayout_4.setSpacing(2)
        self.horizontalLayout_4.setMargin(3)
        self.horizontalLayout_4.setObjectName(QtCore.QString.fromUtf8("horizontalLayout_4"))
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(QtCore.QString.fromUtf8("verticalLayout_2"))
        self.label = QtGui.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(11)
        font.setWeight(75)
        font.setBold(True)
        self.label.setFont(font)
        self.label.setObjectName(QtCore.QString.fromUtf8("label"))
        self.verticalLayout_2.addWidget(self.label)
        self.pixMap02 = QtGui.QLabel(self)
        self.pixMap02.setText(QtCore.QString.fromUtf8(""))
        self.pixMap02.setObjectName(QtCore.QString.fromUtf8("pixMap02"))
        self.verticalLayout_2.addWidget(self.pixMap02)
        self.horizontalLayout_4.addLayout(self.verticalLayout_2)
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(QtCore.QString.fromUtf8("verticalLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setObjectName(QtCore.QString.fromUtf8("horizontalLayout"))
        self.pixMap01 = QtGui.QLabel(self)
        self.pixMap01.setText(QtCore.QString.fromUtf8(""))
        self.pixMap01.setObjectName(QtCore.QString.fromUtf8("pixMap01"))
        self.horizontalLayout.addWidget(self.pixMap01)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.button02 = QtGui.QPushButton(self)
        self.button02.setMaximumSize(QtCore.QSize(24, 24))
        self.button02.setText(QtCore.QString.fromUtf8(""))
        self.button02.setObjectName(QtCore.QString.fromUtf8("button02"))
        self.horizontalLayout.addWidget(self.button02)
        self.button01 = QtGui.QPushButton(self)
        self.button01.setMaximumSize(QtCore.QSize(24, 24))
        self.button01.setText(QtCore.QString.fromUtf8(""))
        self.button01.setObjectName(QtCore.QString.fromUtf8("button01"))
        self.horizontalLayout.addWidget(self.button01)
        self.button04 = QtGui.QPushButton(self)
        self.button04.setMaximumSize(QtCore.QSize(24, 24))
        self.button04.setText(QtCore.QString.fromUtf8(""))
        self.button04.setObjectName(QtCore.QString.fromUtf8("button04"))
        self.horizontalLayout.addWidget(self.button04)
        self.button03 = QtGui.QPushButton(self)
        self.button03.setMaximumSize(QtCore.QSize(24, 24))
        self.button03.setText(QtCore.QString.fromUtf8(""))
        self.button03.setObjectName(QtCore.QString.fromUtf8("button03"))
        self.horizontalLayout.addWidget(self.button03)
        self.button05 = QtGui.QPushButton(self)
        self.button05.setMaximumSize(QtCore.QSize(24, 24))
        self.button05.setText(QtCore.QString.fromUtf8(""))
        self.button05.setObjectName(QtCore.QString.fromUtf8("button05"))
        self.horizontalLayout.addWidget(self.button05)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setObjectName(QtCore.QString.fromUtf8("horizontalLayout_3"))
        self.label_2 = QtGui.QLabel(self)
        self.label_2.setObjectName(QtCore.QString.fromUtf8("label_2"))
        self.horizontalLayout_3.addWidget(self.label_2)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4.addLayout(self.verticalLayout)

        self.connect(self.button02, QtCore.SIGNAL("clicked()"), self.awesome)

    def awesome(self):
        print self.label.text() + ' is awesome!'

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    win = uiControlTest()
    sys.exit(app.exec_())

rawDescription: Populating a QListWidget with custom widgets


code:
class TestView(TemplateView):
   def __init__(self,*args,**kwargs):
       TemplateView.__init__(self,*args,**kwargs)
       print "I am",self.__class__.__name__
       print "My File:",self.template_name

class Whatever(TestView):
   pass

print Whatever()
print TestView()

rawDescription: get class name inside generic view class

description: Get class name inside generic view class


code:
from lxml import html

s = '
The Keyword:The text
'

tree = html.fromstring(s)
text = tree.text_content()
print text

rawDescription: lxml.html extract a string by searching for a keyword

description: Lxml.html extract a string by searching for a keyword


code:
def max_in_range(lst, low, high):
    # If the length of the range is 1, the sole element in the range must be the maximum.
    if low == high:
        return lst[low]

    # break the array into two pieces, lst[low:low+1] / lst[low+1:high+1],
    # find the maximum in each of the pieces
    piece1_max = lst[low]
    piece2_max = max_in_range(lst, low + 1, high)

    # find the maximum of the maxima
    if piece1_max > piece2_max:
        return piece1_max
    else:
        return piece2_max

lst = [112,32,45,71238,9999,45,12,6,3]
print max_in_range(lst, 0, len(lst) - 1)

rawDescription: Recursive max function for a range in java or python


rawDescription: Attribute Error: Nonetype has no attribute 'group'


code:
import sys
import linecache
import random

class Tracer(object):
    def __init__(self):
        self.lastframe = None

    def traceit(self, frame, event, arg):
        if event == "line":
            lineno = frame.f_lineno
            filename = frame.f_globals["__file__"]
            if filename == "<stdin>":
                filename = "traceit.py"
            if (filename.endswith(".pyc") or
                filename.endswith(".pyo")):
                filename = filename[:-1]
            name = frame.f_globals["__name__"]
            line = linecache.getline(filename, lineno)
            if frame.f_back is self.lastframe:
                print "%s:%s:%s: %s" % (name,  lineno,frame.f_code.co_name , line.rstrip())
            else:
                print "%s:%s:%s(%s)" % (name,  lineno,frame.f_code.co_name , str.join(', ', ("%s=%r" % item for item in frame.f_locals.iteritems())))

                print "%s:%s:%s: %s" % (name,  lineno,frame.f_code.co_name , line.rstrip())
                #print frame.f_locals
            self.lastframe = frame.f_back
        return self.traceit

def main():
    print "In main"
    for i in range(5):
        print i, random.randrange(0, 10)
    print "Done."

sys.settrace(Tracer().traceit)
main()

rawDescription: How to use traceit to report function input variables in stack trace

description: Use traceit to report function input variables in stack trace


code:
def word_find(line,words):
    return list(set(line.strip().split()) & set(words))

def main(file,words):
    with open('file') as f:
        for i,x in enumerate(f, start=1):
            common = word_find(x,words)
            if common:
                print i, "".join(common)

if __name__ == '__main__':
    main('file', words)

rawDescription: How to find words in text files with Python

description: Find words in text files with Python


code:
class Circle():
    #Constructor
    def __init__ (self, radius):
        self.__radius = radius
        self.calcArea()
    def calcArea(self, PI = 3.14):
        self.__area = (self.__radius**2) * PI
    #Get Functions
    def GetArea(self):
        return self.__area
    def GetRadius(self):
        return self.__radius
    #Set Functions
    def SetRadius(self, radius):
        self.__radius = radius
        self.calcArea()

class Cylinder():
    #Constructor
    def __init__(self, radius, height):
        self.__height = height
        self.__base = Circle(radius)
        Cylinder.calcVolume(self)
    def calcVolume(self):
        self.__volume = self.__base.GetArea() * self.__height
    #Get Functions
    def GetVolume(self):
        return self.__volume
    def GetBase(self):
        return self.__base
    def GetRadius(self):
        return self.__base.GetRadius()
    def GetHeight(self):
        return self.__height
    #Set Functions
    def SetRadius(self, radius):
        self.__base.SetRadius(radius)
        self.calcVolume()
    def SetHeight(self, height):
        self.__height = height
        self.calcVolume()

class Cone(Cylinder):
    #Constructor
    def __init__ (self, radius, height):
        Cylinder.__init__(self, radius, height)
        Cone.calcVolume(self)
    def calcVolume(self):
        Cylinder.calcVolume(self)
        self.__volume = Cylinder.GetVolume(self) * (1.0/3.0)
    #Get Functions
    def GetVolume(self):
        return self.__volume
    #Set Functions
    def SetRadius(self, radius):
        Cylinder.SetRadius(self, radius)
        self.calcVolume()
    def SetHeight(self, height):
        Cylinder.SetHeight(self, height)
        self.calcVolume()

def main():
        cylinder = Cylinder(5, 6)
        cone = Cone(5, 6)
        circle = Circle(5)
        print cylinder.GetVolume()
        print cone.GetVolume()
        print circle.GetArea()
        cone.SetHeight(7)
        print cone.GetVolume()

main()

rawDescription: Python Polymorphism

description: Python Polymorphism


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

for line in fileinput.input():
    line = line.rstrip("\r\n")    # equiv of chomp
    H = line.split('\t')

    if H[30]=='Good':
        # some operation in col

        # first - what do you get from this?
        print repr(H[22])

        # second - what do you get from this?
        print unicode(H[22], "Latin-1")
    else:
        # do something else
        pass  # only necessary if no code in this section

rawDescription: Simple command line handling equivalent of Perl in Python


code:
#!/usr/bin/python
import os, sys, optparse, time, json
import facebook

##

USER_SESSION_FILE = os.path.expanduser('fb-user.session')
APP_KEY_FILE = os.path.expanduser('fb-app.keys')

##

def main():
    app_keys = open(APP_KEY_FILE).readlines()
    fb_api = facebook.Facebook(api_key=app_keys[0].strip(), secret_key=app_keys[1].strip())
    opts, args = parse_options()
    if args == ['init']:
        init(fb_api)
        return
    session = json.load(open(USER_SESSION_FILE))
    fb_api.uid = session['uid']
    fb_api.secret = session['secret']
    fb_api.session_key = session['session_key']

    fb_api.stream.publish(message="test from PyFacebook")

def init(fb_api):
    fb_api.auth.createToken()

    sys.stdout.write('Opening web page to add application (press ENTER when done)...')
    sys.stdout.flush()
    fb_api.login()
    raw_input()

    sys.stdout.write('Asking for offline access now...')
    sys.stdout.flush()
    fb_api.request_extended_permission('offline_access')
    raw_input()

    sys.stdout.write('And, finally, asking for permission to publish')
    sys.stdout.flush()
    fb_api.request_extended_permission('publish_stream')
    raw_input()

    fb_api.auth.getSession()

    if fb_api.session_key_expires != 0:
        print """We were granted a temporary key; please wait a minute and run `%s init` again.""" % (sys.argv[0],)
    else:
        if not os.path.exists(USER_SESSION_FILE):
            # Only set restrictive permissions when creating the file
            # ourselves.
            open(USER_SESSION_FILE, 'w').close()
            os.chmod(USER_SESSION_FILE, 0600)
        json.dump({
                   'uid': fb_api.uid,
                   'secret': fb_api.secret,
                   'session_key': fb_api.session_key,
                   },
                   open(USER_SESSION_FILE, 'w'),
                   sort_keys=True,
                   indent=4)

def parse_options():
    p = optparse.OptionParser()
    return p.parse_args()

if __name__ == '__main__':
    sys.exit(main())

rawDescription: PyFacebook Infinite Session

description: PyFacebook Infinite Session


code:
import os
import re

def build_files_set(rootdir):
    root_to_subtract = re.compile(r'^.*?' + rootdir + r'[\\/]{0,1}')

    files_set = set()
    for (dirpath, dirnames, filenames) in os.walk(rootdir):
        for filename in filenames + dirnames:
            full_path = os.path.join(dirpath, filename)
            relative_path = root_to_subtract.sub('', full_path, count=1)
            files_set.add(relative_path)

    return files_set

def compare_directories(dir1, dir2):
    files_set1 = build_files_set(dir1)
    files_set2 = build_files_set(dir2)
    return (files_set1 - files_set2, files_set2 - files_set1)

if __name__ == '__main__':
    dir1 = 'old'
    dir2 = 'new'
    in_dir1, in_dir2 = compare_directories(dir1, dir2)

    print '\nFiles only in {}:'.format(dir1)
    for relative_path in in_dir1:
        print '* {0}'.format(relative_path)

    print '\nFiles only in {}:'.format(dir2)
    for relative_path in in_dir2:
        print '* {0}'.format(relative_path)

rawDescription: Compare directories on file/folder names only, printing any differences?


code:
from PIL import Image

try:
    im = Image.open('test.gif')
    f=0
    while True:
        im.seek(f)
        im.save('test_%02d.png' % f)
        f += 1
except EOFError:
    print "Done!"
except:
    print "Some Other Error"

rawDescription: De-animate an animated gif with python

description: De-animate an animated gif with python


code:
from datetime import datetime
from itertools import tee, izip
from functools import partial

def pairwise(iterable):
    """Iterate in pairs

    >>> list(pairwise([0, 1, 2, 3]))
    [(0, 1), (1, 2), (2, 3)]
    """
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def parse_time(time_str, time_format='%H:%M:%S.%f'):
    return datetime.strptime(time_str, time_format)

with open('foo.txt') as f:
    for (time0, flag0), (time1, flag1) in pairwise(line.split() for line in f):
        delta = parse_time(time1) - parse_time(time0)
        print '{} {}-{}'.format(delta.total_seconds(), flag1, flag0)

rawDescription: Python: Find time difference between consecutive lines in a text file


code:
import locale
locale.setlocale(locale.LC_ALL, '') # set to user's locale, not "C"
dec_pt_chr = locale.localeconv()['decimal_point']
if dec_pt_chr == ",":
    list_delimiter = ";"
else:
    list_delimiter = ","
print repr(dec_pt_chr), repr(list_delimiter)
locale.setlocale(locale.LC_ALL, 'French_France.1252')
dec_pt_chr = locale.localeconv()['decimal_point']
if dec_pt_chr == ",":
    list_delimiter = ";"
else:
    list_delimiter = ","
print repr(dec_pt_chr), repr(list_delimiter)

rawDescription: python csv list separator based on regional settings

description: Python csv list separator based on regional settings


code:
tagtable = self.textbuffer.props.tag_table

def foreach_func(tag, data):
    print tag.props.name

tagtable.foreach(foreach_func, None)

rawDescription: How I can names of all tags in gtk.TexTagTable?


code:
import csv, operator
with open('test.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        # row is a list of strings,
        # one item for each column:  row --> [c1, c2, c3, ...]
        print ' * '.join(row),
        # create a list of floats
        row = map(float, row)
        # multiply all items
        result = reduce(operator.mul, row)
        print '= ', result

rawDescription: Assigning each column in a file as a variable to use in a function with a for loop


code:
import requests

def get_repositories(url):
    result = []
    r = requests.get(url=url)
    if 'next' in r.links :
        result += get_repositories(r.links['next']['url'])

    for repository in r.json():
        result.append(repository.get('name'))

    return result

url = "https://api.github.com/users/stackforge/repos"
print get_repositories(url)

rawDescription: How to get all repositories of a specific GitHub user

description: Get all repositories of a specific GitHub user


code:
file=open(filename,"r")
line = file.readline()
students=[]
while line != "":
    splitedline=line.split(" ")
    average=0
    for i in range(len(splitedline)-1) :
        print splitedline[i+1]
        average+=int(splitedline[i+1])
    average=average/(len(splitedline)-1)
    students.append([splitedline[0],average])
    line = file.readline()
print(students)
file.close()

rawDescription: In python, read lines from input file, print each name, compute average


code:
raw = '''your xml string here'''

from xml.etree import ElementTree as ET
root = ET.fromstring(raw)
for address in root.findall('.//address'):
    print address.find('.//areacode').text, address.find('./peraddr').text

rawDescription: fetch child's child value from xml using et tree python

description: Fetch child's child value from xml using et tree python


code:
import re
REPLACEMENTS = dict([('find1', 'replace1'),
                     ('find2', 'replace2'),
                     ('find3', 'replace3')])

def replacer(m):
    return REPLACEMENTS[m.group(0)]

x = 'find1, find2, find3'
r = re.compile('|'.join(REPLACEMENTS.keys()))
print r.sub(replacer, x)

rawDescription: Iterative find/replace from a list of tuples in Python


code:
def scenario2(response):
    print response
    print "Conversation"
    print "Conversation"
    print "Conversation"
    res = sget_choice(s2option_list) # call it once save return value in a variable
    if res == 0: # now you are checking the value from the previous call not calling again
        dead("Conversation")
    else:
        print "Conversation"
        sget_choice2(s2option_list2)

rawDescription: Function using While True not working as expected. Asks for input Twice


code:
from Tkinter import *
from socket import *
port = 7142

on = '02 00 00 00 00'
off = '02 01 00 00 00'

def callback_power_on(data, host):
    if not host:
        print "No host given!"
        return
    print "power on!"
    connection = socket(AF_INET, SOCK_STREAM)
    connection.connect((host, port))
    connection.sendall(add_checksum(data))
    connection.close()

def callback_power_off(data, host):
    if not host:
        print "No host given!"
        return
    print "power off!"
    connection = socket(AF_INET, SOCK_STREAM)
    connection.connect((host, port))
    connection.sendall(add_checksum(data))
    connection.close()

def add_checksum(s):
    result = []
    acc = 0
    for hexcode in s.split():
        code = int(hexcode, 16)
        acc += code
        result.append(chr(code))
    result.append(chr(acc))
    return ''.join(result)

master = Tk()

entered_host = StringVar()
e = Entry(master, textvariable=entered_host)
e.pack()

b = Button(
    master,
    text="Power On",
    command=lambda: callback_power_on(on, entered_host.get()))
b.pack()

c = Button(
    master,
    text="Power Off",
    command=lambda: callback_power_off(off, entered_host.get()))
c.pack()

mainloop()

rawDescription: radio buttons tkinter passing host value

description: Radio buttons tkinter passing host value


code:
from pydoc_data import topics

a = topics.topics['class']
print a

rawDescription: Assign help() to a variable

description: Assign help() to a variable


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

print "matplotlib.__version__   = ", matplotlib.__version__
print "matplotlib.get_backend() = ", matplotlib.get_backend()

# radar green, solid grid lines
plt.rc('grid', color='#316931', linewidth=1, linestyle='-')
plt.rc('xtick', labelsize=15)
plt.rc('ytick', labelsize=15)

# force square figure and square axes looks better for polar, IMO
width, height = matplotlib.rcParams['figure.figsize']
size = min(width, height)
# make a square figure
fig = plt.figure(figsize=(size, size))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')

r = np.arange(0, 3.0, 0.01)
theta = 2*np.pi*r
ax.plot(theta, r, color='#ee8d18', lw=3)
ax.set_rmax(2.0)
plt.grid(True)

ax.set_title("And there was much rejoicing!", fontsize=20)
#This is the line I added:
arr1 = plt.arrow(0, 0.5, 0, 1, alpha = 0.5, width = 0.015,
                 edgecolor = 'black', facecolor = 'green', lw = 2, zorder = 5)

# arrow at 45 degree
arr2 = plt.arrow(45/180.*np.pi, 0.5, 0, 1, alpha = 0.5, width = 0.015,
                 edgecolor = 'black', facecolor = 'green', lw = 2, zorder = 5)

plt.show()

rawDescription: Arrows in Polar Matplotlib Plot

description: Arrows in Polar Matplotlib Plot


code:
import re
print re.sub(r'\bpi\b', 'math.pi', "2*pi")
print re.sub(r'\bpi\b', 'math.pi', "the pink elephant")

rawDescription: Selective python string replacements

description: Selective python string replacements


code:
n = int(raw_input("Enter a five-digit number: "))
digits = [(n /10**i)%10 for i in range(4,-1,-1)]
multiplicand = [5,4,3,2,1]
result = [d*m for d,m in zip(digits, multiplicand)]

print result

rawDescription: How do you multiply each digit of a number by different numbers in python?

description: Multiply each digit of a number by different numbers in python


code:
import sys

def pairings(remainder, partial = None):
    partial = partial or []

    if len(remainder) == 0:
        yield partial

    else:
        for i in xrange(1, len(remainder)):
            pair = [[remainder[0], remainder[i]]]
            r1   = remainder[1:i]
            r2   = remainder[i+1:]
            for p in pairings(r1 + r2, partial + pair):
                yield p

def main():
    n = int(sys.argv[1])
    items = list(range(n))
    for p in pairings(items):
        print p

main()

rawDescription: Python: Generating All Pairwise-Unique Pairings


code:
from urlparse import parse_qs
s = "/?parameter=value&other=some"
print parse_qs(s[2:]) # prints {'other': ['some'], 'parameter': ['value']}

rawDescription: How to parse BaseHTTPRequestHandler.path

description: Parse BaseHTTPRequestHandler.path


code:
for p in paired_tweets[:100]:
    print p[1].encode('utf-8').strip()

rawDescription: Python sorting, limiting the print of result


code:
import random
import nltk
import pandas
import csv
import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from operator import itemgetter
from sklearn.metrics import classification_report
train_setT = [tuple(x) for x in train_set]
test_setT = [tuple(x) for x in test_set]

train_set = np.array([''.join(el[0]) for el in train_setT])
test_set = np.array([''.join(el[0]) for el in test_setT])

y_train = np.array([el[1] for el in train_setT])
y_test = np.array([el[1] for el in test_setT])

vectorizer = TfidfVectorizer(min_df=2,ngram_range=(1, 2), strip_accents='unicode', norm='l2')

X_train = vectorizer.fit_transform(train_set)
X_test = vectorizer.transform(test_set)

nb_classifier = MultinomialNB().fit(X_train, y_train)

y_nb_predicted = nb_classifier.predict(X_test)

print metrics.confusion_matrix(y_test, y_nb_predicted)
print classification_report(y_test, y_nb_predicted)

rawDescription: Optimize NLTK Code To Make Predictions From Text


code:
import sys
import threading

import cmd

def monitor():
    r = redis.Redis(YOURHOST, YOURPORT, YOURPASSWORD, db=0)

    channel = sys.argv[1]
    p = r.pubsub()

    p.subscribe(channel)

    print 'monitoring channel', channel
    for m in p.listen():
        print m['data']

class my_cmd(cmd.Cmd):
    """Simple command processor example."""

    def do_start(self, line):
        my_thread.start()

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print "missing argument! please provide the channel name."
    else:
        my_thread = threading.Thread(target=monitor)
        my_thread.setDaemon(True)

        my_cmd().cmdloop()

rawDescription: Stop python script in infinite loop

description: Stop python script in infinite loop


code:
import re
m1 = re.compile(r'.*?\.txt$')
pattern = 'yourpattern'
m2 = re.compile(r'%s' % (pattern))

for file in filter(m1.search, os.listdir(somedir)):
    if m2.search(open(file,'r').read()):
        print file, 'contains', pattern
    else:
        print file, 'does not contain', pattern

rawDescription: python read files from hard disk and return result depending on the pattern found

description: Python read files from hard disk and return result depending on the pattern found


code:
re_str = r"\?engine=(?P<eng>[\w-]*?)&query=(?P<query>[=\d\+\w-]*?)&subegine=(?P<sub>\w*)\s"
reg = re.compile(re_str)
for line in file:
  m = reg.search(line)
  print "Engine", m.group("eng")
  print "Query", m.group("query")
  print "Sub", m.group("sub")

rawDescription: Parse GET requests in Apache log by arguments


code:
#!/usr/bin/env python

import multiprocessing
import random

def fib(n):
    "Slow fibonacci implementation because why not"
    if n < 2:
        return n
    return fib(n-2) + fib(n-1)

def process_b(queue_in, queue_out):
    print "Starting process B"
    while True:
        j = queue_in.get()
        print "Job: %d" % j["val"]
        j["result"] = fib(j["val"])
        queue_out.put(j)

def process_a(index, pipe_end, queue):
    print "Starting process A"
    value = random.randint(5, 50)
    j = {
        "a_id": index,
        "val": value,
    }

    queue.put(j)
    r = pipe_end.recv()

    print "Process A sent value %d and received: %s" % (value, r)

def main():
    print "Starting main"

    a_pipes = list()
    jobs = multiprocessing.Queue()
    done_jobs = multiprocessing.Queue()

    for i in range(5):
        multiprocessing.Process(target=process_b, args=(jobs, done_jobs,)).start()

    for i in range(10):
        receiver, sender = multiprocessing.Pipe(duplex=False)
        a_pipes.append(sender)
        multiprocessing.Process(target=process_a, args=(i, receiver, jobs)).start()

    while True:
        j = done_jobs.get()
        a_pipes[j["a_id"]].send(j["result"])

if __name__ == "__main__":
    main()

rawDescription: Python: How to return values in a multiprocessing situation?


code:
prev_one = one
one, two, three = pygame.mouse.get_pressed()

if prev_one == 0 and one == 1:
    print 'mouse was clicked this frame'

rawDescription: Referencing previous frames values Python Pygame


code:
from collections import defaultdict

urls = defaultdict(int)

for url in url_source:
    print '{}: {}'.format(url, urls[url])

    # process

    urls[url] += 1

rawDescription: How to count the number of time a unique URL is open in python?

description: Count the number of time a unique URL is open in python


code:
import commands
import glob
from os import path

dir1 = '/home/x/nearline'
dir2 = '/home/x/sge_jobs_output'

for filepath in glob.glob(path.join(dir1, '*.recal.fastq.gz')):
    filename = path.basename(filepath)
    job_id = filename.split('.', 1)[0]

    ## Look for corresponding .txt file
    txt_filepath = path.join(dir2, '%s.txt' % job_id)
    ## Fail early if corresponding .txt file is missing
    if not path.isfile(txt_filepath):
        print('Missing %s for %s' % (txt_filepath, filepath))
        continue

    ## Both exist, process each
    ## This is from your code snippet
    result = commands.getoutput('zcat ' + fullpath1 + ' |wc -l')
    fastq_seq_num = int(result)/4.0

    linelist = open(txt_filepath).readlines()
    lastline = linelist[len(linelist)-1]
    num_seq_processed_sai = lastline.split(']')[1].split()[0]

    if fastq_seq_num == num_seq_processed_sai:
        print "Sequence numbers match (%d : %d)" % (fastq_seq_num, num_seq_processed_sai)
    else:
        print "Sequence numbers do not match (%d : %d)" % (fastq_seq_num, num_seq_processed_sai)

rawDescription: About python loop

description: About python loop


code:
print repr(data)
len(data)
struct.unpack("64B", data)

rawDescription: How to convert string of ints of type unsigned char to an int in python

description: Convert string of ints of type unsigned char to an int in python


code: ur"^[\s\S]*Ticket Price \(including £0\.50 booking fees\)[\s\S]£5\.50[\s\S]*$"

rawDescription: Need fresh eyes on Python assertRegexpMatches


code:
import unittest

# stores 5 user-entered numbers (strings, for now) in a list
def getFiveNums():
    numbers = []
    print "Howdy. Please enter five numbers, hit <enter> after each one"
    for i in range(5):
        newNum = input("Please type in a number:")
        numbers.append(newNum)
    return numbers

def mock_input(dummy_prompt):
    return 1

class TestGetFiveNums(unittest.TestCase):
    def setUp(self):
        self.saved_input = __builtins__.input
        __builtins__.input = mock_input

    def tearDown(self):
        __builtins__.input = self.saved_input

    def testGetFiveNums(self):
        printed_lines = getFiveNums()
        self.assertEquals(printed_lines, [1, 1, 1, 1, 1])

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

rawDescription: Doctesting functions that receive and display user input - Python (tearing my hair out)


code:
from dulwich import repo, diff_tree

fn = 'a.txt'
r = repo.Repo('.')
prev = None
walker = r.get_graph_walker()
cset = walker.next()
while cset is not None:

    commit = r.get_object(cset)
    if prev is None:
        prev = commit.tree
        cset = walker.next()
        continue

    res = None
    delta = diff_tree.tree_changes(r, prev, commit.tree)
    for x in diff_tree.tree_changes(r, prev, commit.tree):
        if x.new.path == fn:
            res = cset
            break

    if res:
        break

    prev = commit.tree
    cset = walker.next()

print fn, res

rawDescription: How to get last commit for specified file with python(dulwich)?

description: Get last commit for specified file with python(dulwich)


code:
li = soup.find('li', {'class': 'text'})
children = li.findChildren()
for child in children:
    print child

rawDescription: How to find children of nodes using Beautiful Soup

description: Find children of nodes using Beautiful Soup


code:
# Get folder path containing text files
file_list = glob.glob(source_dir + '/*.TXT')
data = []
for file_path in file_list:
    data.append(
        np.genfromtxt(file_path, delimiter=',', skip_header=3, skip_footer=18))
# now you can access it outside the "for loop..."
for d in data:
    print d

rawDescription: Pythonic way to import data from multiple files into an array


code:
import datetime
import bottle
from bottle import route, static_file, get, post, error, request, template, redirect, response, hook

# unchanged from OP
@route('/index.html')
def index_handler():
    return '
Hello, world!
'

# unchanged from OP
def log_after_request():
    try:
        length = response.content_length
    except:
        try:
            length = len(response.body)
        except:
            length = '???'
    print 'MYLOG:', '{ip} - - [{time}] "{method} {uri} {protocol}" {status} {length}'.format(
        ip=request.environ.get('REMOTE_ADDR'),
        time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        method=request.environ.get('REQUEST_METHOD'),
        uri=request.environ.get('REQUEST_URI'),
        protocol=request.environ.get('SERVER_PROTOCOL'),
        status=response.status_code,
        length=length,
    )

# code I've added begins here
class AccessLogMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, e, h):
        # call bottle and store the return value
        ret_val = self.app(e, h)

        # log the request
        log_after_request()

        # return bottle's return value
        return ret_val

app = bottle.app()
logged_app = AccessLogMiddleware(app)
bottle.run(host='0.0.0.0', port='8000', app=logged_app)

rawDescription: logging response content length using bottle and cherrypy

description: Logging response content length using bottle and cherrypy


code:
srcpat = '/folderA/filename*.log'
dstdir = '/folderB'
for srcfile in glob.iglob(srcpat):
   if not os.path.isfile(srcfile): continue

   dstfile = os.path.join(dstdir, os.path.basename(srcfile))
   with open(srcfile) as src, open(dstfile, 'w') as dst:
       for line in src:
           parts = line.split()
           status = parts[8]  # value of 8th position in the log file
           if not status.isdigit():
               print " Not A Number :", status
               dst.write(status)  # Or print >>dst, status if you want newline

rawDescription: How to take input of a directory

description: Take input of a directory


code:
from sqlalchemy.sql import or_
query = Session.query(MyTable)
query = query.filter(or_(MyTable.info == None, ~MyTable.info.contains(['Recalled'])))
print len(query.all())

rawDescription: SQLAlchemy filter for rows that do not contain value in an array column


code:
import argparse

def a(arg1, arg2, **kwargs):
    print arg1
    print arg2

if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.set_defaults(method = a)
        parser.add_argument('arg1', type = str)
        parser.add_argument('arg2', type = str)

        arguments = parser.parse_args()
        arguments.method(**vars(arguments))

rawDescription: Python - Pass Arguments to Different Methods from Argparse


code:
import wx
def onText1(event):
    print "First Text1!"
    event.Skip()

def onText2(event):
    print "Then Text2!"

app = wx.App()

frame = wx.Frame(None, -1, '')
box = wx.StaticBox(frame, -1, "")
sizer = wx.StaticBoxSizer(box, orient=wx.VERTICAL)
text0 = wx.StaticText(frame,label="1st Item")
text0_input = wx.TextCtrl(frame, wx.ID_ANY, size=(345,25))
text0_input.SetValue("")
sizer.Add(text0, wx.ALIGN_LEFT|wx.ALL, border=10)
sizer.Add(text0_input, wx.ALIGN_LEFT|wx.ALL, border=10)
text0_input.Bind(wx.EVT_TEXT, onText2)
text0_input.Bind(wx.EVT_TEXT, onText1)

main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(sizer)
frame.SetSizer(main_sizer)

frame.Centre()
frame.Show()
text0_input.SetFocus()
window_focus = True

app.MainLoop()

rawDescription: binding one widget to EVT_TEXT event to trigger more than one event handlers in wxpython

description: Binding one widget to EVT_TEXT event to trigger more than one event handlers in wxpython


code:
#!/usr/bin/env python

def get_all(D, k):
    yield k
    for ii in D.get(k, []):
        for jj in get_all(D, ii):
            yield jj

A = { 'a' : dict(b=1, c=1),
    'c' : dict(d=1),
    'd' : dict(e=1,f=1,g=1),
    'h' : dict(j=1)
    }

for ii in get_all(A,'a'):
    print ii

rawDescription: Topological sort, recursive, using generators


code:
def caller(func, *args, **kwargs):
    return func(*args, **kwargs)
def hello(a, b, c):
    print a, b, c
caller(hello, 1, b=5, c=7)

rawDescription: Implementing a 'function-calling function'


code:
class Body(object):
    """Representation of a geometric body.

      :ivar surface: a :class:`example.Surface` instance

      Usage example:

      >>> mybody = Body()
      >>> mybody.surface.get_surface_area()
      >>> 4

      Another way of doing it:

      >>> mybody = Body()
      >>> mysurface = Surface(mybody)
      >>> mysurface.get_surface_area()
      >>> 4

    """
    def __init__(self):
        self.surface = Surface(self)

class Surface(object):
    """Representation of a geometric surface.

     :ivar body: The supplied :class:`example.Body` instance

    """
    def __init__(self, body):
        self.body = body

    def get_surface_area(self):
        """ Calculate surface area of the body """
        print 4

rawDescription: How do I document "sub-classes" using sphinx and autodoc?

description: Document "sub-classes" using sphinx and autodoc


code:
def printModel(model):
    columns = [m.key for m in model.__table__.columns]
    for x in columns:
        print x, getattr(model, x)

rawDescription: Print column titles and values in SqlAlchemy


code:
import glob
strings = ['string1', 'string2']
for file in glob.glob('*.csv'):
    with open(file) as f:
        contents = f.read()
    for string in strings:
        if string in contents:
            print file
            break

rawDescription: Finding many strings in directory

description: Finding many strings in directory


code:
import random
import time

rock = 1
paper = 2
scissors = 3

names = { rock: "Rock" , paper: "Paper" , scissors: "Scissors" }
rules = { rock: scissors , paper :rock , scissors: paper }

player_score = 0
computer_score = 0

def start():

    print "Let's play a game of rock paper and scissors"
    while game():
        pass
    scores()

def game():
    player = move()
    computer = random.randint(1,3)
    result(player, computer)
    return play_again()

def move():
    while True:
        print #this is not how you could get int input in Python
        player = raw_int("Rock = 1\nPaper = 2\nScissors =3\nMake a move: ")

        try:
            player = int(player)
            if player in (1,2,3):
                return player
        except ValueError:
            pass
        print "Oops! I didn't understand that. Please enter 1,2 or 3." #note the indentation here

def result(player, computer):
    print "1..."
    time.sleep(1)
    print "2..."
    time.sleep(1)
    print "3..."
    time.sleep(0.5)

    print "Computer threw {0)!".format(names[computer])

    global player_score,computer_score

    if player == computer:
        print "Tie game."

    else:
        if rules[player] == computer:
            print "Your victory has been assured."
            player_score += 1

        else:
            print" The computer laughs as you realise you have been defeated."
            computer_score += 1

def play_again(): #again, indentation
    #and this is not how you could get string input in Python
    answer = raw_input("Would you like to play again? y/n: ")
    if answer in ("Y", "Y" , "yes" , "Yes" , "Of course!"):
        return answer
    else:
        print "Thank you very much for playing our game.See your next time!"

def scores(): #note the indentation here
    global player_score,computer_score
    print "High Scores"
    print "Player:" , player_score
    print "Computer:", computer_score

if __name__ == '__main__': #note the underscores here
  start()

rawDescription: Python2.7: What is wrong with this program? It runs but the weird traceback error


Python loop for :1/30 + 2/29 + 3/28


code:
import numpy as np

a = np.array([1,2,3])
b = np.array([None, a, a, a])[1:]

print b.dtype, b[0].dtype, b[1].dtype
# object int32 int32

rawDescription: Numpy object array of numerical arrays

description: Numpy object array of numerical arrays


code:
import hashlib
hash_object = hashlib.sha1(b'HelWorld')
pbHash = hash_object.hexdigest()
length = len(pbHash.decode("hex"))
print length

rawDescription: how to create a sha1 hash in python

description: Create a sha1 hash in python


code:
l = ['Bafra Pide','Bafra Pide','Deneme Restoran','Bafra Pide']
s = set(l)
for i in s:
   print i

rawDescription: how to use distinct() on filtered queries in Django?

description: Use distinct() on filtered queries in Django


code:
import sys

def foobar():
    print sys._getframe().f_code.co_name

rawDescription: Equivalent of __func__ (from C) in Python


code:
L = []
for student in range(0,10):
    x = (raw_input("Enter grade here: ")).lower()
    L.append(x)

d = dict((x,L.count(x)) for x in set(L))
for k,v in d.iteritems():
    print "Count for {}'s : {}".format(k.capitalize(), v)

rawDescription: Python, can't figure out how to save looped variable


code:
class Color(object):
    def __init__(self,color):
        self.color = color
        r,g,b = self.color
        self.r = r
        self.g = g
        self.b = b

    def __str__(self):
        return "(red: {}, green: {}, blue: {})".format(self.r, self.g, self.b)

if __name__=='__main__':
    color = Color ((150, 100, 55))
    print color

rawDescription: How to create a class that will store a tuple of (r,g,b)?

description: Create a class that will store a tuple of (r,g,b)


code:
with open('filename.txt') as file:
    contents = file.read()
    print repr(contents)

rawDescription: Print data from a text file into a raw format?


code:
spells = ['fireball', 'iceball', 'lightning bolt', 'firestorm', 'heal', 'paralyze']
equipped_spells = ['fireball', 'iceball']

print equipped_spells
while True:
    inp = raw_input("Type the name of a spell you want to use.: ").lower()
    lst = [x for x in spells if x.startswith(inp)]
    if len(lst) == 0:
        print "No such spell"
    elif len(lst) == 1:
        spell = lst[0]
        break
    else:
        print "Which of", lst, "do you mean?"

print "You picked", spell

rawDescription: Allowing raw_input to use items in a list as an answer


code:
import subprocess

from pyVim import connect

proc = subprocess.Popen(["sudo dmidecode|grep UUID|awk '{print $2}'"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
uuid = out[:-1]

SI = None
SI = connect.SmartConnect(host=ARGS.host,
                          user=ARGS.user,
                          pwd=ARGS.password,
                          port=ARGS.port)

VM = SI.content.searchIndex.FindByUuid(None, uuid,
                                       True,
                                       False)

HOST = VM.runtime.host

print "Host name: {}".format(HOST.name)

rawDescription: How to get the name and IP of the host of a VMware virtual machine?

description: Get the name and IP of the host of a VMware virtual machine


code:
def noisy(n):
  for i in range(n):
    print i
    yield i

def test(*args):
  print "in test"
  for arg in args:
    print arg

test(*noisy(4))

rawDescription: Are *parameters calls lazy?

description: Are *parameters calls lazy


code:
import time
from random import random
from functools import partial
from multiprocessing import Pool, current_process

def parallel(m, G):
    D = 0
    for i in xrange(G):
        D += random()
    # uncomment to give the other workers more chances to run
    # time.sleep(.001)
    return (current_process().name, time.time()), 1 * (D < 1)

# don't deny the existence of Windows
if __name__ == '__main__':
    pool = Pool()
    TOTAL = 0
    proc_times = {}
    for i in xrange(5):

        # times is a list of proc_name:timestamp pairs
        times, results = zip(*pool.map(partial(parallel, G=2), xrange(100)))
        TOTAL += sum(results)

        # process_times_loc is guaranteed to hold the last timestamp
        # for each proc_name, see the doc on dict
        proc_times_loc = dict(times)
        print 'local completion times:', proc_times_loc

        proc_times.update(proc_times_loc)

    print TOTAL
    print 'total completion times:', proc_times

rawDescription: How to get end of process time per processor using "pool" in Python?

description: Get end of process time per processor using "pool" in Python


rawDescription: Group a string into 3s in a loop (python)


code:
s = '0xFFFF00'
i = int(s, 16)
print i

rawDescription: convert string rep of hexadecimal into actual hexadecimal

description: Convert string rep of hexadecimal into actual hexadecimal


code:
import sys
import telnetlib

tn = telnetlib.Telnet("xxxxxxxx")

TELNET_PROMPT="xxxxxxxxxx"
TIMEOUT=1
tn.write("xxxxxxx"+"\n")
tn.write("xxxxxxx"+"\n")
print tn.read_until(TELNET_PROMPT, TIMEOUT)
tn.write("term len 0" + "\n")
print tn.read_until(TELNET_PROMPT, TIMEOUT)
tn.write("show version" + "\n")
print tn.read_until(TELNET_PROMPT, TIMEOUT)
tn.write("exit"+"\n")
tn.close()

rawDescription: Telnet to router in Python Script

description: Telnet to router in Python Script


code:
import subprocess

p = subprocess.Popen((["python", "script.py"]), stdout=subprocess.PIPE)

while p.poll() is None:
    (stdout, stderr) = p.communicate()
    print stdout

rawDescription: Python: Check when a cmd command completes its job


code:
import pygame
from pygame.locals import *
import math
import numpy

#----------------------------------------------------------------------
# functions
#----------------------------------------------------------------------

def SineWave(freq=1000, volume=16000, length=1):

    num_steps = length * SAMPLE_RATE
    s = []

    for n in range(num_steps):
        value = int(math.sin(n * freq * (6.28318/SAMPLE_RATE) * length) * volume)
        s.append( [value, value] )

    return numpy.array(s)

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

def SquareWave(freq=1000, volume=100000, length=1):

    num_steps = length * SAMPLE_RATE
    s = []

    length_of_plateau = int( SAMPLE_RATE / (2*freq) )

    print num_steps, length_of_plateau

    counter = 0
    state = 1

    for n in range(num_steps):

        value = state * volume

        s.append( [value, value] )

        counter += 1

        if counter == length_of_plateau:
            counter = 0
            state *= -1

    return numpy.array(s)

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

def MakeSound(arr):
    return pygame.sndarray.make_sound(arr)

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

def MakeSquareWave(freq=1000):
    return MakeSound(SquareWave(freq))

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

def MakeSineWave(freq=1000):
    return MakeSound(SineWave(freq))

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

def DrawSineWave():

    # sine wave

    yPos = -1 * math.sin(step) * AMPLITUDE
    posRecord['sin'].append((int(xPos), int(yPos) + WIN_CENTERY))
    if showSine:
        # draw the sine ball and label
        pygame.draw.circle(screen, RED, (int(xPos), int(yPos) + WIN_CENTERY), 10)
        sinLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)
        screen.blit(sinLabelSurf, sinLabelRect)

    # draw the waves from the previously recorded ball positions
    if showSine:
        for x, y in posRecord['sin']:
            pygame.draw.circle(screen, DARKRED, (x, y), 4)

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

def DrawSquareWave():

    # square wave

    posRecord['square'].append((int(xPos), int(yPosSquare) + WIN_CENTERY))
    if showSquare:
        # draw the square ball and label
        pygame.draw.circle(screen, GREEN, (int(xPos), int(yPosSquare) + WIN_CENTERY), 10)
        squareLabelRect.center = (int(xPos), int(yPosSquare) + WIN_CENTERY + 20)
        screen.blit(squareLabelSurf, squareLabelRect)

    # draw the waves from the previously recorded ball positions
    if showSquare:
        for x, y in posRecord['square']:
            pygame.draw.circle(screen, BLUE, (x, y), 4)

#----------------------------------------------------------------------
# constants - (uppercase name)
#----------------------------------------------------------------------

# set up a bunch of constants
WHITE      = (255, 255, 255)
DARKRED    = (128,   0,   0)
RED        = (255,   0,   0)
BLACK      = (  0,   0,   0)
GREEN      = (  0, 255,   0)
BLUE       = (  0,   0, 255)

BGCOLOR = WHITE

WINDOWWIDTH = 1200 # width of the program's window, in pixels
WINDOWHEIGHT = 720 # height in pixels

WIN_CENTERX = int(WINDOWWIDTH / 2) # the midpoint for the width of the window
WIN_CENTERY = int(WINDOWHEIGHT / 2) # the midpoint for the height of the window

FPS = 160 # frames per second to run at

AMPLITUDE = 80 # how many pixels tall the waves with rise/fall.

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

SAMPLE_RATE = 22050 ## This many array entries == 1 second of sound.

SINE_WAVE_TYPE = 'Sine'
SQUARE_WAVE_TYPE = 'Square'

#----------------------------------------------------------------------
# main program
#----------------------------------------------------------------------

#-------------------
# variables (which don't depend on pygame)
#-------------------

sound_types = {SINE_WAVE_TYPE:SQUARE_WAVE_TYPE, SQUARE_WAVE_TYPE:SINE_WAVE_TYPE}

current_type = SINE_WAVE_TYPE
current_played = { 'z': None, 'c': None }
current_drawn = None

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

# variables that track visibility modes
showSine = True
showSquare = True

xPos = 0
step = 0 # the current input f

posRecord = {'sin': [], 'square': []} # keeps track of the ball positions for drawing the waves

yPosSquare = AMPLITUDE # starting position

#-------------------
# start program
#-------------------

pygame.init()

screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('Nibbles!')

# making text Surface and Rect objects for various labels

pygame.display.set_caption('Trig Waves')
fontObj = pygame.font.Font('freesansbold.ttf', 16)

### HERE
squareLabelSurf = fontObj.render('square', True, BLUE, BGCOLOR)
squareLabelRect = squareLabelSurf.get_rect()

sinLabelSurf = fontObj.render('sine', True, RED, BGCOLOR)
sinLabelRect = sinLabelSurf.get_rect()

#-------------------
# mainloop
#-------------------

fps_clock = pygame.time.Clock()

_running = True

while _running:

    #-------------------
    # events
    #-------------------

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            _running = False

        # some keys don't depend on `current_type`

        elif event.type == KEYDOWN:

            if event.key == K_ESCAPE:
                _running = False

            if event.key == K_RETURN:
                current_type = sound_types[current_type]  #Toggle
                print 'new type:', current_type

        # some keys depend on `current_type`

        if current_type == SINE_WAVE_TYPE:

            if event.type == KEYDOWN:

                #lower notes DOWN

                if event.key == K_z:
                    print current_type, 130.81
                    current_played['z'] = MakeSineWave(130.81)
                    current_played['z'].play()
                    current_drawn = DrawSineWave

                elif event.key == K_c:
                    print current_type, 180.81
                    current_played['c'] = MakeSineWave(180.81)
                    current_played['c'].play()
                    current_drawn = DrawSineWave

            elif event.type == KEYUP:

                #lower notes UP

                if event.key == K_z:
                    current_played['z'].fadeout(350)
                    current_drawn = None

                    #sine - reset data
                    xPos = 0
                    posRecord['sin'] = []
                    step = 0

                elif event.key == K_c:
                    current_played['c'].fadeout(350)
                    current_drawn = None

                    #sine - reset data
                    xPos = 0
                    posRecord['sin'] = []
                    step = 0

        elif current_type == SQUARE_WAVE_TYPE:

            if event.type == KEYDOWN:

                #lower notes DOWN

                if event.key == K_z:
                    print current_type, 130.81
                    current_played['z'] = MakeSquareWave(130.81)
                    current_played['z'].play()
                    current_drawn = DrawSquareWave

                elif event.key == K_c:
                    print current_type, 180.81
                    current_played['c'] = MakeSquareWave(180.81)
                    current_played['c'].play()
                    current_drawn = DrawSquareWave

            elif event.type == KEYUP:

                #lower notes UP

                if event.key == K_z:
                    current_played['z'].fadeout(350)
                    current_drawn = None

                    # square - reset data
                    xPos = 0
                    yPosSquare = AMPLITUDE
                    posRecord['square'] = []
                    step = 0

                elif event.key == K_c:
                    current_played['c'].fadeout(350)
                    current_drawn = None

                    # square - reset data
                    xPos = 0
                    yPosSquare = AMPLITUDE
                    posRecord['square'] = []
                    step = 0

    #-------------------
    # draws
    #-------------------

    # fill the screen to draw from a blank state
    screen.fill(BGCOLOR)

    if current_drawn:
        current_drawn()

    pygame.display.update()

    #-------------------
    # moves
    #-------------------

    if current_drawn:
        xPos += 1.0 #0.5

        if xPos > WINDOWWIDTH:
            #sine ### HERE
            xPos = 0
            posRecord['sin'] = []
            step = 0

            # square ### HERE
            yPosSquare = AMPLITUDE
            posRecord['square'] = []
        else:
            #sine ### HERE
            step += 0.008
            #step %= 2 * math.pi

            # square ### HERE
            # jump top and bottom every 100 pixels
            if xPos % 100 == 0:
                yPosSquare *= -1
                # add vertical line
                for x in range(-AMPLITUDE, AMPLITUDE):
                    posRecord['square'].append((int(xPos), int(x) + WIN_CENTERY))

    #-------------------
    # FPS
    #-------------------

    fps_clock.tick(FPS)

#-------------------
# end program
#-------------------

pygame.quit()

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

rawDescription: pygame both audial and visual sine wave

description: Pygame both audial and visual sine wave


code:
print "Enter 100 words:"
words = [] # create a list
for x in range(100): # loop through all the numbers from 0 to 100
  words.append(raw_input("Word {}".format(x + 1))) # ask for the word,
                                                   # then add it to the list

rawDescription: how to input many times in python?

description: Input many times in python


code:
class mydict(dict):
    def __iter__(self):
        return iter(sorted(super(mydict, self).__iter__()))

d = mydict({2: 1, 4: 5, 3: 7, 1: 2})
dit = iter(d)
print next(dit)  # 1
print next(dit)  # 2
print next(dit)  # 3
print next(dit)  # 4
print next(dit)  # StopIteration

rawDescription: Design a subclass of dict whose iterator would return its keys in sorted order


code:
with open('OpenDR Data.txt', 'r') as fp:
    for idx, line in enumerate(fp, 1):
        if idx % 10 in [7,8,9,0]:
            matAll = line.split()
            MatList = map(float, matAll)
            MatArray1D = np.array(MatList)
            print MatArray1D

rawDescription: Python use for loop to read specific multiply lines from txt files


code:
def divis_through_twenty(n):
  return any(n % x for x in xrange(20,1,-1))

x = 20
while divis_through_twenty(x):
  x += 20

print x

rawDescription: How can I make this Project Euler solution execute in Python at the same speed as Java?

description: Make this Project Euler solution execute in Python at the same speed as Java


rawDescription: All sets length 2 from numpy array

description: All sets length 2 from numpy array


code:
liste = []

dit = {}
file = open('ip.txt','r')

file = file.readlines()

for line in file:
        liste.append(line.strip())

for i, element in enumerate(liste, 1):
        if element in dit:
                dit[element][0] += 1
                dit[element][1] =  i
        else:
                dit[element] = [1,i]

for key,value in dit.items():
        print "%s occurs %d times, last occurence at line %d" % (key, value[0], value[1])

rawDescription: Python find last occurence in a file

description: Python find last occurence in a file


code:
from numpy import array

values = array([(x % 2) for x in range(12)], dtype=bool).reshape((4,3))

weights = array(range(1, 4))

answers = values.dot(weights)
print answers
# output: [ 2 4 2 4 ]

rawDescription: Efficiently sum a small numpy array, broadcast across a ginormous numpy array?


code: print '# \'// Warning: Render view: Selected region is too small // \r\ndefaultPointLight(1, 1,1,1, 0, 0, 0,0,0, 1);\r\nrenderWindowRender redoPreviousRender renderView;\r\n'.replace(r'\r\n', '\n')

rawDescription: email RenderLog with nice formatting

description: Email RenderLog with nice formatting


code:
import random

mylist = [1, 2, 3]
keep_playing = True

while keep_playing:

    # Get legal guess
    print "There are 3 cups, and 1 egg hidden underneath."
    print "Which cup do you think the egg is under?"
    talong_c = raw_input("1 - 2 - 3? ")
    while talong_c not in "123":
        talong_c = raw_input("1 - 2 - 3? ")

    true_cup = random.choice(mylist)
    if int(talong_c) == true_cup:
        print "\nYou win!"
    else:
        print "\nYou lose!  It was under cup", true_cup

    print "Would you like to play again?"
    talong_c1 = raw_input("> ")
    keep_playing = talong_c1.lower() == 'y'

rawDescription: Random ball under cup game in Python

description: Random ball under cup game in Python


rawDescription: merge two lists python

description: Merge two lists python


code:
fileName = "input.txt"
with open(fileName,"r") as file:
    for line in file:
        for word in line.split():
            if  word != '#':
                print word
            else:
                print "End of File"

rawDescription: How to remove python white spaces

description: Remove python white spaces


code:
from scrapy.spider import BaseSpider
from scrapy.http import Request

class MySpider(BaseSpider):
    name = 'wikipedia'
    allowed_domains = ['en.wikipedia.org']
    start_urls = [
        'http://en.wikipedia.org/wiki/Main_Page',
    ]

    def parse(self, response):
        print "I'm at wikipedia"
        request = Request(url="https://google.com",
                          callback=self.parse_google,
                          dont_filter=True)
        yield request

    def parse_google(self, response):
        print "I'm at google"

rawDescription: Scrapy: Creating a Request to a site that is not in allowed_domains


code:
f = s.makefile()
for line in f:
    print 'Read:', line
    command, arguments = line.rstrip().split(' ', 2)
    if command == 'PING':
         f.write('PONG ' + arguments + '\r\n')

rawDescription: Python IRC bot disconnecting after 3 pings


code:
class DockingFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="Last Hand",
                          style=wx.CAPTION  | wx.FRAME_FLOAT_ON_PARENT)

        parent.Bind(wx.EVT_MOVE, self.OnParentMove)
        parent.Bind(wx.EVT_SHOW, self.OnParentShow)

    def SnapToParent(self):
        print "*Snapping to parent"
        pr = positioning.position(
            self.Rect,
            my='right_top', at='left_top', of=self.Parent.Rect)
        self.Move(pr.top_left)

    def OnParentMove(self, moveEvent):
        moveEvent.Skip()
        self.SnapToParent()

    def OnParentShow(self, event):
        event.Skip()
        print "Parent %s" % ("Hide", "Show")[event.GetShow()]
        self.Show(event.GetShow())

rawDescription: wxPython: Trying to make a docking window, binding parent EVT_ACTIVATE prevents parent resizing

description: WxPython: Trying to make a docking window, binding parent EVT_ACTIVATE prevents parent resizing


code:
from itertools import groupby

def ranger(values, range_size):
    def keyfunc(n):
        key = n/(range_size+1) + 1
        print '{} in {}'.format(n, key)
        return key

    return [len(list(g)) for k, g in groupby(values, key=keyfunc)]

myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print ranger(myset, 10)
print ranger(myset, 15)

rawDescription: Grouping list of integers in a range into chunks


code:
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Table
data = {'true': True, 'false': False, 'one': 1, 'zero': 0}
table = Table.create('q32109154-test1', schema=[HashKey('hkey')])
data['hkey'] = 'test1'
table.put_item(data=data)
result = table.get_item(hkey='test1')
print [(k, v) for k, v in result.items()]
table = Table.create('q32109154-test2', schema=[HashKey('hkey')])
data['hkey'] = 'test2'
table.use_boolean()
table.put_item(data=data)
result = table.get_item(hkey='test2')
print [(k, v) for k, v in result.items()]

rawDescription: Boolean Converted To decimal.Decimal object in Boto DynamoDB Requests


code:
for i in range(10, -1, -1):
    print i

rawDescription: Python for loop equavalent to C

description: Python for loop equavalent to C


code:
from win32com.client import Dispatch
import os

dir = 'C:\Users\<user name>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup'
name = 'shortcut.lnk'
path = os.path.join(dir, name)
target = '<your exe>'
wDir = '<working directory>'
icon = '<file to take the icon from, can be your exe>'

shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()

rawDescription: Make cx_Freeze to add app to startups

description: Make cx_Freeze to add app to startups


code:
word = 'alfalfa'

location = word.find('a')
if location > -1:
    print 'found "a", count this'

while location > -1:
    location = word.find('a', location + 1)
    if location > -1:
        print 'found another "a", count this'

rawDescription: How to seperate vowels and constants when a user inputs a word Python

description: Seperate vowels and constants when a user inputs a word Python


code:
import subprocess
threshold = 10
child = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE)
output = child.communicate()[0].strip().split("\n")
for x in output[1:]:
    if int(x.split()[-2][:-1]) >= threshold:
        print x

rawDescription: Python script to verify disk space output from Linux


code:
from BeautifulSoup import BeautifulSoup

s = """
   1. Content of the paragraph  in italic  but not  strong  ignore.
"""
soup = BeautifulSoup(s, convertEntities=BeautifulSoup.HTML_ENTITIES)

for p in soup.findAll('p'):
    for a in p.findAll('a'):
        a.extract()
    print ''.join(p.findAll(text=True))

rawDescription: Extracting tag content based on content value using BeautifulSoup


code:
import wmi
import time

time_to_sleep  = 30

c = wmi.WMI()
process_info = {}

while True:
    for process in c.Win32_Process ():
            id = process.ProcessID
            for p in c.Win32_PerfRawData_PerfProc_Process (IDProcess=id):
                n1, d1 = long (p.PercentProcessorTime), long (p.Timestamp_Sys100NS)
                n0, d0 = process_info.get (id, (0, 0))
                try:
                    percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
                except ZeroDivisionError:
                    percent_processor_time = 0.0
                process_info[id] = (n1, d1)
                print id, process.Caption, str(percent_processor_time)
    time.sleep(time_to_sleep)

rawDescription: WMI Unexpected COM Error -2147352567 when calling recursive function


code:
from django.db.models import get_models, signals
from django.conf import settings
from django.utils.translation import ugettext_noop as _

if "notification" in settings.INSTALLED_APPS:
    from notification import models as notification

    def create_notice_types(app, created_models, verbosity, **kwargs):
        notification.create_notice_type("messages_received", _("Message Received"), _("you have received a message"), default=2)
        notification.create_notice_type("messages_sent", _("Message Sent"), _("you have sent a message"), default=1)
        notification.create_notice_type("messages_replied", _("Message Replied"), _("you have replied to a message"), default=1)
        notification.create_notice_type("messages_reply_received", _("Reply Received"), _("you have received a reply to a message"), default=2)
        notification.create_notice_type("messages_deleted", _("Message Deleted"), _("you have deleted a message"), default=1)
        notification.create_notice_type("messages_recovered", _("Message Recovered"), _("you have undeleted a message"), default=1)

    signals.post_syncdb.connect(create_notice_types, sender=notification)
else:
    print "Skipping creation of NoticeTypes as notification app not found"

rawDescription: How is django-messages creating notification types during syncdb?


code:
string = r'C:\Users\Victor\Dropbox\Private\files\test.txt'
string
print string

rawDescription: Python regex replace backslash or frontslash


code: print u'ÆØÅ'

rawDescription: Print UTF-8 characters in cmd using python


code:
import random
from timeit import Timer

def random_strings(size):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    min = 3
    max = 8
    strings = []
    for count in xrange(1, size):
        current = ''
        for x in random.sample(alpha, random.randint(min,max)):
            current += x
        strings.append(current)
    return strings

string_list_1 = random_strings(10000)
string_list_2 = random_strings(10000)

def string_test():
    common = filter(lambda x: x in string_list_2, string_list_1)
    return common

def set_test():
    string_set_1 = frozenset(string_list_1)
    string_set_2 = frozenset(string_list_2)
    common = string_set_1 & string_set_2
    return common

string_timer = Timer("__main__.string_test()", "import __main__")
set_timer = Timer("__main__.set_test()", "import __main__")
print string_timer.timeit(10)
# 22.6108954005
print set_timer.timeit(10)
#  0.0226439453

rawDescription: Search for item in list with 2MILLION items - Python


code:
from itertools import izip_longest

for customer, room in izip_longest(A, B):
    if room:
        print customer + ' is in ' + room
    else:
        print customer + ' all rooms are reserved'

rawDescription: How to zip two arrays without truncating to the shortest array?

description: Zip two arrays without truncating to the shortest array


code:
def raw_print(str, *args):
    out_str = str % args
    sys.stdout.write(out_str)

class DeferredAsserter(object):
    def __init__(self):
        self.broken = False
    def assert_equal(self, expected, actual):
        outstr = '%s == %s...' % (expected, actual)
        raw_print(outstr)
        try:
            assert expected == actual
        except AssertionError:
            raw_print('FAILED\n\n')
            self.broken = True
        except Exception, e:
            raw_print('ERROR\n')
            traceback.print_exc()
            self.broken = True
        else:
            raw_print('PASSED\n\n')

    def invoke(self):
        assert not self.broken

rawDescription: Python test framework with support of non-fatal failures


code:
class A(object):
  @classmethod
  def foo(cls):
    print cls.__name__
    # *** I would like to print either 'A' or 'B' here

class B(A):
  pass

A.foo()
B.foo()

rawDescription: How can I find out what class I was called as from a @staticmethod function in python?

description: Find out what class I was called as from a @staticmethod function in python


code:
import os

searchFolder = '/Users/bubble/Desktop/pics'

with open('/Users/bubble/Desktop/workfile.txt','w') as f:
    for root, dirs, files in os.walk(searchFolder):
        for file in files:
            pathName = os.path.join(root,file)
            print pathName
            print os.path.getsize(pathName)
            print
            f.write('{}\n'.format(pathName))
            f.write('{}\n'.format(os.path.getsize(pathName)))

rawDescription: Python's osWalk to text file? only one line being printed


code:
import numpy
import theano
import theano.tensor as tt

def compile_model(input_size, hidden_size, output_size, learning_rate):
    w_h = theano.shared(numpy.random.randn(input_size, hidden_size).astype(theano.config.floatX))
    b_h = theano.shared(numpy.zeros(hidden_size, dtype=theano.config.floatX))
    w_y = theano.shared(numpy.random.randn(hidden_size, output_size).astype(theano.config.floatX))
    b_y = theano.shared(numpy.zeros(output_size, dtype=theano.config.floatX))
    parameters = (w_h, b_h, w_y, b_y)
    x = tt.matrix()
    z = tt.lvector()
    h = tt.tanh(theano.dot(x, w_h) + b_h)
    y = tt.nnet.softmax(theano.dot(h, w_y) + b_y)
    c = tt.nnet.categorical_crossentropy(y, z).mean()
    u = [(p, p - learning_rate * theano.grad(c, p)) for p in parameters]
    trainer = theano.function([x, z], outputs=[c], updates=u)
    tester = theano.function([x], outputs=[y])
    return trainer, tester, parameters

def refresh_model(parameters, input_size, hidden_size, output_size):
    w_h, b_h, w_y, b_y = parameters
    w_h.set_value(numpy.random.randn(input_size, hidden_size).astype(theano.config.floatX))
    b_h.set_value(numpy.zeros(hidden_size, dtype=theano.config.floatX))
    w_y.set_value(numpy.random.randn(hidden_size, output_size).astype(theano.config.floatX))
    b_y.set_value(numpy.zeros(output_size, dtype=theano.config.floatX))

def main():
    input_size = 30
    hidden_size = 10
    output_size = 20
    learning_rate = 0.01
    batch_size = 40
    epoch_count = 50

    trainer, tester, parameters = compile_model(input_size, hidden_size, output_size, learning_rate)
    x = numpy.random.randn(batch_size, input_size)
    z = numpy.random.randint(output_size, size=(batch_size,))
    print 'Training model with hidden size', hidden_size

    for _ in xrange(epoch_count):
        print trainer(x, z)

    hidden_size = 15
    refresh_model(parameters, input_size, hidden_size, output_size)
    print 'Training model with hidden size', hidden_size

    for _ in xrange(epoch_count):
        print trainer(x, z)

main()

rawDescription: Best way to re-initialise a compiled Theano function

description: Re-initialise a compiled Theano function


code:
data = np.genfromtxt(filepath, names=True, dtype=None)
idx = np.abs(data['Chan1'] - data['Chan2'])<1
print data[idx]

rawDescription: Finding same values in a row of csv in python


code:
from socket import gethostbyaddr

with open('top-1m.csv') as input:
    for line in input:
        index, host = line.strip().split(',')
        try:
            output = gethostbyaddr(host)
            print "%s %s is %s/%s" % (index, host, output[0], output[2])
        except:
            print host, "not found"

rawDescription: In python, what is the most efficient way to perform DNS queries on a comma separated list of domain names?


code: print len(set(anagram))

rawDescription: Count unique values in Python list

description: Count unique values in Python list


code:
import numpy as np
def pair(matrix,i,j):
    str1=''
    for value in matrix[i]:
        str1+=str(value)+' '
    # Delete one extra space
    str1=str1[:-1]

    str2=''
    for value in matrix[j]:
        str2+=str(value)+' '
    str2=str2[:-1]
    return str1+', '+str2

matrix=np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

print pair(matrix,0,1)
print pair(matrix,0,2)

rawDescription: Convert numpy array to a string using numpy.array_str()


code:
import pyglet
from pyglet.gl import *
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

# Direct OpenGL commands to this window.
config = Config(double_buffer = True)
window = pyglet.window.Window(config = config)
window.set_vsync(True)
window.set_fullscreen(True)

colorSwap = 0
fullscreen = 1

fps_display = pyglet.clock.ClockDisplay()

def on_draw(dt):
    global colorSwap
    glClear(GL_COLOR_BUFFER_BIT)  # Clear the color buffer
    glLoadIdentity()              # Reset model-view matrix

    glBegin(GL_QUADS)
    if colorSwap == 1:
        glColor3f(1.0, 0.0, 0.0)
        colorSwap = 0
    else:
        glColor3f(0.0, 1.0, 0.0)
        colorSwap = 1

    glVertex2f(window.width, 0)
    glVertex2f(window.width, window.height)
    glVertex2f(0.0, window.height)
    glVertex2f(0.0, 0.0)
    glEnd()
    fps_display.draw()

@window.event
def on_key_press(symbol, modifiers):
    global fullscreen
    if symbol == pyglet.window.key.F:
        if fullscreen == 1:
            window.set_fullscreen(False)
            fullscreen = 0
        else:
            window.set_fullscreen(True)
            fullscreen = 1
    elif symbol == pyglet.window.key.ESCAPE:
        print ''

dt = pyglet.clock.tick()
pyglet.clock.schedule_interval(on_draw, 0.0001)
pyglet.app.run()

rawDescription: Python: pyglet vs PyOpengl performance evaluation for frame dropping