code:
example_dict = { 'key1' : 'value1',
                 'key2' : 'value2',
                 'key3' : { 'key3a': 'value3a' },
                 'key4' : { 'key4a': { 'key4aa': 'value4aa',
                                       'key4ab': 'value4ab',
                                       'key4ac': 'value4ac'},
                            'key4b': 'value4b'}
                }

def find_key(d,key):
    for k,v in d.items():
        if isinstance(v,dict):
            p = find_key(v,key)
            if p:
                return [k] + p
        elif v == key:
            return [k]

print find_key(example_dict,'value4ac')

rawDescription: Get parents keys from nested dictionary

description: Get parents keys from nested dictionary


code:
def bench(num):
     start = time.time()
     for i in range(num):
         producer.publish({"name": 'test', 'data': 1231231})
     elapsed = time.time() - start
     print "Sent %s messages in %.2f seconds : %.1f msg/sec" % (num, elapsed, num / elapsed)

bench(100)
bench(1000)
bench(10000)

rawDescription: Looking for a compiled Python AMQP library


code:
import glob
from BeautifulSoup import BeautifulSoup

for filename in glob.glob('/home/phi/Data/*.htm'):
    soup = BeautifulSoup(open(filename, "r").read()) # assuming some HTML
    for a_tr in soup.findAll("tr", attrs={ "class" : "evenColor" }):
        print a_tr

rawDescription: Scraping Multiple html files to CSV

description: Scraping Multiple html files to CSV


code:
haystack = "aaaAAAbbbBBB"
needle   = "AAA"

pos = haystack.rfind(needle)

if pos >= 0:
    print "found at", pos - len(haystack)
else:
    print "not found"

rawDescription: Python - "windowed" iteration through a binary object?


code:
from bs4 import BeautifulSoup, SoupStrainer
import threading
import urllib2

def fetch_url(url):
    urlHandler = urllib2.urlopen(url)
    html = urlHandler.read()
#this tells it to soup the page that is at the url above
    soup = BeautifulSoup(html)

#this tells it to find the string in the first instance of each of the tags in the parenthesis
    title = soup.find_all('title')
    article = soup.find_all('article')

    try:
        title = str(title[0].get_text().encode('utf-8'))
    except:
        print "had to skip one bad title\n"
        return
    try:
        article = str(article[0].get_text().encode('utf-8'))
    except:
        print "had to skip one bad article"
        return

    try:
# make the file using the things above
        output_files_pathname = 'DailyNews/'  # path where output will go
        new_filename = title + ".txt"

# write each of the things defined into the text file
        outfile = open(output_files_pathname + new_filename, 'w')
        outfile.write(title)
        outfile.write("\n")
        outfile.write(article)
        outfile.close()
        print "%r added as a text file" % title
        return

    except:
        print "had to skip one cant write file"
        return

    return
with open("dailynewsurls.txt", 'r') as urlfile:
# read one line at a time until end of file
    threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urlfile]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

rawDescription: Using WorkerPool to multithread through a list of URLs


code:
f = open('sampler_chain.dat').read()

ndim=4
import numpy as np
import re
pattern = re.compile("^[0-9]")
data = np.zeros((1,ndim),float)
i=0;dl=[]
for x in f.split():
      if pattern.match(x):
         m = re.match(r"(\d+)\.(\d+)", x)
         x=m.group(0)
         print x
         if ((i/4==0) and (i%4<4)):
            data[i/4,i%4]=float(x)
         elif ((i/4>0) and (i%4<4)):
              dl.append(float(x))
         if (i%4==3) and (i/4>0):
             data=np.append(data,[dl],axis=0)
             dl=[]
         i+=1
      else:
         continue

rawDescription: Reading a file contains lists of values into an array


code:
def connectivityDictSub(num, d, setl, key, i):
    if i >= num:
        assert(key not in d)
        d[key] = setl
    else:
        for ni in range(len(setl)):
            nsetl, nkey = setl[:], key
            for other in nsetl[ni]:
                assert(other != i)
                x,y = sorted((i, other))
                ki = ((2*num-3-x)*x)/2 + y-1
                nkey |= 1<<ki
            nsetl[ni] = nsetl[ni] + [i] #not the same as += since it makes a copy
            connectivityDictSub(num, d, nsetl, nkey, i+1)
        nsetl = setl + [[i]]
        connectivityDictSub(num, d, nsetl, key, i+1)

def connectivityDict(groundSet):
    gset = sorted(set(groundSet))
    d = {}
    connectivityDictSub(len(gset), d, [], 0, 0)
    for setl in d.values():
        setl[:] = [tuple(gset[i] for i in x) for x in setl]
    return map(tuple, d.values())

for x in connectivityDict('ABCD'):
    print x

rawDescription: Python - Arranging combinations of list into a list of tuples of various sizes


code:
def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

rawDescription: Python loop counter in a for loop

description: Python loop counter in a for loop


code:
import pygame as pg
import sys
import random

window_wth = 720
window_hgt = 360
window_resolution = window_wth, window_hgt

fps = 15

card_wth = 72
card_hgt = 92
gap_x = 77
gap_y = 97

c1 = (random.randrange(255), random.randrange(255), random.randrange(255))
c2 = (random.randrange(255), random.randrange(255), random.randrange(255))
c3 = (random.randrange(255), random.randrange(255), random.randrange(255))
c4 = (random.randrange(255), random.randrange(255), random.randrange(255))

bkg_colour = (30, 30, 30)
pg.display.set_caption("Game")
main_display = pg.display.set_mode(window_resolution)
background = pg.Surface(window_resolution)

pos_x = int((window_wth % gap_x) / 2)
pos_y = int((window_hgt % gap_y) / 2)

global cards

class Card(object):
    def __init__(self, xpos, ypos, colour):
        super(Card, self).__init__()

        self.colour = colour
        self.xpos = xpos
        self.ypos = ypos
        self.width = 72
        self.height = 92
        self.rect = pg.Rect((xpos, ypos, self.width, self.height))

def make_cards(tt_pos_x, tt_pos_y):
    global cards
    cards = []
    for x in range(tt_pos_x, window_wth - gap_x, gap_x):
        for y in range(tt_pos_y, window_hgt - gap_y, gap_y):
            colour = (random.randrange(255), random.randrange(255), random.randrange(255))
            card = Card(x, y, colour)
            cards.append(card)
    return cards

def main():
    global fps_clock, main_display, cards
    fps_clock = pg.time.Clock()

    while True:

        if pg.mouse.get_pressed()[0]:
            print "mouse button pressed"
            pos = pg.mouse.get_pos()
            for card in cards:
                if card.rect.collidepoint(pos):
                    cards.remove(card)

        for event in pg.event.get():
            if event.type == pg.QUIT:
                sys.exit()

        fps_clock.tick(fps)
        update()

def update():
    global cards
    background.fill((0,0,0))
    for card in cards:
        pg.draw.rect(background, card.colour, card.rect, 5)

    main_display.blit(background, (0,0))
    pg.display.update()

if __name__ == '__main__':
    global cards
    cards = make_cards(pos_x, pos_y)
    pg.display.update()
    main()

rawDescription: How do I remove a specific pygame.draw on click?

description: Remove a specific pygame.draw on click


code:
web_pages = {1:('Google Scholar','website1'),
         2:('Moodle','website2'),
         3:('BBC','website3'),
         4:('Webmail','website4')}

##-------output_structure_top---------------------------
def output_structure_top ():
    print "--- MY BOOKMARK MANAGER --- "+"\n"
    print "Number"+" "*10 +"Name"+" "*30+"Address \n"
    print "-"*60+"\n"

##----output_structure_bottom------------------------
def output_structure_bottom():
    print "-"*60+"\n"

##----------------------------------------------------
def output_structure_value(key,value):
    print (str(key) +" "*10+ value[0] +" "*30 +value[1])

output_structure_top ()
for key, value in web_pages.iteritems():
    output_structure_value(key,value)
output_structure_bottom()

rawDescription: python dictionary formatted printout

description: Python dictionary formatted printout


code:
pix = mapImage.get_region(x,y,1,1).get_image_data().get_data("RGBA", 4)

print 'r = ' + str(ord(pix[0]))
print 'g = ' + str(ord(pix[1]))
print 'b = ' + str(ord(pix[2]))
print 'a = ' + str(ord(pix[3]))

rawDescription: problem with reading RGB values of pixels using pyglet

description: Problem with reading RGB values of pixels using pyglet


code:
import lxml.etree as et

tree = et.fromstring('''
... your xml ...
''')

for host_ip in tree.xpath("/scenario/init/send/command[@name='CER']/avp[@name='Host-IP-Address']"):
    host_ip.attrib['value'] = 'foo'

print et.tostring(tree)

rawDescription: python lxml - modify attributes

description: Python lxml - modify attributes


code:
db = sqlite3.connect("Gene.sqlite")
cur = db.cursor()
looking_for = 'hello'
cur.execute("SELECT type,description FROM Table WHERE name = '%s'", (looking_for,))
for i in cur.fetchall():
    result = '
<c>TYPE: {}
DESCRIPTION:</c> {}'
    print result.format(*i)
else:
    print '{} does not exist in the Database'.format(looking_for)

rawDescription: How to stop a search into a database when I already have results

description: Stop a search into a database when I already have results


code:
from dateutil import rrule
from datetime import  timedelta , datetime
holidays = [] # This is just a list of dates to exclude

def datetime_in_x_trading_hours(start_dt,future_hours):
    # First we add two hours. This is because its simpler to view the timeset
    # as 24hrs MON - FRI. (This also helps align the dates for the holidays)
    print start_dt
    start_dt += timedelta(hours=2)
    rs = get_fx_rset(start_dt)
    # Now using the set get the desired time and put the the missing hours
    future_time = rs[future_hours]
    future_time -= timedelta(hours=2)
    return future_time

def get_fx_rset(start_date_time):

    # Create a rule to recur every weekday starting today
    r = rrule.rrule(rrule.HOURLY,
                    byweekday=[rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR],
                    byhour=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
                    byminute=[0],
                    bysecond=[0],
                    dtstart=start_date_time)

    # Create a rruleset
    rs = rrule.rruleset()
    # Attach our rrule to it
    rs.rrule(r)
    # Add holidays as exclusion days
    for exdate in holidays:
        rs.exdate(exdate)

    return rs

today = datetime.now() - timedelta(days=2)
print datetime_in_x_trading_hours(today, 7)

rawDescription: RRule set for days and hours in day

description: RRule set for days and hours in day


code:
import itertools

lst = [1,2,3,4]
lst2 = ['one','two','three','four','five']

print dict(itertools.izip_longest(lst2, lst, fillvalue=None))
# {'five': None, 'four': 4, 'one': 1, 'three': 3, 'two': 2}

rawDescription: Python: add the key to each list item, and then convert to dictionary


code:
from xml.dom import minidom
data = minidom.parseString(s)
parts = data.getElementsByTagName('item')
item = parts[0]
item.childNodes
item.childNodes[1].nodeValue = 'changed'
print item.toxml()

rawDescription: Figuring out where CDATA is in lxml element?


code:
import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
     sys.stdout = outfile
     for cdir, dir, files in os.walk(r'/Users'):
         for file in files:
             if file.endswith('.py'):
                filename = os.path.join(cdir, file)
                size = os.path.getsize(filename)
                records.setdefault(size, []).append(filename)
     print records
     sys.stdout = out

rawDescription: Adding items to an existing dictionary using loops in python


code:
stickList = map(int, "5 4 4 2 2 8".split())
stickList.sort()
for i in reversed(xrange(len(stickList))):
    stickList[i] -= stickList[0]
print stickList

rawDescription: Array elements not getting edited in a Python List


code:
import wx

class Panel(wx.Panel):
    def __init__(self, parent):
        super(Panel, self).__init__(parent)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.Bind(wx.EVT_PAINT, self.on_paint)
        self.Bind(wx.EVT_LEFT_DOWN, self.on_left_down)
        self.Bind(wx.EVT_LEFT_UP, self.on_left_up)
    def on_left_down(self, event):
        print 'on_left_down', event.GetPosition()
    def on_left_up(self, event):
        print 'on_left_up', event.GetPosition()
    def on_paint(self, event):
        dc = wx.AutoBufferedPaintDC(self)
        # Use dc.DrawBitmap(bitmap, x, y) to draw the cards here

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None)
        self.SetTitle('My Title')
        Panel(self)

def main():
    app = wx.App()
    frame = Frame()
    frame.Center()
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: wxPython Solitaire GUI

description: WxPython Solitaire GUI


code: exec"x=10\nwhile x>0: print x; x-= 1"

rawDescription: in python, is it possible to write a while loop and all its contents on one line?

description: In python, is it possible to write a while loop and all its contents on one line


code:
import subprocess

p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "java -jar"], stdin=p1.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
p3 = subprocess.Popen(["grep", "-v", "grep"], stdin=p2.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
p4 = subprocess.Popen(["awk", "//{print $2}"], stdin=p3.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
out, err = p4.communicate()

print out

rawDescription: Running shell command in python and reading output


code:
from collections import Counter
import numpy as np

mat=[[1,2,3],[3,2,1],[5,4,6]]
mat = np.matrix(mat)

submat = mat[a-1:c,b-1:d] # extract the sub matrix desired

flattened = np.array(submat.flatten()).flatten() #flatten it for use in counter

print Counter(flattened) # prints the counts of each unique item

len_unique = len(Counter(flattened)) # the total number of unique items.

rawDescription: Best way to find the number of distinct element in a submatrix using python

description: Find the number of distinct element in a submatrix using python


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("teststring", type=str, help="this is a string")
args = parser.parse_args()
print args.teststring

rawDescription: Passing a string using argparse

description: Passing a string using argparse


code:
import poplib

M = poplib.POP3("pop.gmail.com")
M.user("user")
M.pass_("pass")
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print j

rawDescription: Python Selenium - clicking on the account confirmation link in the email


code:
for i, x in enumerate(all_decks):
        print i, x.name

rawDescription: Why all are indexes in my list of lists 0?


code:
import time, subprocess, socket, re

afttFile=open("ApplicationPackage.DOC", "r")

fileName=""
packageName=""
activityName=""
packageFile=None

window_dump=None
current_window=None
windows=None

#Function for executing adb shell command
def adb(command, input=None):
    if not isinstance(command,list): command=command.split()
    return subprocess.Popen(command, stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT).communicate(input=input)[0]

#Function for getting current window hash id
def getWindowHash():
    command='adb shell '

    window_dump=subprocess.Popen(command+'dumpsys window windows', shell=False, stdout=subprocess.PIPE)
    window_dump=window_dump.stdout.read()

    regexp=re.compile(r'Window #\d+[:\s\r\n]+Window\{(?P<hash>[a-f\d]{8}) (?P<title>.*) paused=.*\}:?[\r\n]+(?P<attributes>(?:    .*[\r\n]+)+)', re.MULTILINE)

    windows=[ m.groupdict() for m in regexp.finditer(window_dump) ]

    # fetch current window
    m=re.search('mCurrentFocus=Window\{(?P<hash>\S+) (?P<title>\S*) \S+', window_dump)
    if m:
        current_window=m.groupdict()
        #print self.current_window
    else:
        current_window=None

    for window in windows:
        if window['hash']==current_window['hash']:
            return [window][0]['hash']

#Read Packag Name & Corresponding Activity Name from Provided file
for line in afttFile:
    #print line
    if len(line.split("."))==3:
        if packageFile!=None:
            packageFile.flush()
            packageFile.close()
            #print "File with name: "+fileName+" closed"

        packageName=line.strip("\n")
        print "Package Name: "+packageName
        fileName=line.split(".")[2].strip("\n")+".txt"
        #print fileName
        #Create file with corresponding package name
        packageFile=open(fileName, "a")

        #packageFile.flush()
        #packageFile.close()
    else:
        activityName=line.strip("\n")
        print "Activity Name: "+activityName
        ## if packageName=="com.android.browser":
             ## #print packageName
             ## ommand="adb -s emulator-5554 shell am start -a android.intent.MAIN -n "+packageName+"/"+activityName
             ## print command
             ## ## result=subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
             ## ## result=result.stdout.read()

        #print packageName
        if packageName=="com.android.mms":
            command="adb shell am start -n "+packageName+"/"+activityName
            print command
            result=subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
            result=result.stdout.read()
            time.sleep(10)

            print "Parsing has been started"
            f=open("AFTT.txt", "w")

            command='adb shell '
            comm='adb '

            for port in range(5939,5979,2):
                try:
                    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    subprocess.Popen(command+'service call window 2', shell=False, stdout=subprocess.PIPE)
                    time.sleep(.5)
                    subprocess.Popen(command+'service call window 1 i32 4939', shell=False, stdout=subprocess.PIPE)
                    time.sleep(.5)

                    adb(comm+' forward tcp:%d tcp:4939' % port)
                    print "forwarding done"

                    s.connect(('127.0.0.1', port))
                    #print "Connection Made"
                    print "Port Used for Communication: %s" %port
                    hashId=getWindowHash()
                    print "Window Hash_Id: %s" %hashId

                    s.sendall('DUMP %s\n'%hashId)
                    print "Command sent"
                    s.settimeout(360)
                    data=''
                    i=0
                    t0 = time.time()
                    print "Starting loop"
                    while True:
                        datum=s.recv(32*1024)
                        #print datum
                        #print 'Received %d bytes' % len(datum)
                        #print "\n"
                        print "Packet: "+datum
                        f.write(datum)

                        if (datum.endswith('\nDONE.\n') or datum.endswith('DONE.\n') or datum.endswith('\nDONE.\nDONE\n') or datum.endswith('DONE.\nDONE\n')):
                            #print "End of Packet ransfer"
                            break

                        if datum == '':
                            #print "Socket closed"
                            raise socket.error('Socket closed')

                        data+=datum

                        if time.time() - t0 > 360:
                            #print "Timeout"
                            raise socket.error('Timeout')
                        i=i+1
                    break

                except socket.error:
                    #print "Checking for another port"
                    subprocess.Popen(command+'service call window 2', shell=False, stdout=subprocess.PIPE)
                    time.sleep(.5)
                    subprocess.Popen(command+'service call window 1 i32 4939', shell=False, stdout=subprocess.PIPE)
                    time.sleep(.5)
                    #f.close()
                    s.close()
                    #print "Server restarted"

            #Open File for Parsing UI Elements
            f=open("AFTT.txt", "r")
            #package=open("Package.txt", "w")
            for line in f:
                widg_id=re.compile(r'mID=\S*', re.MULTILINE).findall(line)
                widg_text=re.compile(r'mText=\d*,[a-zA-Z\W\d]*', re.MULTILINE).findall(line)

                if len(widg_id)!=0 or len(widg_text)!=0:
                    ##################################################################
                    #Parse Widget Id
                    if len(widg_id)!=0:
                        widg_id=widg_id[0]
                        widg_id=str(widg_id)
                        widg_id=widg_id.strip("[]'")
                        if 'id' in widg_id:
                            widg_id=widg_id.split(",")[1].split("/")[1]
                        else:
                            widg_id=widg_id.split(",")[1]
                        packageFile.write(widg_id+"->")
                    else:
                        packageFile.write("None->")

                    ##################################################################
                    #Parse Widget Text
                    if len(widg_text)!=0:
                        widg_text=str(widg_text)
                        #Remove unncessary characters from String
                        widg_text=widg_text.strip("[]'")

                        #Get the second element that is excluding 'mText'
                        widg_text=widg_text.split(",")[1]

                        #SPlit text on basis of space
                        widg_text_ls=widg_text.split(" ")

                        widg_text=""
                        #Remove one element from last
                        widg_text_ls.pop()
                        #Create new STring by joining list
                        widg_text=" ".join(widg_text_ls)

                        if len(widg_text)==0:
                            packageFile.write("None->")
                        else:
                            packageFile.write(widg_text+"->")
                    else:
                        packageFile.write("None->")

                    ##################################################################
                    #Parse Widget Type
                    widg_type=str(line.split("@")[0])
                    widg_type=widg_type.strip(" ")
                    packageFile.write(widg_type)
                    packageFile.write("\n")
            f.close()
afttFile.close()

rawDescription: How can I get all component and widget Id of current Android window screen programmatically?

description: Get all component and widget Id of current Android window screen programmatically


code:
from csv import reader
csv_reader = reader(open("C:/text.txt","r"), quotechar="\"")

for row in csv_reader:
    print row

['391788', 'HP Deskjet 3050 scanner always seems to break', "
I'm running a Windows 7 64 blah blah blah........ake this work permanently?
\n\n
Update: It might have something to do with my computer. It seems to work much better on another computer, windows 7 laptop. Not sure exactly what the deal is, but I'm still looking into it...
\n", 'windows-7 printer hp']

rawDescription: R's read.table equivalent in Python

description: R's read.table equivalent in Python


code:
import yaml
class User(object):
    def __init__(self, name, surname):
       self.name= name
       self.surname= surname

    def yaml(self):
       return yaml.dump(self.__dict__)

    @staticmethod
    def load(data):
       values = yaml.safe_load(data)
       return User(values["name"], values["surname"])

user = User('spam', 'eggs')
serialized_user = user.yaml()
print "serialized_user:  %s" % serialized_user.strip()

#Network
deserialized_user = User.load(serialized_user)
print "name: %s, sname: %s" % (deserialized_user.name, deserialized_user.surname)

rawDescription: How to deserialize an object with PyYAML using safe_load?

description: Deserialize an object with PyYAML using safe_load


code:
import subprocess

if subprocess.call(["gcc", "test.c"]) == 0:
    subprocess.call(["./a.out <input.txt >output.txt"], shell=True)
else: print "Compilation errors"

rawDescription: Compile a C/C++ Program and store standard output in a File via Python


code:
import maya.cmds as cmds

selObjs = cmds.ls(sl=1)
selAttrs = cmds.channelBox("mainChannelBox", q=1, sma=1)
scales = ['sy','sx','sz','v']

if not selObjs:
    print "no object and attribute is selected!"
elif not selAttrs:
    print "no attribute is selected!"
else:
    for eachObj in selObjs:
        for eachAttr in selAttrs:
            if any(scaleVizItem in eachAttr for scaleVizItem in scales):
                cmds.setAttr (eachObj+"."+eachAttr, 1)
            else:
                cmds.setAttr (eachObj+"."+eachAttr, 0)

rawDescription: Proper way to use setAttr with channel box selection


code:
from Tkinter import *

class PokerGame(object):
    def __init__(self):
        self.run()

    def run(self):
        self.root = Tk()
        self.root.title("PyPoker")
        self.root.geometry("1280x720")
        #self.width = 1280
        #self.height = 720
        #self.canvas = Canvas(self.root, width = self.width, height = self.height)
        #self.canvas.pack()

        self.drawStartScreen()
        self.root.mainloop()

    def drawStartScreen(self):
        self.bgImage = PhotoImage(file = 'startbg.gif')

        self.bgLabel = Label(self.root, image = self.bgImage)
        self.bgLabel.place(x = 0, y = 0, relwidth = 1, relheight = 1)

        self.btnPlay = Button(self.root, text = "Play", command = self.playGame)
        self.btnPlay.place(relheight = 0.1, relwidth = 0.1, relx = 0.5, rely = 0.4, anchor = CENTER)

        self.btnInstructions = Button(self.root, text = "How To Play", command = self.showInstructions)
        self.btnInstructions.place(relheight = 0.1, relwidth = 0.1, relx = 0.5, rely = 0.5, anchor = CENTER)

    def playGame(self):
        self.redrawAll()

    def showInstructions(self):
        self.redrawAll()

    def redrawAll(self):
        print "trying to delete all"
        self.btnPlay.place_forget()
        self.btnInstructions.place_forget()
        self.bgLabel.place_forget()

PokerGame()

rawDescription: canvas.delete(ALL) not working

description: Canvas.delete(ALL) not working


code:
lines = subprocess.Popen([program, '-i'], stdout=subprocess.PIPE).communicate()[0]
print lines.splitlines()[0] + '\n'

rawDescription: In python how can i print only the first line of stdout which results from a shell command


code:
if feature[1] <= position and feature[2] >= position:
    print feature

rawDescription: Extracting secondary strucutre data from Swissprot Features tuple Python


rawDescription: Python 2.7 list of lists manipulation functionality


code:
import signal
import time

class TimeOutException(Exception):
    pass

def timeout(seconds, *args, **kwargs):
    def fn(f):
        def wrapped_fn(*args, **kwargs):
            signal.signal(signal.SIGALRM, handler)
            signal.alarm(seconds)
            f(*args, **kwargs)
        return wrapped_fn
    return fn

def handler(signum, frame):
    raise TimeOutException("Timeout")

@timeout(5)
def my_function_that_takes_long(time_to_sleep):
    time.sleep(time_to_sleep)

if __name__ == '__main__':
    print 'Calling function that takes 2 seconds'
    try:
        my_function_that_takes_long(2)
    except TimeOutException:
        print 'Timed out'

    print 'Calling function that takes 10 seconds'
    try:
        my_function_that_takes_long(10)
    except TimeOutException:
        print 'Timed out'

rawDescription: Timing out urllib2 urlopen operation in Python 2.4


code:
from apscheduler.schedulers.background import BlockingScheduler

count = 0

def job_function():
    print "job executing"
    global count, scheduler

    # Execute the job till the count of 5
    count = count + 1
    if count == 5:
        scheduler.remove_job('my_job_id')

scheduler = BlockingScheduler()
scheduler.add_job(job_function, 'interval', seconds=1, id='my_job_id')

scheduler.start()

rawDescription: Python - Apscheduler not stopping a job even after using 'remove_job'


code:
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol, Factory
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet import reactor

# Stream-oriented connections like TCP are handled by an instance
# of a Protocol subclass
class SomeKindOfClient(Protocol):

     # When a new connection is established, the first thing that
     # happens is this method is called.
     def connectionMade(self):
         # self.transport is set by the superclass, and lets us
         # send data over the connection
         self.transport.write("GREETING")

         # a Deferred is a generic, composable API for specifying
         # callbacks
         self.greetingComplete = Deferred()

         # Here's some local state
         self._buffer = ""

     # Whenever bytes arrive on the TCP connection, they're passed
     # to this method
     def dataReceived(self, bytes):

         # Incorportate the network event data into our local state.
         #  This kind of buffering is always necessary with TCP, because
         # there's no guarantees about how many bytes will be delivered
         # at once (except that it will be at least 1), regardless of
         # the size of the send() the peer did.
         self._buffer += bytes

         # Figure out if we're done - let's say the server response is 32
         # bytes of something
         if len(self._buffer) >= 32:
             # Deliver it to whomever is waiting, by way of the Deferred
             # object
             greeting, self._buffer = self._buffer[:32], self._buffer[32:]
             complete = self.greetingComplete
             self.greetingComplete = None
             complete.callback(greeting)

         # Otherwise we'll keep waiting until dataReceived is called again
         # and we have enough bytes.

# One of the normal ways to create a new client connection
f = Factory()
f.protocol = SomeKindOfClient
e = TCP4ClientEndpoint(reactor, "somehost", 1234)

# Connect returns one of those Deferreds - letting us specify a function
# to call when the connection is established.  The implementation of
# connect is also doing basically the same kind of thing as you're asking
# about.
d = e.connect(f)

# Execution continues to this point before the connection has been
# established.  Define a function to use as a callback when the connection
# does get established.
def connected(proto):
    # proto is an instance of SomeKindOfClient.  It has the
    # greetingComplete attribute, which we'll attach a callback to so we
    # can "wait" for the greeting to be complete.
    d = proto.greetingComplete

    def gotGreeting(greeting):
        # Note that this is really the core of the answer.  This function
        # is called *only* once the protocol has decided it has received
        # some necessary data from the server.  If you were waiting for a
        # session identifier of some sort, this is where you might get it
        # and be able to proceed with the remainder of your application
        # logic.
        print "Greeting arrived", repr(greeting)

    # addCallback is how you hook a callback up to a Deferred - now
    # gotGreeting will be called when d "fires" - ie, when its callback
    # method is invoked by the dataReceived implementation above.
    d.addCallback(gotGreeting)

# And do the same kind of thing to the Deferred we got from
# TCP4ClientEndpoint.connect
d.addCallback(connected)

# Start the main loop so network events can be processed
reactor.run()

rawDescription: python networking: asynchat handshake

description: Python networking: asynchat handshake


code:
def get_pixel_colour(i_x, i_y):
    import win32gui
    i_desktop_window_id = win32gui.GetDesktopWindow()
    i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
    long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
    i_colour = int(long_colour)
    return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)

print get_pixel_colour(0, 0)

rawDescription: Is it possible to get the color of a particular pixel on the screen with it's X and Y coordinates?


code:
class BodyMassIndex(object): #Inheriting from object in 2.x ensures a new-style class.
  count = 0
  def __init__(self, name, weight, height):
    self.name = name
    self.weight = 14 * weight
    self.height = 12 * height
    self.notes = None
    self.bmitotal = 0
    BodyMassIndex.count += 1

  def display_count(self):
    print "Total number of objects is %d" % BodyMassIndex.count

  def calculate_bmi(self):
    return ( self.weight * 703 ) / ( self.height ** 2 )

test = BodyMassIndex("bob", 10, 10)
test.notes = "some notes"
print(test.notes)

rawDescription: Basic Python Class

description: Basic Python Class


code:
from tzwhere import tzwhere

print tzwhere.tzwhere().tzNameAt(38.897663,-77.036562)

rawDescription: Get timezone of location offline

description: Get timezone of location offline


code:
for i in range (1, yearsRunning + 1):
    print
    print "Savings Schedule for Year", i,":"
    print "Month    Interest    Amount  Balance"
    for k in range (1, 13):
        totalInterest = monthlyInterest * totalInvestBal
        totalInvestBal = totalSavings + totalInterest + totalInvestBal
        totalSavings = totalSavings
        print k, round(totalInterest,2), round(totalSavings,2), round(totalInvestBal,2)
    print
    #IF WE KEEP ONLY i IT becomes 12 here so we need another -> VARIABLE!!!!! for example K!!.
    print "Savings summary for year %s:" %(i) #use this " words words %s words" %(variable name)
    print "Total amount saved:", totalSavings
    print "Total interest earned:", totalInterest
    print "End of year balance:", totalInvestBal

rawDescription: Beginner Python Code Issue: Accumulator Loop


code:
import numpy as np

d = np.random.choice(xrange(0, 1000), size=100000, replace=True).tolist()
d = [str(item) for item in d]

total = len(d)
greatest = d[total-1]
for i in reversed(xrange(total)):
    greatest = max(greatest, d[i])
    if i % 1000 == 0:  # To track progress
        print i

rawDescription: Python Quickest Method to Iteratively Slice List of Date Strings


code:
from sklearn import datasets
import pandas
from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation
from sklearn.metrics import confusion_matrix

def get_enhanced_confusion_matrix(actuals, predictions, labels):
    """"enhances confusion_matrix by adding sensivity and specificity metrics"""
    cm = confusion_matrix(actuals, predictions, labels = labels)
    sensitivity = float(cm[1][1]) / float(cm[1][0]+cm[1][1])
    specificity = float(cm[0][0]) / float(cm[0][0]+cm[0][1])
    weightedAccuracy = (sensitivity * 0.9) + (specificity * 0.1)
    return cm, sensitivity, specificity, weightedAccuracy

iris = datasets.load_iris()
x=pandas.DataFrame(iris.data, columns=['var1','var2','var3', 'var4'])
y=pandas.Series(iris.target, name='target')

response, _  = pandas.factorize(y)

xTrain, xTest, yTrain, yTest = cross_validation.train_test_split(x, response, test_size = .25, random_state = 36583)
print "building the first forest"
rf = RandomForestClassifier(n_estimators = 500, min_samples_split = 2, n_jobs = -1, verbose = 1)
rf.fit(xTrain, yTrain)
importances = pandas.DataFrame({'name':x.columns,'imp':rf.feature_importances_
                                }).sort(['imp'], ascending = False).reset_index(drop = True)

cm, sensitivity, specificity, weightedAccuracy = get_enhanced_confusion_matrix(yTest, rf.predict(xTest), [0,1])
numFeatures = len(x.columns)

rfeMatrix = pandas.DataFrame({'numFeatures':[numFeatures],
                              'weightedAccuracy':[weightedAccuracy],
                              'sensitivity':[sensitivity],
                              'specificity':[specificity]})

print "running RFE on  %d features"%numFeatures

for i in range(1,numFeatures,1):
    varsUsed = importances['name'][0:i]
    print "now using %d of %s features"%(len(varsUsed), numFeatures)
    xTrain, xTest, yTrain, yTest = cross_validation.train_test_split(x[varsUsed], response, test_size = .25)
    rf = RandomForestClassifier(n_estimators = 500, min_samples_split = 2,
                                n_jobs = -1, verbose = 1)
    rf.fit(xTrain, yTrain)
    cm, sensitivity, specificity, weightedAccuracy = get_enhanced_confusion_matrix(yTest, rf.predict(xTest), [0,1])
    print("\n"+str(cm))
    print('the sensitivity is %d percent'%(sensitivity * 100))
    print('the specificity is %d percent'%(specificity * 100))
    print('the weighted accuracy is %d percent'%(weightedAccuracy * 100))
    rfeMatrix = rfeMatrix.append(
                                pandas.DataFrame({'numFeatures':[len(varsUsed)],
                                'weightedAccuracy':[weightedAccuracy],
                                'sensitivity':[sensitivity],
                                'specificity':[specificity]}), ignore_index = True)
print("\n"+str(rfeMatrix))
maxAccuracy = rfeMatrix.weightedAccuracy.max()
maxAccuracyFeatures = min(rfeMatrix.numFeatures[rfeMatrix.weightedAccuracy == maxAccuracy])
featuresUsed = importances['name'][0:maxAccuracyFeatures].tolist()

print "the final features used are %s"%featuresUsed

rawDescription: Recursive feature elimination on Random Forest using scikit-learn


code:
children = {}
for obj in tree:
    children.setdefault(obj.parent, []).append(obj)

def preorder(root, children):
    yield root.value
    for child in children.get(root, []):
        for value in preorder(child, children):
            yield value

for root in children[None]:
    for value in preorder(root, children):
        print value

rawDescription: What is the most efficient way to traverse a tree in Python?


code:
from bs4 import BeautifulSoup as BS
url ="mydomain.com"
usock = urllib2.urlopen(url)
data = usock.read()
usock.close()
soup = BS(data)
print soup.find('font', {'class':'big'}).text

rawDescription: Getting html tag value in python

description: Getting html tag value in python


code:
import json

class decoder(json.JSONDecoder):

    def __init__(self, list_type=list,  **kwargs):
        json.JSONDecoder.__init__(self, **kwargs)
        # Use the custom JSONArray
        self.parse_array = self.JSONArray
        # Use the python implemenation of the scanner
        self.scan_once = json.scanner.py_make_scanner(self)
        self.list_type=list_type

    def JSONArray(self, s_and_end, scan_once, **kwargs):
        values, end = json.decoder.JSONArray(s_and_end, scan_once, **kwargs)
        return self.list_type(values), end

s = "[1, 2, 3, 4, 3, 2]"
print json.loads(s, cls=decoder) # [1, 2, 3, 4, 3, 2]
print json.loads(s, cls=decoder, list_type=list) # [1, 2, 3, 4, 3, 2]
print json.loads(s, cls=decoder, list_type=set) # set([1, 2, 3, 4])
print json.loads(s, cls=decoder, list_type=tuple) # set([1, 2, 3, 4, 3, 2])

rawDescription: Python: Change list type for json decoding


code:
def subStringMatchExact(target,key,matches=(),base=0):
    if find(target,key) != -1:
        matches += (find(target,key)+base,)
        base += find(target,key)+len(key)
        return subStringMatchExact(target[find(target,key)+len(key):],key,matches,base)
    else:
        print matches
        return matches

rawDescription: Python: "return <tuple>" keeps returning None


code:
import psutil

for pid in psutil.pids():
    p = psutil.Process(pid)
    if p.name() == "notepad.exe":
        print p.cmdline()

rawDescription: Getting which file is open in notepad using Python


code:
import SimpleHTTPServer
import SocketServer

PORT = 8888

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

rawDescription: How to access to a file on localhost

description: Access to a file on localhost


code:
import urllib.parse, urllib.request

params = { "SendXML": "<company><User><Username>username</Username><Password>passweord</Password></User><Content Type=sms>.." }
url_string = "http://api.company.com/SendMessageXml.ashx?%s" % (urllib.parse.urlencode(params))
s = ""
with urllib.request.urlopen(url_string) as url:
    s = url.read()

print s

rawDescription: white spaces in url

description: White spaces in url


code:
length = 0
max_length = 0 ##

for n in range(1,101):
    print "Sequence #:", n
    seq = [] ##
    while n != 1:
        print n,
        seq.append(n)  ##
        if n % 2 == 0:
           n = n / 2
           length = length + 1
        else:
            n = (n * 3) + 1
            length = length + 1
        if n == 1:
            print n
            seq.append(n) ##
            length = length + 1
    print "The sequence above contains", length, "numbers"

    if length > max_length:  ##
        max_length = length  ##
        max_seq = seq[:]     ##

    length = 0

print 'max length: ', max_length ## same as len(max_seq)
print 'max seq: ', max_seq       ##

rawDescription: Hailstone Sequence in Python

description: Hailstone Sequence in Python


code:
def getCommand(*args):
    global text
    x_pos = text.xview()[0]
    y_pos = text.yview()[0]
    command = text.get('insert linestart', 'insert').replace('command>', '', 1)
    print command
    text.insert(END, "\n")
    text.insert(END, "command>")
    return 'break'

rawDescription: Tkinter text widget cursor on particular line


code:
import os
import glob

def combine(arguments):
    all_files = []
    for arg in arguments:
        if '*' in arg or '?' in arg:
            # contains a wildcard character
            all_files.extend(glob.glob(arg))
        elif os.path.isdir(arg):
            # is a dictionary
            all_files.extend(glob.glob(os.path.join(arg, '*')))
        elif os.path.exists(arg):
            # is a file
            all_files.append(arg)
        else:
            # invalid?
            print '%s invalid' % arg
    return all_files

rawDescription: Combining file and directory selection options


code:
import pygame
import pygame.mixer

pygame.init()
pygame.mixer.init()

#-----

audio = pygame.mixer.Sound("example.ogg")
print 'sound length (in seconds):', audio.get_length()

audio_array = pygame.sndarray.array(audio)
print 'array length (in  bytes):', len(audio_array)

freq = len(audio_array)/audio.get_length() # frequences (loops per seconds)
print 'freq / bytes per second:', freq

#-----

clock = pygame.time.Clock()

#start_time = pygame.time.get_ticks()

raw_input("\npress ENTER ")

audio.play(-1)

for left, right in audio_array:
    #current_time = pygame.time.get_ticks()
    #play_time = current_time - start_time

    print left, right

    clock.tick(freq)

rawDescription: Translate sndarray into a number based on time in python?


code:
count = { 'a': 120, 'b': 120, 'c': 100 }

highest = max(count.values())

print [k for k,v in count.items() if v == highest]

rawDescription: Using Python's max to return two equally large values


code:
print 'omnia praeclara'
import multi4

print 'rara sunt'
import cmd2

class Prompt(cmd2.Cmd):

    def default(self, line):
        return cmd2.Cmd.default(self, line)
    prompt = '\n+++ '
    intro = '\n by that remembered or with that forgot.'
    def do_exit(self, line):
        return True

if __name__ == "__main__":
    multi4.init_manager()
    Prompt().cmdloop()

rawDescription: Multiprocessing not working with cmd2 module, import issue?


rawDescription: Splitting list Python

description: Splitting list Python


code:
import multiprocessing as mp
import time

class My_class(mp.Process):
    def __init__(self, name, num):
        super(My_class, self).__init__()
        self.name = name
        self.num = num

    def run(self):
        print self.name, "created and waiting for", str(self.num), "seconds"
        time.sleep(self.num)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class('p1', 20)
    p2=My_class('p2', 10)
    p1.start()
    p2.start()
    print 'main exited'

rawDescription: Python subclassing process with parameter


code:
import MySQLdb

conn = MySQLdb.connect(host="localhost", user="root", passwd="nobodyknow", db="amit")
cursor = conn.cursor()

stmt = "SELECT * FROM overflows"
cursor.execute(stmt)

# Fetch and output
result = cursor.fetchall()
print result

# get the number of rows
numrows = int(cursor.rowcount)

# Close connection
conn.close()

rawDescription: use python to access mysql

description: Use python to access mysql


code:
repos = ['/repo1', '/repo2', '/repo3']
# launch 3 async calls:
procs = [subprocess.Popen(['svn', 'update', repo]) for repo in repos]
# wait.
for proc in procs:
    proc.wait()
# check for results:
if any(proc.returncode != 0 for proc in procs):
    print 'Something failed'

rawDescription: Asynchronous background processes in Python?


code:
def checkSubnet(self, phrase):
    found = 0

    self.remote_file.seek(0)

    for line in self.remote_file:
        if phrase in line:
            found = 1
            print "FOUND IT"
            break

    return found

rawDescription: Going back to the start of a sftp remote-file


code:
import glob,csv,os, itertools

list_of_files = glob.glob('C:/test/*.csv')
print 'By the Power of the Python, Split these here files!'

directory = 'C:/test/conv/'
if not os.path.exists(directory):
    os.makedirs(directory)

for filename in list_of_files:
    storage = []
    specialStorage = []
    with open(filename,"r") as source:
        header_line = next(source)
        rdr= csv.reader( source, delimiter = ',',lineterminator='\n' )
        x=0
        resetValue = 0

        for row in itertools.islice(rdr,0,None):
            itemRow4 = row[4]

            if x == 0:
                previousitemRow4 = row[4]
                x = x+1

            outfileName=directory+previousitemRow4+'.csv'

            if previousitemRow4 == itemRow4:

                storage.append((row[8],row[11],row[6],row[0]))
                previousitemRow4 = itemRow4

            if previousitemRow4 != itemRow4:

                with open(outfileName,"a") as result:

                    wtr=csv.writer(result, lineterminator='\n')
                    previousitemRow4 = itemRow4

                    if len(specialStorage) !=0:
                        wtr.writerow(specialStorage)
                    wtr.writerows(storage)
                    storage = []

                specialStorage=(row[8],row[11],row[6],row[0])

        else:
            with open(outfileName,"a") as result:

                    wtr=csv.writer(result, lineterminator='\n')
                    previousitemRow4 = itemRow4
                    wtr.writerow(specialStorage)
                    wtr.writerows(storage)
                    storage = []

            print 'end of file reached'

rawDescription: Improve python csv processing loop

description: Improve python csv processing loop


code:
import subprocess, signal, time, os

cmd = "python target.py"
P = subprocess.Popen(cmd,shell=True)

while True:
   time.sleep(5)
   os.kill(P.pid, signal.SIGSTOP)
   print "doing something"
   os.kill(P.pid, signal.SIGCONT)

rawDescription: How do I get a subprocess to suspend execution of an external program every 5 seconds?

description: Get a subprocess to suspend execution of an external program every 5 seconds


code:
text = filtered_html.xpath('//text()')
print ''.join(t.strip() for t in text)  # prints "www.helloonline.com/"

rawDescription: Viewing html text between tags (python, lxml, urllib, xpath)


code:
f = open(filename,'rb')
m = hashlib.md5()
while True:
    ## Don't read the entire file at once...
    data = f.read(10240)
    if len(data) == 0:
        break
    m.update(data)
print m.hexdigest()

rawDescription: Python MD5 not matching md5 in terminal

description: Python MD5 not matching md5 in terminal


code:
"""Friendly Python SSH2 interface."""

import os
import tempfile
import paramiko

class Connection(object):
    """Connects and logs into the specified hostname.
    Arguments that are not given are guessed from the environment."""

    def __init__(self,
                 host,
                 username = None,
                 private_key = None,
                 password = None,
                 port = 22,
                 ):
        self._sftp_live = False
        self._sftp = None
        if not username:
            username = os.environ['LOGNAME']

        # Log to a temporary file.
        templog = tempfile.mkstemp('.txt', 'ssh-')[1]
        paramiko.util.log_to_file(templog)

        # Begin the SSH transport.
        self._transport = paramiko.Transport((host, port))
        self._tranport_live = True
        # Authenticate the transport.
        if password:
            # Using Password.
            self._transport.connect(username = username, password = password)
        else:
            # Use Private Key.
            if not private_key:
                # Try to use default key.
                if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
                    private_key = '~/.ssh/id_rsa'
                elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
                    private_key = '~/.ssh/id_dsa'
                else:
                    raise TypeError, "You have not specified a password or key."

            private_key_file = os.path.expanduser(private_key)
            rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
            self._transport.connect(username = username, pkey = rsa_key)

    def _sftp_connect(self):
        """Establish the SFTP connection."""
        if not self._sftp_live:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
            self._sftp_live = True

    def get(self, remotepath, localpath = None):
        """Copies a file between the remote host and the local host."""
        if not localpath:
            localpath = os.path.split(remotepath)[1]
        self._sftp_connect()
        self._sftp.get(remotepath, localpath)

    def put(self, localpath, remotepath = None):
        """Copies a file between the local host and the remote host."""
        if not remotepath:
            remotepath = os.path.split(localpath)[1]
        self._sftp_connect()
        self._sftp.put(localpath, remotepath)

    def execute(self, command):
        """Execute the given commands on a remote machine."""
        channel = self._transport.open_session()
        channel.exec_command(command)
        output = channel.makefile('rb', -1).readlines()
        if output:
            return output
        else:
            return channel.makefile_stderr('rb', -1).readlines()

    def close(self):
        """Closes the connection and cleans up."""
        # Close SFTP Connection.
        if self._sftp_live:
            self._sftp.close()
            self._sftp_live = False
        # Close the SSH Transport.
        if self._tranport_live:
            self._transport.close()
            self._tranport_live = False

    def __del__(self):
        """Attempt to clean up if not explicitly closed."""
        self.close()

def main():
    """Little test when called directly."""
    # Set these to your own details.
    myssh = Connection('example.com')
    myssh.put('ssh.py')
    myssh.close()

# start the ball rolling.
if __name__ == "__main__":
    main()

rawDescription: how to rsh ssh using python 2.3

description: Rsh ssh using python 2.3


code:
locale.setlocale(locale.LC_ALL, 'English')
'English_United States.1252'
print locale.format('%.2f', 123456789.0, True)
123,456,789.00

rawDescription: Thousand separator in format string with floats


code:
with open("test1.txt", "r") as f1:
    text = f1.read()
    print unicode(text, 'unicode_escape')
    str1 = u'\u26be\u26be\u26be'
    print(str1)

rawDescription: Why does printing a file with unicode characters does not produce the emojis?


code:
import mechanize

class HeadRequest(mechanize.Request):
    def get_method(self):
        return "HEAD"

request = HeadRequest("http://www.example.com/")
response = mechanize.urlopen(request)

print response.info()

rawDescription: How can I perform a HEAD request with the mechanize library?

description: Perform a HEAD request with the mechanize library


code:
from socketIO_client import SocketIO, BaseNamespace

class MainNamespace(BaseNamespace):

    def on_aaa(self, *args):
        print 'aaa', args

class ChatNamespace(BaseNamespace):

    def on_bbb(self, *args):
        print 'bbb', args

class NewsNamespace(BaseNamespace):

    def on_ccc(self, *args):
        print 'ccc', args

mainSocket = SocketIO('localhost', 8000, MainNamespace)
chatSocket = mainSocket.connect('/chat', ChatNamespace)
newsSocket = mainSocket.connect('/news', NewsNamespace)
mainSocket.wait()

rawDescription: python-websocket and socket.io namespace

description: Python-websocket and socket.io namespace


code:
goals = 0

numlist={}
for line in xl:
    numlist[line[0]]=int(line[1])#second element witch are goals

for player in numlist:
    if numlist[player] > goals:
        winner = player
        goals = numlist[player]
print goals, winner

rawDescription: list inspect second item print first item in list

description: List inspect second item print first item in list


code:
import csv
with open('myfile_0.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        print ', '.join(row)

# output:
# Time, InfD, Com, ComN
# 0, 3, 4, 0
# 1, 2, 5, 1

rawDescription: Python: how to read .csv file in an efficient way?


code:
import os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class myHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write("This is working")

def main():
    try:
        server = HTTPServer(("", 8080), myHandler)
        print "Sever is up.."
        server.serve_forever()
    except KeyboardInterrupt:
        print
        print "Bye, Bye!"
        server.socket.close()

if __name__ == "__main__":
    main()

description: PHP HTTP server? Ports 80, 443-444, 1000-3000, 8000-9000. (No-Apache)


code:
#!/usr/bin/env python2.7

def chan_values(num):
    """parses int into an array of True/False values for the channels"""
    channels = []

    while num > 0:
        channels.append(num%10==1)
        num /= 10

    channels += [False]*(8-len(channels))

    return channels

print chan_values(111)
print chan_values(10001000)

rawDescription: Python Parse Variable Number

description: Python Parse Variable Number


code:
#!/usr/bin/env python

APPNAME = "My App"
ICON = "/usr/share/pixmaps/firefox.png"

from gi.repository import AppIndicator3 as AI
from gi.repository import Gtk

def sayhello(item):
    print "menu item selected"

def scroll(aai, ind, steps):
    print "hello" # doesn't print anything

def makemenu():
    ' Set up the menu '
    menu = Gtk.Menu()
    check_item = Gtk.MenuItem('Check')
    exit_item = Gtk.MenuItem('Quit')
    check_item.connect('activate', sayhello)
    check_item.show()
    exit_item.connect('activate', Gtk.main_quit)
    exit_item.show()
    menu.append(check_item)
    menu.append(exit_item)
    menu.show()
    return menu

def startapp():
    ai = AI.Indicator.new(APPNAME, ICON, AI.IndicatorCategory.HARDWARE)
    ai.set_status(AI.IndicatorStatus.ACTIVE)
    ai.set_menu(makemenu())
    ai.connect("scroll-event", scroll)
    Gtk.main()

startapp()

rawDescription: Detect scroll wheel signal in system tray using Python AppIndicator in Ubuntu 12.04


code:
def is_dead(wr): print "blech"

class Foo(object):
    def bar(self): pass

method = Foo.bar
wr = weakref.ref(method, is_dead)
1 + 1
method = None

rawDescription: Weak reference to Python class method

description: Weak reference to Python class method


code:
def colnum_string(n):
    div=n
    string=""
    temp=0
    while div>0:
        module=(div-1)%26
        string=chr(65+module)+string
        div=int((div-module)/26)
    return string
print colnum_string(28)
#output:AB

rawDescription: Convert spreadsheet number to column letter


code:
from BeautifulSoup import BeautifulSoup

t="""

Points

yes me!

Bad

woo woo

"""

soup = BeautifulSoup(t)

for ta in soup.findAll('table'):
    for s in ta.findPreviousSiblings():
        if s.name == u'h2':
            if s.text == u'Points':
                print ta
            else:
                break;

rawDescription: Matching specific table within HTML, BeautifulSoup


code:
def whatisthis(s):
    if isinstance(s, str):
        print "ordinary string"
    elif isinstance(s, unicode):
        print "unicode string"
    else:
        print "not a string"

rawDescription: How do I check if a string is unicode or ascii?

description: Check if a string is unicode or ascii


code:
import os

if __name__=='__main__':
    PRJ_FLDR=os.path.dirname(os.path.abspath(__file__))
    print 'PRJ_FLDR=',PRJ_FLDR
    apptemplates = os.path.abspath(os.path.join(PRJ_FLDR, '../app/templates'))
    print 'apptemplates=',apptemplates

rawDescription: getting correct path of a folder in python

description: Getting correct path of a folder in python


rawDescription: Pandas combining rows with diffrent row Names in to new df


code:
def find_pairs(numbers, k):
    seen = set()
    for n in numbers:
        if k - n in seen:
            print n, k - n
        seen.add(n)

a = [1,4,45,6,10,12,3]
find_pairs(a, 16)
# 10 6
# 12 4

rawDescription: Sum to K using python duplicate entries

description: Sum to K using python duplicate entries


code:
def get_year():
    year = raw_input("Please enter the year: ")
    return int(year) #otherwise it is a string!

def get_month():
    month = raw_input("Please enter the month: ")
    return month

def leap_year(year):
    if year % 4 == 0:
        return True
    else:
        return False

def get_days(month,leap_year): #leap_year must be passes to this function
    #This checks for "january" and "february" with leap years
    #and falls back to last option on EVERYTHING ELSE like a feb without a leap year or even a "march"
    if month == "january":
        print "31 days"
    elif month == "february" and leap_year == True:
        print "29 days"
    else:
        print "28 days"

    #this is a separate block that runs AFTER the previous block
    if month == "march":
        print "31 days"
    elif month == "april":
        print "30 days"
    elif month == "may":
        print "31 days"
    elif month == "june":
        print "30 days"
    elif month == "july":
        print "31 days"
    elif month == "august":
        print "31 days"
    elif month == "september":
        print "30 days"
    elif month == "october":
        print "31 days"
    elif month == "november":
        print "30 days"
    elif month == "december":
        print "31 days"
    else:
        print "invalid input" #so that it doesnt fail silently when I enter 2

def main():
    user_year = get_year()
    user_month = get_month()
    leap_status = leap_year(user_year) #store the leap_year status to a variable
    get_days(user_month, leap_status)  #and then pass it to a function

main()

rawDescription: Calendar program help (string variables)


code:
from matplotlib import cm

p = plt.imshow(gauss, cmap=cm.Greys_r, vmin=025, vmax=1.)

rawDescription: change the python matplotlib colormap dynamic range for certain range

description: Change the python matplotlib colormap dynamic range for certain range


code:
import sys
from pygments import highlight
from pygments.formatters.terminal import TerminalFormatter
from pygments.lexer import RegexLexer
from pygments.token import Token

class ArithmeticLexer(RegexLexer):
    tokens = {
        'root': [
            (r'[ \n]', Token.Whitespace),
            (r'\d+', Token.Number),
            (r'\+', Token.Plus),
            (r'-', Token.Minus),
            (r'\*', Token.Multiply),
            (r'/', Token.Division),
        ]
    }

COLOR_SCHEME = {
    Token.Whitespace: ('', ''),
    Token.Number: ('darkgreen', 'green'),
    Token.Plus: ('darkred', 'red'),
    Token.Minus: ('darkblue', 'blue'),
    Token.Multiply: ('darkyellow', 'yellow'),
    Token.Division: ('brown', 'fushia'),
}

if __name__ == '__main__':
    with open(sys.argv[1], 'rb') as f:
        for line in f:
            line = highlight(line, ArithmeticLexer(), TerminalFormatter(colorscheme=COLOR_SCHEME))
            print line.strip()

rawDescription: Python: Write colored text in file

description: Python: Write colored text in file


code: print "{:{width}}{}".format("test", "string", width=10)

rawDescription: Python string formatting fill value as variable


code:
from serial import Serial
from fcntl import  ioctl
from termios import (
    TIOCMIWAIT,
    TIOCM_RNG,
    TIOCM_DSR,
    TIOCM_CD,
    TIOCM_CTS
)

ser = Serial('/dev/ttyUSB0')

wait_signals = (TIOCM_RNG |
                TIOCM_DSR |
                TIOCM_CD  |
                TIOCM_CTS)

if __name__ == '__main__':
    while True:
        ioctl(ser.fd, TIOCMIWAIT, wait_signals)
        print 'RI=%-5s - DSR=%-5s - CD=%-5s - CTS=%-5s' % (
            ser.getRI(),
            ser.getDSR(),
            ser.getCD(),
            ser.getCTS(),
        )

rawDescription: Python monitor serial port (RS-232) handshake signals


code:
for name in root.namelist():
    if name.find("debug") >= 0:
        for line in root.read(name).split("\n"):
            if line.find("BROKER_LOGON") >= 0:
                print line

rawDescription: Reading line by line from a zipped file in python


code:
# A sink that just prints the lines
@coroutine
def printer():
    while True:
        line = (yield)
        print line,

sources = [
    open('file1'),
    open('file2'),
    open('file3'),
    open('file4'),
    open('file5'),
    open('file6'),
    open('file7'),
]

output = printer()
while sources:
    for source in sources:
        line = source.next()
        if not line: # EOF
            sources.remove(source)
            source.close()
            continue
        output.send(line)

rawDescription: Python, read many files and merge the results


code:
import re
from collections import defaultdict

d = defaultdict(int)

with open('file.txt') as f:
    for line in f:
        qty, chr, _id = re.split('\s+', line.strip())
        d[(_id, chr)] += int(qty)

for (_id, chr), qty in d.iteritems():
    print '{} {}       {}'.format(qty, chr, _id)

rawDescription: clustering or grouping help in awk

description: Clustering or grouping help in awk


code:
print ftfy.ftfy(u"d\u00c3\u00a9cor")
print ftfy.ftfy(u"business\u00e2\u20ac\u2122 active accounts")
print ftfy.ftfy(u"the \u00e2\u20ac\u0153Made in the USA\u00e2\u20ac\u009d label")
print ftfy.ftfy(u"the \u00e2\u20ac\u0153Made in the USA\u00e2\u20ac\u009d label", uncurl_quotes=False)

rawDescription: In what world would \\u00c3\\u00a9 become é?


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

def tripleFunc(g):
    return lambda *args: 3 * g(*args)

newFunc = tripleFunc(f)
print newFunc(5)

rawDescription: Return function that modifies the value of the input function


code:
csv_path = "C:/Users/mydata.csv"
csv_database = open(csv_path, delimiters=";")
data_dict = csv.DictReader(csv_database, delimiter=";")

current_row = 0

number_list = []

for row in data_dict:

    current_row += 1 # Skip heading row

    if current_row == 1:
        continue

    number_list.append(row["Number"]) # Assuming the header of your column is "Number"

# Show results

for number in number_list:
    print number

rawDescription: How store column from a .csv file into a list?


code:
original = {232: [230, 231], 148: [144, 145, 147, 232], 231: [214, 215]}

def expand(data, number, dest):
    if data.get(number):
        res = []

        for n in data.get(number):
            expand(data, n, res)

        dest.append([number, res])
    else:
        dest.append(number)

    return dest

print expand(original, 148, [])
[[148, [144, 145, 147, [232, [230, [231, [214, 215]]]]]]]

rawDescription: How to recursively substitute a list of tuple pairs?

description: Recursively substitute a list of tuple pairs


code:
import unittest
import random

class NullWriter(object):
    def write(*_, **__):
        pass

    def flush(*_, **__):
        pass

SETUP_COUNTER = 0

class MyTestCase(unittest.TestCase):

    def setUp(self):
        global SETUP_COUNTER
        SETUP_COUNTER += 1

    def test_one(self):
        self.assertTrue(random.random() > 0.3)

    def test_two(self):
        # We just want to make sure this isn't run
        self.assertTrue(False, "This should not have been run")

def suite():
    tests = []
    for _ in range(100):
        tests.append('test_one')

    return unittest.TestSuite(map(MyTestCase, tests))

results = unittest.TextTestRunner(stream=NullWriter()).run(suite())
print dir(results)
print 'setUp was run', SETUP_COUNTER, 'times'

rawDescription: How to run python unittests repeatedly from a script and collect results

description: Run python unittests repeatedly from a script and collect results


code:
def xirr(transactions):
    years = [(ta[0] - transactions[0][0]).days / 365.0 for ta in transactions]
    residual = 1
    step = 0.05
    guess = 0.05
    epsilon = 0.0001
    limit = 10000
    while abs(residual) > epsilon and limit > 0:
        limit -= 1
        residual = 0.0
        for i, ta in enumerate(transactions):
            residual += ta[1] / pow(guess, years[i])
        if abs(residual) > epsilon:
            if residual > 0:
                guess += step
            else:
                guess -= step
                step /= 2.0
    return guess-1

from datetime import date
tas = [ (date(2010, 12, 29), -10000),
    (date(2012, 1, 25), 20),
    (date(2012, 3, 8), 10100)]
print xirr(tas) #0.0100612640381

rawDescription: financial python library that has xirr and xnpv function?

description: Financial python library that has xirr and xnpv function


code: print [day for day in days if day in content.lower()]

rawDescription: Output list element in Python function "any"


code:
i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

rawDescription: Python: Writing to and Reading from serial port


code:
f = open("file.dat")
st = os.fstat(f.fileno())

if f.closed:
    print "File " + f.name + " closed"
elif st.st_size>512:
    f.write(data)
    lastblock = newblock
    doAckLast()

rawDescription: Check Size of File Assigned to a Variable in Python 2


code:
import random
a=0
final=0
working=0

rolls = int(raw_input("How many dice do you want to roll? "))
sides = int(raw_input("How many sides? "))

while a<rolls:
    a=a+1
    working=random.randint(1, sides)
    final=final+working

print "Your total is:", final

rawDescription: Is there a random function in python that accepts variables?


code:
import serial
import struct
import time
#import csv
ser = serial.Serial("COM5",115200)
buffer = []
last_displayed = 0
while 1:
        val = ser.read(1)
        if (val == '\x7e'):
            val = ser.read(1)
            if (val == '\x5D'):
                val = ser.read(18)
                data = struct.unpack(">HHhhhhlh",val)
                cur_time = time.time()
                if cur_time - last_displayed >= .1:  # ~10Hz
                    print data
                    last_displayed = cur_time

rawDescription: Slowing down the displayed serial data in Python


code:
foo="bar"
vars()[foo] = 'qwertry'
print bar  # --> 'qwertry'

rawDescription: How to create variables from arguments in python

description: Create variables from arguments in python


code: print 'angle above the horizon:', satellite.alt

rawDescription: pyephem compute elevation angle

description: Pyephem compute elevation angle


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

class MyWorker(QObject):

    wait_for_input = pyqtSignal()
    done = pyqtSignal()

    @pyqtSlot()
    def firstWork(self):
        print 'doing first work'
        time.sleep(2)
        print 'first work done'
        self.wait_for_input.emit()

    @pyqtSlot()
    def secondWork(self):
        print 'doing second work'
        time.sleep(2)
        print 'second work done'
        self.done.emit()

class Window(QWidget):
    def __init__(self, parent = None):
        super(Window, self).__init__()

        self.initUi()
        self.setupThread()

    def initUi(self):
        layout = QVBoxLayout()
        self.button = QPushButton('User input')
        self.button.setEnabled(False)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.show()

    @pyqtSlot()
    def enableButton(self):
        self.button.setEnabled(True)

    @pyqtSlot()
    def done(self):
        self.button.setEnabled(False)

    def setupThread(self):
        self.thread = QThread()
        self.worker = MyWorker()

        self.worker.moveToThread(self.thread)

        self.thread.started.connect(self.worker.firstWork)
        self.button.clicked.connect(self.worker.secondWork)
        self.worker.wait_for_input.connect(self.enableButton)
        self.worker.done.connect(self.done)

        # Start thread
        self.thread.start()

if __name__ == "__main__":
    app = QApplication([])
    w = Window()
    app.exec_()

rawDescription: PyQt4 Wait in thread for user input from GUI


code:
import os,glob,fileinput
root="/tmp"
path=os.path.join(root,"dir")
alines=["line 1\n","line 2\n","line 3\n","line 4\n"]
os.chdir(path)
# for clients
for clientfile in glob.glob("*.client.log"):
    data=open(clientfile).readlines()
    data.append(alines)
    open("temp","w").write(''.join(data))
    os.rename("temp",clientfile)
for svrfile in glob.glob("*.server.log"):
    f=0
    for line in fileinput.FileInput(svrfile,inplace=1):
         ind=line.find("After-this")
         if ind!=-1 and not f:
             line=line[:ind+10] + ''.join(alines) + line[ind+10:]
             f=1
         print line

rawDescription: python file manipulation

description: Python file manipulation


code:
data = driver.find_elements_by_xpath('//*[@id="a-stockFinancials_tabs"]/div[2]/div[1]/table/tbody/tr/td')
for element in data:
    print element.get_attribute("innerHTML")

rawDescription: Xpath wildcard in selenium to capture multiple instances of results


code:
photos = [] # photos here
videos = [] # videos here

def move(type):
    for file in eval(type):
        print file

move('photos')
move('videos')

rawDescription: Python accessing a list by name

description: Python accessing a list by name


code:
import tempfile

fh = tempfile.NamedTemporaryFile()  # this creates an actual file in the temp directory
fh.write(my_string)
print fh.name
call_other_thing(fh.name)
fh.close()  # file is now deleted

rawDescription: Let string act as file

description: Let string act as file


code:
import time

while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        print line, # already has newline

rawDescription: Continuously Parse file in Python

description: Continuously Parse file in Python


code:
from bs4 import BeautifulSoup

# I put the HTML in a file, but this will work with a URL as well
with open('weather.html', 'r') as f:
  fcst = f.read()

# Turn the html into a navigable soup object
soup = BeautifulSoup(fcst)

# Define your zones
zones = ['AKZ214', 'AKZ215', 'AKZ213']

weatherFull = []

# This is a more Pythonic loop structure - instead of looping over
# a range of len(zones), simply iterate over each element itself
for zone in zones:
  # Here we use BS's built-in 'find' function to find the 'a' element
  # with a name = the zone in question (as this is the pattern).
  zone_node = soup.find('a', {'name': zone})

  # This loop will continue to cycle through the elements after the 'a'
  # tag until it hits another 'a' (this is highly structure dependent :) )
  while True:
    weatherFull.append(zone_node)
    # Set the tag node = to the next node
    zone_node = zone_node.nextSibling
    # If the next node's tag name = 'a', break out and go to the next zone
    if getattr(zone_node, 'name', None)  == 'a':
      break

# Process weatherFull however you like
print weatherFull

rawDescription: Multiple-line output from a single-line match in Python


code:
#cmn.py
import sys
print 'I am being imported by', sys._getframe(1).f_globals.get('__name__')

rawDescription: How to know who is importing me in python?

description: Know who is importing me in python


code:
import time
import numpy as np

webColours = np.array([
    [0,0,0],
    [0,0,128],
    [0,128,0],
    [0,128,128],
    [128,0,0],
    [128,0,128],
    [128,128,0],
    [192,192,192],
    [128,128,128],
    [0,0,255],
    [0,255,0],
    [0,255,255],
    [255,0,0],
    [255,0,255],
    [255,255,0],
    [255,255,255]
])

def getBaseColours(colours):
    # colours is 1000000x3
    # set up a distances array (16x1000000)
    distances = np.zeros((16, np.size(colours, 0)))
    for colour in xrange(16):
        # calculate distance of each input colour to this webColour
        distances[colour] = np.sum(abs(colours - webColours[colour]), 1)
    # which of 16 distances is the least for each of 1000000 colours
    return np.argmin(distances, 0)

startTime = time.time()
colour = np.array([134,234,43])
colours = np.tile(colour, (1000000, 1))
getBaseColours(colours)
print "Time: " + str(time.time()-startTime)

rawDescription: Python2 poor performance in simple math operations


code:
list_iter = iter([1, 2, 3, 4, 5])
for i in list_iter:
    print "not skipped: ", i
    if i == 3:
        print "skipped: ", next(list_iter, None)
        continue

rawDescription: How to make a double 'continue' in a loop?

description: Make a double 'continue' in a loop


code:
import numpy as np
matrix = np.loadtxt('matrix.txt', usecols=range(7))
print matrix

rawDescription: import text file as matrix in numpy

description: Import text file as matrix in numpy


code:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=login, password=password)
transport = ssh.get_transport()
channel_tcpdump = transport.open_session()
channel_tcpdump.get_pty()
channel_tcpdump.set_combine_stderr(True)

cmd = "tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap"        # command will never exit
channel_tcpdump.exec_command(cmd)  # will return instantly due to new thread being spawned.
# do something else
time.sleep(15)      # wait 15 seconds
_,stdout,_ = ssh.exec_command("pgrep tcpdump") # or explicitly pkill tcpdump
print stdout.read()     # other command, different shell
channel_tcpdump.close()     # close channel and let remote side terminate your proc.
time.sleep(10)

rawDescription: Process dies, if it is run via paramiko ssh session and with "&" in the end


code:
from billiard import current_process
from celery import task

@task
def print_info():
    # This will print an int in [0..concurrency[
    print current_process().index

rawDescription: Get worker ID in Celery

description: Get worker ID in Celery


code:
import serial
import sys
from time import sleep

try:
  ser = serial.Serial("/dev/ttyUSB0", 115200,timeout=0, parity=serial.PARITY_NONE,
                        stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
except:
  sys.exit("Error connecting device")

while True:
  queue = ser.inWaiting()
  if queue > 0:
    data = ser.read(1000)
    print data
  sleep(0.2)

rawDescription: No output from pyserial

description: No output from pyserial


code:
for keys, values in YourDictionaryHere.items():
    print keys, values

rawDescription: Python format count() method

description: Python format count() method


code:
import os
print "user who executed the code: %d" % os.getuid()
print "current effective user: %d" % os.geteuid()
if os.getuid() == 0:
    os.seteuid(65534) # user id of the user "nobody"
    print "current effective user: %d" % os.geteuid()
    # do what you need to do with non-root privileges here, e.g. write to a file
    print >> open("/tmp/foobar.txt", "w"), "hello world"
    os.seteuid(0)
print "current effective user: %d" % os.geteuid()

rawDescription: Python Disable and Enable Root Privileges


code:
#!/usr/bin/env python

import time, sys

def main():
    result = 1
    print 'starting time: ' , time.ctime()

    while(result):
        result = raw_input('press g to start timer, ctrl+c to stop.\n')

        if result is 'g':
            print_something()
            result = ''
        else:
            result = None
            time.stop()
            sys.exit()

def print_something():
    while 1:
        try:
            print 'the time: ' , time.ctime()
            time.sleep(1);
        except KeyboardInterrupt:
            break
main()

rawDescription: conditional keypress via command line

description: Conditional keypress via command line


code:
class Holder:
    a = 4

class A(Holder):
    pass

print A().a

rawDescription: One constant value for multiple classes

description: One constant value for multiple classes


code:
from PyQt4.QtCore import QCoreApplication, Qt
from PyQt4.QtGui import QListWidget, QListWidgetItem, QApplication

import sys

class MyList(QListWidget):
    def __init__(self):
        QListWidget.__init__(self)
        self.add_items()
        self.itemClicked.connect(self.item_click)

    def add_items(self):
        for item_text in ['item1', 'item2', 'item3']:
            item = QListWidgetItem(item_text)
            self.addItem(item)

    def item_click(self, item):
        print item, str(item.text())

if __name__ == '__main__':
    app = QApplication([])
    myList = MyList()
    myList.show()
    sys.exit(app.exec_())

rawDescription: How to send the selected item in the listWidget to another function as a parameter

description: Send the selected item in the listWidget to another function as a parameter


code:
class Foo(object):
    def __enter__(self):
        print 'Entered with block'
    def __exit__(self, *exc_info):
        print 'Exited with block'
        return False

with Foo():
    pass

rawDescription: Generator destruction when the break statement occurs


code:
import fileinput
for line in fileinput.input('text.txt', inplace=1):
    if line.startswith(('Extract',  'Text')):
        print '\n'+line+'\n'
    else:
        print line

rawDescription: Insert new line before multiple keywords in text file


code:
def myreadlines(f, newline):
  buf = ""
  while True:
    while newline in buf:
      pos = buf.index(newline)
      yield buf[:pos]
      buf = buf[pos + len(newline):]
    chunk = f.read(4096)
    if not chunk:
      yield buf
      break
    buf += chunk

with open('file') as f:
  for line in myreadlines(f, "."):
    print line

rawDescription: Reading a file with a specified delimiter for newline


code:
import os, zipfile
if 'filenames.txt' in os.listdir('.'):
    print 'file is in current dir'
else:
    zf = zipfile.ZipFile('files.zip')
    zf.extract('filenames.txt')

rawDescription: Check files in current directory

description: Check files in current directory


code:
import os

def locateA(pattern, root):
    file  = open(pattern, 'r')
    for path, dirs, files in os.walk(root):
        for word in files:
            file.seek(0)             # this line is new
            for line in file:
                if line.strip() in word:
                    print os.path.join(path, word), line.strip()

rawDescription: Py Search files in Folder and Subfolders


code:
import threading
import time
import SimpleHTTPServer
import SocketServer

PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)

def worker():

    # minimal web server.  serves files relative to the
    print "serving at port", PORT
    httpd.serve_forever()

def my_service():
    time.sleep(3)
    print "I am going down"
    httpd.shutdown()

h = threading.Thread(name='httpd', target=worker)
t = threading.Thread(name='timer', target=my_service)

h.start()
t.start()

rawDescription: In python, how to get a UDPServer to shutdown itself?


code:
buffer = [{"siteid": 1 , "distance": 2, "codes": "1|b|c", "urv": "545"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 3 , "distance": 2, "codes": "1|b|c", "urv": "546"}]
layer = [{"siteid": 2 }, {"siteid": 4 }, {"siteid": 3 }]
ids = [l['siteid'] for l in layer]
print [b for b in buffer if b['siteid'] in ids]

rawDescription: Two lists of dictionaries with some different keys, how to find intersection?


code:
import re

res = []
with open('test.txt') as f:
    res = sum([re.findall('\\THISTAG\[.*?\]{(.*?)}', line)
               for line in f if not line.startswith('%')
              ], [])

    print res # ['WANT0', 'WANT1', 'WANT2', 'WANT3', 'OBV_WANT']

rawDescription: Multi-line regex with multiple matches and negative conditions in python


code:
from argparse import ArgumentParser
import os
import signal
import subprocess
import itertools

# your argumentparser stuff goes here

def become_tty_fg():
    os.setpgrp()
    hdlr = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
    tty = os.open('/dev/tty', os.O_RDWR)
    os.tcsetpgrp(tty, os.getpgrp())
    signal.signal(signal.SIGTTOU, hdlr)

if __name__ == "__main__":
    args = parser.parse_args()

    if args.verbose: print "command is %s" % (args.command)
    if args.invert and args.limit==None:
        sys.exit("You must define a limit if you have inverted the return code test")

    for run_count in itertools.count():
        return_code = subprocess.call(args.command, close_fds=True,
                                      preexec_fn=become_tty_fg)
        if args.test == True: break
        if run_count >= args.limit: break
        if args.invert and return_code != 0: break
        elif not args.invert and return_code == 0: break

    print "Ran command %d times" % (run_count)

rawDescription: How do I set the terminal foreground process group for a process I'm running under a pty?

description: Set the terminal foreground process group for a process I'm running under a pty


code:
from PIL import Image
im = Image.open("dead_parrot.jpg") #Can be many different formats.
pix = im.load()
print im.size #Get the width and hight of the image for iterating over
print pix[x,y] #Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)

rawDescription: How can I read the RGB value of a given pixel in Python?

description: Read the RGB value of a given pixel in Python


code:
import threading, time

# Job
def Job(i, stop_event):
  print
  print 'Start CountJob nr:', i
  print
  while(not stop_event.is_set()):
    pass
  print 'Job', i, 'exiting'

def SuperJob(stop_event):
  for i in range(0,400):
    p = threading.Thread(target=Job, args=(i, stop_event))
    p.daemon = True
    p.start()

    if stop_event.is_set():
      return

# run the Jobs
stop_event = threading.Event()
p = threading.Thread(target=SuperJob, args=(stop_event,))
p.start()
time.sleep(10)
stop_event.set()

rawDescription: Run X Python threads for time period Y

description: Run X Python threads for time period Y


code:
infile = '/etc/dhcp/dhcpd.conf'
str = raw_input('Enter hostname to search: ');
def search_host( str, infile):
    start = False
    with open(infile, 'r') as f:
        for line in f:
            if re.search(str, line):
                start = True
            if start:
                print line
                if re.search('}', line):
                    break
search_host(str, infile);

rawDescription: editing dhcp.conf with python script

description: Editing dhcp.conf with python script


code:
small = None
larg = None
count = 0

while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break

    try:
        num = float (inp)

    except:
        print "Invalid number"

    if small is None or num < small:
        small = num

print "Done"
print small

rawDescription: Finding minimum of the input numbers

description: Finding minimum of the input numbers


code:
import cv2
import numpy as np

# total_frames = 50
cv2.namedWindow("Dragonfly Simulation")
cv2.startWindowThread()
# for i in range(total_frames):
while True:
    # do stuff
    img = np.random.randint(0,255,(200,300)).astype(np.uint8)
    cv2.imshow("Dragonfly Simulation", img)
    key = cv2.waitKey(200)
    print key
    if key in [ord('a'), 1048673]:
        print 'a pressed!'
    elif key in [27, 1048603]: # ESC key to abort, close window
        cv2.destroyAllWindows()
        break

# do the rest of processing after break
print 'results:'

rawDescription: OpenCV Python: How to detect if a window is closed?


code:
def progress_callback(current, total):
    print current
    print "==============="
    print total
    print "==============="
    if(current<total):
        print "unfinish"
    else:
        print "finish"
blob_service = BlobService(account_name=storage_account_name, account_key=storage_account_key)
blob_service.put_block_blob_from_path(container, blob_name, 'C:\\Users\\file_path',progress_callback=progress_callback)

rawDescription: How to check to make sure that blob_service.put_block_blob_from_path() was successful in python?

description: Check to make sure that blob_service.put_block_blob_from_path() was successful in python


code:
import urllib
import urlparse

url = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'
parts = urlparse.urlparse(url)
query_dict = urlparse.parse_qs(parts.query)  # {'wid': ['98'], 'hei': ['98']}
query_dict['wid'] = '360'
query_dict['hei'] = '360'
new_parts = list(parts)
new_parts[4] = urllib.urlencode(query_dict)
print urlparse.urlunparse(new_parts)

rawDescription: how do i replace a query with a new value in urlparse?

description: Replace a query with a new value in urlparse


code:
class PerformanceTestCase(TestCase):
    def setUp(self):
        self.begin_time = datetime.datetime.now()

    def tearDown(self):
        delta = datetime.datetime.now() - self.begin_time
        print 'Time taken', delta.seconds

        from django.db import connection
        print 'SQL queries', len(connection.queries)

rawDescription: Django performance testing suite that'll report on metrics (db queries etc.)


code:
import random
print random.choice([dog, cat])

rawDescription: How do I perform a random event in Python by picking a random variable?

description: Perform a random event in Python by picking a random variable


code:
#### Assume driver is your webdriver instance

text = 'http://some.website'
elements = driver.find_elements_by_class('wx-label')

for element in elements:
    if text in element.text:
        print element.text

rawDescription: Find partial content of text on page, then return the full contents of that <div> in Python with Selenium


code:
meas_times = [0, 2, 4, 6, 8, 11, 12, 14, 18, 20, 22]
meas_values = [-1, 0, 1, 0, -1, 0.5, 1, 0, 0, 1, 0]

def get_value(target_value):
    if target_value in meas_times:
        return meas_values[meas_times.index(target_value)]
    else:
        upper_index, upper_time = next((i, e) for i, e in enumerate(meas_times) if e > target_value)
        lower_value, upper_value = meas_values[upper_index - 1], meas_values[upper_index]
        abs_dt = float(abs(lower_value) + abs(upper_value)) / (upper_time - meas_times[upper_index - 1])

        if upper_value > lower_value:
            return lower_value + abs_dt * (target_value - meas_times[upper_index - 1])
        else:
            return lower_value - abs_dt * (target_value - meas_times[upper_index - 1])

target_times = [0, 5, 10, 15, 18, 20]
print map(get_value, target_times)
# [-1, 0.5, 0.0, 0.0, 0, 1]

rawDescription: Resampling data to target grid

description: Resampling data to target grid


code:
import shapely.geometry as shapgeo
import numpy as np
import cv2

def make_image():
    img = np.zeros((500, 500), np.uint8)
    white = 255
    cv2.ellipse( img, (250, 300), (100,70), 30, 0, 360, white, -1 )
    return img

if __name__ == '__main__':
    img = make_image()

    #Create a "coarse" ellipse
    _, contours0, hierarchy = cv2.findContours( img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]
    h, w = img.shape[:2]
    vis = np.zeros((h, w, 3), np.uint8)
    cv2.drawContours( vis, contours, -1, (128,255,255), 1)

    #Extract contour of ellipse
    cnt = np.vstack([contours[0]]).squeeze()

    #Determine centroid
    M = cv2.moments(cnt)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    print cx, cy

    #Draw full segment lines
    cv2.line(vis,(cx,0),(cx,w),(150,0,0),1)
    cv2.line(vis,(0,cy),(h,cy),(150,0,0),1)

    # Calculate intersections using Shapely
    # http://toblerity.org/shapely/manual.html
    PolygonEllipse= shapgeo.asLineString(cnt)
    PolygonVerticalLine=shapgeo.LineString([(cx,0),(cx,w)])
    PolygonHorizontalLine=shapgeo.LineString([(0,cy),(h,cy)])

    insecv= np.array(PolygonEllipse.intersection(PolygonVerticalLine)).astype(np.int)
    insech= np.array(PolygonEllipse.intersection(PolygonHorizontalLine)).astype(np.int)
    cv2.line(vis,(insecv[0,0], insecv[0,1]),(insecv[1,0], insecv[1,1]),(0,255,0),2)
    cv2.line(vis,(insech[0,0], insech[0,1]),(insech[1,0], insech[1,1]),(0,255,0),2)

    cv2.imshow('contours', vis)

    0xFF & cv2.waitKey()
    cv2.destroyAllWindows()

rawDescription: How to draw a line from the centroid of a contour to the perimeter of the contour?

description: Draw a line from the centroid of a contour to the perimeter of the contour


code:
users = {}

with open(text_file) as f:
    for line in f:
        parts = line.rstrip().split(', ')
        name = parts[0]
        users[name] = {}

        for rating in parts[1:]:
            song, score = rating.split(': ')
            song = song[1:-1]
            users[name][song] = score

print users

rawDescription: Reading from a text file into a dictionary with variable columns


code:
def some_func():
    print 'in some_func'
    return [1, 2, 3, 10]

for a in some_func():
    print a

rawDescription: python: does `for i in obj.func()` re-run `func` every iteration?

description: Python: does `for i in obj.func()` re-run `func` every iteration


code:
from ipaddr import ipaddr
raw = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
ip = ipaddr.IPv6Address(ipaddr.Bytes(raw))

print "IP is: " + str(ip)

original = bytes(ip.packed)

print "Original raw bytes: " + repr(original)

rawDescription: How do I get an IPv6 address from raw bytes?

description: Get an IPv6 address from raw bytes


code:
if event.type == pygame.KEYDOWN:
        if event.key==K_w:

            if map1[chary/32-1][charx/32] != 01:
                #chary -= 32
                WUP==True
            else:
                WUP==False
            #WUP=False
        if event.key==K_a:

            ALEFT=True
            if map1[chary/32][charx/32-1] != 01:
                #charx -= 32
                ALEFT==True
            else:
                WUP==False
            #charx -= 32
            #ALEFT=False
        if event.key==K_s:

            #SDOWN=True
            if map1[chary/32+1][charx/32] != 01:
                #chary += 32
                SDOWN=True
            else:
                SDOWN==False

        if event.key==K_d:

            if map1[chary/32][charx/32+1] != 01:
                #charx += 32
                DRIGHT==True
            else:
                DRIGHT==False

rawDescription: Collision with smooth movement?

description: Collision with smooth movement


code:
import os
print os.path.abspath('somefile')

rawDescription: What's the purpose of "import package"?

description: What's the purpose of "import package"


code:
def _(v):
    if type(v) == type(0.0):
        print "%e" % v
    else:
        print v

rawDescription: How do I control number formatting in the python interpreter?

description: Control number formatting in the python interpreter


code:
def print1(lists, index):
    if lists[index][3] == 0:
            try:
                    name=lists[index][0]
                    val = next(l[3] for l in lists[index:] if l[3]>0 and l[0]==name)
                    print lists[index][:-1] + [val]
            except:
                    print "No value found with same name where price>0"
    else:
            print lists[index]

A=[]
A.append(['Name1','date1','time1',0.00])
A.append(['Name1','date1','time2',0.00])
A.append(['Name2','date1','time1',10])
A.append(['Name1','date1','time3',20])
A.append(['Name1','date1','time4',30])
A.append(['Name1','date2','time5',40])
print1(A,1)

rawDescription: Python - Finding next element in list matching a condition. Substitute previous entry


code:
for path, dirs, files in os.walk("."):
    print path
    for file in files:
        print os.path.join(path, file)

rawDescription: Create a tree-style directory listing in Python


code:
scn = Scanner("localhost", "8834", login="root", password="password123")
reports = scn.reportList()
for r in reports:
    if r["readableName"] == SOME_NAME:
        print r["status"]

rawDescription: How to parse and return variables in python

description: Parse and return variables in python


code:
for x in range(100, 9, -1):
    for y in range(x, 9, -1):
        print 'file_10_' + str(y) + '.txt'

rawDescription: variable in range function

description: Variable in range function


code:
import unittest

class Abstract(object):
    def test_a(self):
        print "Running for class", self.__class__

class Test(Abstract, unittest.TestCase):
    pass

unittest.main()

rawDescription: abstract test case using python unittest

description: Abstract test case using python unittest


code:
def class_decorator(cls):
   for name, method in cls.__dict__.iteritems():
        if hasattr(method, "use_class"):
            # do something with the method and class
            print name, cls
   return cls

def method_decorator(view):
    # mark the method as something that requires view's class
    view.use_class = True
    return view

@class_decorator
class ModelA(object):
    @method_decorator
    def a_method(self):
        # do some stuff
        pass

rawDescription: Can a Python decorator of an instance method access the class?


code:
class Orange(Fruit):
    @staticmethod
    def mass(size):
        return size

a1 = None
try:
    Apple()
    Orange()
    a1 = Apple(type='fuji')
finally:
    del a1
    print gc.get_referrers(Apple)
    print gc.get_referrers(Orange)
    del Apple
    del Orange
    print Fruit.__subclasses__()
    gc.collect()
    sc = Fruit.__subclasses__()
    print sc
    if len(sc) > 0:
        print 42, gc.get_referrers(sc[0])

rawDescription: Garbage collection does not recognize del of a class after instance assignment


code:
a=[[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
a_r = a[::-1]  # reverse original list
for i in range(len(a_r)-1):
   for j in range(len(a_r[0])):
      a_r[i][j] = a_r[i][j] - a_r[i+1][j]

a=a_r[::-1]  # reverse result
for i in a: print i

rawDescription: Python revert accumulated matrix

description: Python revert accumulated matrix


code:
input_text = """Level: 1
Level: 1
Level: 2
Level: 2
Level: 2
Level: 3
Level: 3
Level: 1
Level: 2
Level: 2
Level: 1"""

# Parse input text into a list of levels (as int)
levels = []
for line in input_text.split('\n'):
    try:
        levels.append(int(line.split(': ', 1)[-1]))
    except Exception:
        pass # skip line

# Compute how many children each node has by counting the number of
# consecutive subsequent lines that belong to exactly the next level
counters = [0] * len(levels)
for i, level in enumerate(levels):
    for other in levels[i + 1:]:
        if other == level + 1:
            counters[i] += 1
        elif other == level:
            break

print '\n'.join(':%d' % c for c in counters)

rawDescription: Transforming level depth to subordinate count


code:
a = 'jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=1.1.1.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=server.name)))'
a = a.split('(')
host = a[4].replace(")","").replace("HOST=","")
port = a[5].replace(")","").replace("PORT=","")
s_name = a[7].replace(")","").replace("SERVICE_NAME=","")
url = host + ':' + port + '/' + s_name
print url

rawDescription: Old-Type JDBC URL Parsing using Python

description: Old-Type JDBC URL Parsing using Python


code:
name="Bobby"
number=2014

numberAsString=str(2014) #cast as string

print name[0:3] #gives you "Bob"
print numberAsString[-3:] #gives you "014"

rawDescription: How do I print out the first x amount of decimals/letters?

description: Print out the first x amount of decimals/letters


code:
import numpy as np
A = np.array([[3,1,-1], [1,3,-1], [-1,-1,5]])
w,v =  np.linalg.eig(A)
print w
idx = w.argsort()[::-1] #large to small
# idx = w.argsort() #small to large
w = w[idx]
v = v[:,idx]
print w # now they are ordered and you can iterate through your results to write them to your file

rawDescription: large matrix diagonalization python

description: Large matrix diagonalization python


code:
from astropy.table import Table
table = Table([[1, 2, 3], ['a', 'b', 'c']])
for row in table:
    print row['col0'], row['col1']

rawDescription: Iterate over rows of astropy.table Table object


code:
for key in prices:  # iterates through the keys of prices ["orange", "apple", "pear", "banana"] (though no ordering is guaranteed)
    print key # prints "orange"

    print "price: %s" % prices[key] # prints prices["orange"] (1.5)
    # which means it prints the value of the prices dict, orange key.

    print "stock: %s" % stock[key] # prints stock["orange"] (32)
    #which means it prints the value of the stock dict, orange key.

rawDescription: Key/Value Confusion in Python Dictionaries


code:
a=dict(b=3, c='d', x=10)
print ",".join(['{0}=${1}'.format(k, i) for i, k in enumerate(sorted(a))])

rawDescription: Python dict: Creating a prepared statement


code:
import re
s = u'LastName FirstName (Department / Subdepartment)'
print re.sub(r'([()])', r'\\\1', s)

rawDescription: Escape (Insert backslash) before brackets in a Python string