code:
import requests
import re
from bs4 import BeautifulSoup

r = requests.get('http://www.compareremit.com')
data = r.text

soup = BeautifulSoup(data)
for rate in soup.find_all('div',{"class":"c_logo_box"}):
    print rate.a.img['alt']
    print rate.span.text

rawDescription: Python scraping (Beautiful Soup) to obtain data from this HTML


code:
data = [[1, "name email@email.com address"], [2, "name2 email@@email2.com address"],[3, "name1 name2 name3 email@email.com email2 email3 address1 address2 address3"]]

for ind,d in enumerate(data):
         data[ind]=[d[0]," ".join([x for x in d[1].split() if "@" not in x])] # add the int first then change elements from  index 1.
print data

[[1, 'name address'], [2, 'name2 address'], [3, 'name1 name2 name3 email2 email3 address1 address2 address3']]

rawDescription: Remove a specific phrase from a list of lists


code:
import pickle
from collections import Counter
counts = Counter('the quick brown fox jumps over the lazy dog')
with open('/tmp/demo.pickle', 'wb') as outputfile:
    pickle.dump(counts, outputfile)

del counts
with open('/tmp/demo.pickle', 'rb') as inputfile:
    print pickle.load(counts)

with open('/tmp/demo.pickle', 'rb') as inputfile:
    print pickle.load(inputfile)

rawDescription: how to write the collections.Counter object to a file in python and then reload it from the file and use it as a counter object

description: Write the collections.Counter object to a file in python and then reload it from the file and use it as a counter object


code:
from django.db.models import Sum

annotated_projects = Project.objects.all().annotate(cost_sum=Sum('cost__cost'))
for project in annotated_projects:
    print project.title, project.cost_sum

rawDescription: Django: Summing values

description: Django: Summing values


code:
import threading
import Queue
import time

class Worker(threading.Thread):
  def __init__(self, q):
    threading.Thread.__init__(self)

    self._q = q

  def run(self):
    # here, worker does its job
    # results are pushed to the shared queue
    while True:
      print 'I am working'
      time.sleep(1)
      result = time.time() # just an example
      self._q.put(result)

def process(q):
  while True:
    if q.empty():
      time.sleep(10)
    print 'I am processing'
    worker_result = q.get()
    # do whatever you want with the result...
    print "  ", worker_result

if __name__ == '__main__':
   shared_queue = Queue.Queue()
   worker = Worker(shared_queue)
   worker.start()
   process(shared_queue)

rawDescription: Python Multithreading - Schedule Queue

description: Python Multithreading - Schedule Queue


code:
input_number = 220

print [i for i in xrange(input_number.bit_length()) if ((1 << i) & input_number)]

rawDescription: Return list of active bits

description: Return list of active bits


code:
import re
pattern = re.compile('prod/([\d_]+)/x/blah')
query   = "http://www.example.com/blah/prod/4_2343_234/x/blah.html"
result  = pattern.search(query).group(1)
print result

rawDescription: Get value from a dynamic url

description: Get value from a dynamic url


code:
W = [['a', 'b', 'b', 'b', 'a'],
     ['a', 'a', 'a', 'a', 'b'],
     ['a', 'b', 'a', 'b', 'b'],
     ['a', 'a', 'a', 'b', 'b'],
     ['b', 'b', 'b', 'b', 'b'],
     ['b', 'b', 'b', 'b', 'b']]

def count_matrix(W, r,c, ch):
    ref=(-1,0,1)
    matches=[]
    for dr, dc in [(a, b) for a in ref for b in ref if (a,b)!=(0,0)]:
        if r+dr>=0 and c+dc>=0:
            try:
                matches.append(W[r+dr][c+dc])
            except IndexError:
                pass
    return matches.count(ch)

print count_matrix(W,0,0,'a')   # correctly handles upper LH
# 2
print count_matrix(W,4,1,'a')
# 3

rawDescription: Python and matrix

description: Python and matrix


code:
import datetime
icmpstamp = datetime.datetime.fromtimestamp(1344448836.482289)
icmpstamp
print icmpstamp
datastamp = datetime.datetime.fromtimestamp(1344448832.707281)
datastamp
print datastamp
difference = icmpstamp - datastamp
difference
print difference

rawDescription: time unit in tcpdump timestamps

description: Time unit in tcpdump timestamps


code:
chars = u"¿?!"
print chars[0]

rawDescription: Non-ASCII characters being converted to multi-byte ASCII


code:
from scrapy.spider import Spider
from scrapy.selector import Selector

class ExampleSpider(Spider):
    name = "exampleSpider"
    start_urls = ["http://example.com/sitemap.html"]

    def parse(self, response):
        sel = Selector(response)
        results = sel.xpath("//*[contains(@id, 'result_')]")
        for result in results:
            #do something with the results here
            print result.extract()

rawDescription: Select all element with particular id patern in python scrapy


code:
TCid = "TC1394"
#Generate random number of steps
def generate_Steps():
    list_Steps=[]
    import random
    n_steps=random.randrange(1,15)
    for i in range(n_steps):
        Step={'StepIndex':i+1}
        Step['Input']="Step Input for step %d" % (i+1)
        Step['ExpectedResult']="Expected Result for step %d" % (i+1)
        list_Steps.append(Step)
    print "Using random list of %d Test Steps" % (n_steps)
    return list_Steps

#Update steps
def update_TestSteps(TCid, Steps):
    try:
        #Get number of existing steps
        testcase=rally.get('TestCase', query='FormattedID = %s' % TCid, instance=True)
        print "Updating steps for Test Case %s" % testcase.FormattedID
        list_steps=sorted(testcase.Steps, key=lambda step: step.StepIndex)
        #Calculate what to do on the steps (how many to update, create, or delete)
        nb_steps = { 'Rally':len(testcase.Steps), 'HTML':len(Steps) }
        nb_steps['toUpdate'] = min(nb_steps['Rally'], nb_steps['HTML'])
        nb_steps['toCreate'] = nb_steps['HTML'] - nb_steps['toUpdate']
        nb_steps['toDelete'] = nb_steps['Rally'] - nb_steps['toUpdate']

        #Update content of existing steps with steps from test case
        for StepIndex in range(nb_steps['toUpdate']):
            step=list_steps[StepIndex]
            teststep_fields = Steps[StepIndex]
            (teststep_fields['TestCase'], teststep_fields['ObjectID']) = (testcase.ref, step.oid)
            teststep = rally.update('TestCaseStep', teststep_fields)
        #Create new test steps when required
        for StepIndex in range(nb_steps['toCreate']):
            teststep_fields = Steps[StepIndex+nb_steps['toUpdate']]
            teststep_fields['TestCase'] = testcase.ref
            teststep = rally.put('TestCaseStep', teststep_fields)
        #Delete extra test steps
        for StepIndex in range(nb_steps['toDelete']):
            step=list_steps[StepIndex+nb_steps['toUpdate']]
            rally.delete('TestCaseStep', step.oid)

        #Print message for end of test step update
        message="Updated test steps for TestCase %s" % testcase.FormattedID
        message+=" (steps created: {toCreate}, updated: {toUpdate}, deleted: {toDelete})".format(**nb_steps)
        print message

    except RallyRESTAPIError, details:
        sys.stderr.write('Rally Error during update of Test Step:  %s \n\n' % details)

#Update random list of Steps
update_TestSteps(TCid, generate_Steps())

rawDescription: How to update steps of Test Cases in Rally by using the Python API (pyral)

description: Update steps of Test Cases in Rally by using the Python API (pyral)


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import win32clipboard

element.send_keys(Keys.CONTROL, 'a') #highlight all in box
element.send_keys(Keys.CONTROL, 'c') #copy

win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData() #paste
win32clipboard.CloseClipboard()

print text

rawDescription: Copy text from an input field and save it into a variable with python


code:
valueNeeded = soup.find_all('td', attrs={'class':'same_class_name'})
for tag in valueNeeded:
    print tag.text.strip()

rawDescription: Python BeautifulSoup html tag parsing issue


code:
def derivative(f, x, h):
  return (f(x+h) - f(x-h)) / (2.0*h)

def generateNthrootFunc():
   root = int(raw_input("Please Enter a nth root (n) : "))
   number =  int(raw_input("Please Enter a number (x): "))
   def nthroot(x):
      return x**(root) - (number)
   return nthroot

def newraph(f, x0, h):
   Xold = x0
   Xnew = Xold + 10* h
   while (abs(Xold - Xnew) > h):
      Xold = Xnew
      Xnew = Xold - f(Xnew) / derivative(f, Xold, h)  #NewtonRaphson formula
   return Xnew

root = newraph(generateNthrootFunc(), 1, 0.000001)    # call the solver
print "The root is", root

rawDescription: Input in Functions

description: Input in Functions


code:
import c4d
from c4d import documents,UVWTag
from c4d.utils import Deg
from c4d import symbols as sy, plugins, utils, bitmaps, gui
import math

def BlenderExport():
    if not op: return
    if op.GetType() != 5100:
        print 'Selected Object is not an editable mesh'
        return
    unit = 0.001#for scale
    foffset = 1#for frames
    bd = doc.GetRenderBaseDraw()
    scr = bd.GetFrameScreen()
    rd = doc.GetActiveRenderData()
    sizeX = int(rd[sy.RDATA_XRES_VIRTUAL])
    sizeY = int(rd[sy.RDATA_YRES_VIRTUAL])
    name  = op.GetName()
    fps   = doc.GetFps()
    sFrame= doc.GetMinTime().GetFrame(fps)
    eFrame= doc.GetMaxTime().GetFrame(fps)
    code  = 'import Blender\nfrom Blender import *\nimport bpy\nfrom Blender.Mathutils import *\n\nscn = bpy.data.scenes.active\ncontext=scn.getRenderingContext()\ncontext.fps = '+str(fps)+'\ncontext.sFrame = '+str(sFrame)+'\ncontext.eFrame = '+str(eFrame)+'\ncontext.sizeX = '+str(sizeX)+'\ncontext.sizeY = ' + str(sizeY) + '\n'

    def GetMesh(code):
        # goto 0
        doc.SetTime(c4d.BaseTime(0, fps))
        c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
        c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
        doc.SetTime(doc.GetTime())
        c4d.EventAdd(c4d.EVENT_ANIMATE)

        code      += 'editmode = Window.EditMode()\nif editmode:\tWindow.EditMode(0)\n'
        coords4D   = op.GetPointAll()
        coords     = 'coords = ['
        uvw        = 0
        uvs        = 'uvs = ['
        for tag in op.GetTags():
            if tag.GetName() == "UVW":
                uvw = tag
        for c in coords4D:
            coords += '['+str(c.x*unit)+','+str(c.z*unit)+','+str(c.y*unit)+'],'
        coords     = coords.rpartition(',')[0] + ']\n'
        faces4D    = op.GetAllPolygons()
        fcount     = 0
        faces      = 'faces = ['
        for f in faces4D:
            faces  += '['+str(f)+'],'
            uv = uvw.Get(fcount);
            uvs  += '[Vector('+str(uv[0].x)+','+str(1.0-uv[0].y)+'),Vector('+str(uv[1].x)+','+str(1.0-uv[1].y)+'),Vector('+str(uv[2].x)+','+str(1.0-uv[2].y)+')],'
            fcount += 1

        faces      = faces.rpartition(',')[0] + ']\n'
        uvs        = uvs.rpartition(',')[0] + ']\n'

        code       = code + coords + faces + uvs
        code      += "c4dmesh = bpy.data.meshes.new('"+name+"_mesh')\nc4dmesh.verts.extend(coords)\nc4dmesh.faces.extend(faces)\n\nob = scn.objects.new(c4dmesh,'"+name+"_obj')\nc4dmesh.flipNormals()\n\nif editmode:\tWindow.EditMode(1)\n\n"
        code      += "c4dmesh.quadToTriangle()\nc4dmesh.addUVLayer('c4duv')\n"
        code      += "for f in range(0,"+str(fcount)+"):\n\tc4dmesh.faces[f].uv = uvs[f]\n"

        return code

    def GetIPOKeys(code):
        # store properties for tracks
        tracks   = op.GetCTracks()
        # 0,1,2 = Position, 3,4,5 = Scale, 6,7,8 = Rotation, 9 = PLA
        # props = [[lx,f],[ly,f],[lz,f],[sx,f],[sy,f],[sz,f],[rx,f],[ry,f],[rz,f]]
        try:
            props = []
            trackIDs = [3,4,5,6,7,8,0,2,1]
            propVals = ['LocX','LocZ','LocY','SizeX','SizeY','SizeZ','RotZ','RotX','RotY']
            propIPOs = ['Ipo.OB_LOCX','Ipo.OB_LOCZ','Ipo.OB_LOCY','Ipo.OB_SCALEX','Ipo.OB_SCALEY','Ipo.OB_SCALEY','Ipo.OB_ROTZ','Ipo.OB_ROTX','Ipo.OB_ROTY']
            for t in range(0,9):
                props.append([[],[]])
                curve    = tracks[t].GetCurve()
                keyCount = curve.GetKeyCount()
                for k in range(0,keyCount):
                        key   = curve.GetKey(k)
                        props[t][0].append(key.GetValue())
                        props[t][1].append(key.GetTime().GetFrame(fps))
            # find the max key
            maxProp = max(enumerate(props), key = lambda tup: len(tup[1]))[1][1]
            maxKeys = len(maxProp)
            # loop through tracks and keys
            for key in range(0,maxKeys):
                code += "Blender.Set('curframe',"+str(maxProp[key])+")\n"
                for track in trackIDs:
                    if(key < len(props[track][0])):
                        code += "ob."+propVals[track] + " = " + str(props[track][0][key]) + '\n'
                        code += 'key = ob.insertIpoKey(' + propIPOs[track] + ')\n'
        except:
            pass
        return code
    #     mesh/morph animation -> mesh always has the same number of verts
    def GetShapeKeys(code):
        track = 0;
        tracks = op.GetCTracks()
        for t in tracks:
            if(t.GetName() == 'PLA'):   track = t
        # track    = op.GetCTracks()[9]
        if track != 0:
            curve    = track.GetCurve()
            keyCount = curve.GetKeyCount()
            verts    = []
            frames   = []
            vertsNum  = op.GetPointCount()
            ctime = doc.GetTime()

            for k in range(1,keyCount):
                key = curve.GetKey(k)
                frames.append(key.GetTime().GetFrame(fps))
                c4d.StatusSetBar(100*(k/keyCount))
                doc.SetTime(key.GetTime())
                c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
                c4dvecs = op.GetPointAll();
                blendvecs = []
                for v in c4dvecs:
                    blendvecs.append([v.x*unit,v.z*unit,v.y*unit])
                verts.append(blendvecs)
                c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
            doc.SetTime(ctime)
            c4d.EventAdd(c4d.EVENT_ANIMATE)
            c4d.StatusClear()

            code += '\n\n# shape keys\nverts = ' + str(verts) + '\n'
            code += "if(ob.activeShape == 0):\n\tob.insertShapeKey()\n\n"
            for f in range(0,len(frames)):
                kNum = str(f+1)
                code += "if editmode:   Window.EditMode(0)\n"
                code += "for v in range(0,"+str(vertsNum)+"):\n\tc4dmesh.verts[v].co.x = verts["+str(f)+"][v][0]\n\tc4dmesh.verts[v].co.y = verts["+str(f)+"][v][1]\n\tc4dmesh.verts[v].co.z = verts["+str(f)+"][v][2]\n"
                code += "c4dmesh.calcNormals()\n"
                code += "ob.insertShapeKey()\n"
                code += "if editmode:   Window.EditMode(1)\n"
                code += "shapeKey = ob.getData().getKey()\n"
                code += "newIpo = Ipo.New('Key','newIpo')\n"
                code += "if(shapeKey.ipo == None):   shapeKey.ipo = newIpo\n"
                code += "if(shapeKey.ipo['Key "+kNum+"'] == None):   shapeKey.ipo.addCurve('Key "+kNum+"')\n"
                if(f == 0):  code += "shapeKey.ipo['Key "+kNum+"'].append(BezTriple.New(1.0,0.0,0.0))\n"
                if(f > 0):  code += "shapeKey.ipo['Key "+kNum+"'].append(BezTriple.New("+str(float(frames[f-1]))+",0.0,0.0))\n"
                code += "shapeKey.ipo['Key "+kNum+"'].append(BezTriple.New("+str(float(frames[f]))+",1.0,0.0))\n"
        else:
            #no PLA tracks, look for morph tag
            vertsNum  = op.GetPointCount()
            for tag in op.GetTags():
                if tag.GetType() == 1019633:
                    # print tag[sy.MORPHTAG_MORPHS]
                    '''
                    work around
                    1. store first key for each track curve
                    2. set the first key value to 1 for the 1st track and 0 for the others
                    3. store the mesh vertices -> track name verts = []
                    4. after all track verts are stored, restore the original values
                    5. write the the curve keys for blender shape keys
                    '''
                    code += "if(ob.activeShape == 0):\n\tob.insertShapeKey()\n\n"
                    tc = 0
                    tcs = str(tc+1)
                    for track in tag.GetCTracks():
                        curve = track.GetCurve()
                        value = curve.GetKey(0).GetValue()
                        curve.GetKey(0).SetValue(curve,1.0)
                        print track.GetName()
                        doc.SetTime(c4d.BaseTime(0, fps))
                        c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
                        c4dvecs = op.GetPointAll();
                        blendverts = []
                        for v in c4dvecs:
                            blendverts.append([v.x*unit,v.z*unit,v.y*unit])
                        code += "Key"+tcs+"verts = " + str(blendverts)+"\n"
                        code += "if editmode:   Window.EditMode(0)\n"
                        code += "for v in range(0,"+str(vertsNum)+"):\n\tc4dmesh.verts[v].co.x = Key"+tcs+"verts[v][0]\n\tc4dmesh.verts[v].co.y = Key"+tcs+"verts[v][1]\n\tc4dmesh.verts[v].co.z = Key"+tcs+"verts[v][2]\n"
                        code += "c4dmesh.calcNormals()\n"
                        code += "ob.insertShapeKey()\n"
                        code += "if editmode:   Window.EditMode(1)\n"
                        code += "shapeKey = ob.getData().getKey()\n"
                        code += "newIpo = Ipo.New('Key','newIpo')\n"
                        code += "if(shapeKey.ipo == None):   shapeKey.ipo = newIpo\n"
                        code += "if(shapeKey.ipo['Key "+tcs+"'] == None):   shapeKey.ipo.addCurve('Key "+tcs+"')\n"
                        print op.GetPointAll()
                        c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
                        curve.GetKey(0).SetValue(curve,value)
                        keyCount = curve.GetKeyCount()
                        for k in range(0,keyCount):
                            key = curve.GetKey(k)
                            value = key.GetValue()
                            frame = key.GetTime().GetFrame(fps)
                            code += "shapeKey.ipo['Key "+tcs+"'].append(BezTriple.New("+str(float(frame))+","+str(value)+",0.0))\n"
                        tc += 1
                        tcs = str(tc+1)

                    c4d.EventAdd(c4d.EVENT_ANIMATE)
        return code

    def GetCamera(code):
        bd = doc.GetRenderBaseDraw()
        cp = bd.GetSceneCamera(doc)
        if cp is None: cp = bd.GetEditorCamera()
        fov = Deg(cp[sy.CAMERAOBJECT_FOV])
        pos = cp.GetPos()
        rot = cp.GetRot()
        code += "\nc4dCam = Camera.New('persp','c4d_"+cp.GetName()+"')\nc4dCam.drawPassepartout = True\nc4dCam.alpha = 0.5\nc4dCam.drawLimits = 1\nc4dCam.dofDist = 100.0\n"
        code += "c4dCam.angle = "+str(fov)+"\nc4dCamLens = c4dCam.lens\nc4dCam.lens = c4dCamLens\nWindow.RedrawAll()\nc4dCamObj = scn.objects.new(c4dCam)\n"
        code += "c4dCamObj.setLocation("+str([pos.x,pos.z,pos.y])+")\n"
        code += "c4dCamObj.setEuler("+str([rot.x+(math.pi*.5),rot.y,rot.z])+")\n"
        code += "scn.setCurrentCamera(c4dCamObj)\n"
        return code

    code = GetMesh(code)
    code = GetIPOKeys(code)
    code = GetShapeKeys(code)
    code = GetCamera(code)

    file = open(doc.GetDocumentPath()+'/'+op.GetName()+'_export.py','w')
    file.write(code)
    file.close()

BlenderExport()

rawDescription: 3d animation from cinema4d to blender

description: 3d animation from cinema4d to blender


code:
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
ks = importr('ks')

kde_test = ks.kde_test

matr1 = [1., 3., 1., 3., 0.2, 1.5, 0.5, 1.3]
matr2 = [1., 3., 1., 3., 0.2, 1.5, 0.5, 1.3, 0.5, 4.6]

m1 = robjects.r.matrix(robjects.FloatVector(matr1), nrow=int(len(matr1)/2), byrow=True)
m2 = robjects.r.matrix(robjects.FloatVector(matr2), nrow=int(len(matr2)/2), byrow=True)

res = kde_test(x1 = m1, x2 = m2)

pval = res.rx2('pvalue')

print float(str(pval)[4:])

rawDescription: Pass list from python to R through rpy2

description: Pass list from python to R through rpy2


code:
import Tkinter as tk
from guiLoop import guiLoop # https://gist.github.com/niccokunzmann/8673951#file-guiloop-py

direction = 0
pos = 0 # the position should increase and decrease depending on left and right
# I assume pos can be ... -3 -2 -1 0 1 2 3 ...

@guiLoop
def move_dir():
    global pos
    while True: # edit 1: now looping always
        print 'moving', direction
        pos = pos + direction
        yield 0.5 # move once every 0.5 seconds

def kp(event):
    global direction # edit 2
    if event.keysym == 'Right':
        direction  = 1 # right is positive
    elif event.keysym == 'Left':
        direction = -1
    elif event.keysym == 'Space':
        direction = 0 # 0 is do not move
    elif event.keysym == 'Escape':
        root.destroy()

def kr(event):
    global direction
    direction = 0

root = tk.Tk()
print( "Press arrow key (Escape key to exit):" )
root.bind_all('<KeyPress>', kp)
root.bind_all('<KeyRelease>', kr)
move_dir(root)
root.mainloop()

rawDescription: Tkinter getting key pressed event from a function


code:
def foo():
    print "Yay!"

if True and foo() is None:
    print "indeed"

if False and foo() is None:
    print "nope"

rawDescription: "if var and var2 == getSomeValue()" in python - if the first is false, is the second statement evaluated?'


code:
dictionary = {'a': 5, 'b': 8, 'c':15}
sum = 0
for (key, value) in dictionary.items(): sum += value
percentage = dictionary['a'] / (sum + 0.0)
print "percentage of '%s' is %.2f %%" % ('a' , percentage*100)

rawDescription: Get percentage of a letter in python dictionary


code:
#!/usr/bin/env python

import sys

def main():
    filename = "my_dict.txt"
    listfile = open(filename)
    # doesn't create an itermediate list
    listDM = set(line.strip() for line in listfile)
    # less Pythonic but significantly faster
    # still doesn't create an intermediate list
    # listDM = set(imap(str.strip, listfile))
    listfile.close()
    for line in sys.stdin:
        line = line.strip()
        if line in listDM:
            print  '%s\t%d' % (line, 1)

if __name__ == '__main__':
    main()

rawDescription: Problem in creating a separate function to read file in Hadoop Streaming


code:
from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

for row in grouper(hex_, 10, ""):
    print "".join(row)

rawDescription: Generate a list of all the hex but those provided


code:
class A:
 def a(self):
  print "Hello"

B = [A() for i in xrange(10)]
map(lambda a: a.a(), B)

rawDescription: Calling a class functions using map

description: Calling a class functions using map


rawDescription: Create tab separated print output from a list of tuples python


code:
class Foo(object):
    def __foo(self):
        print "foo"
    def main(self):
        self.__foo()

class Bar(Foo):
    def __foo(self):
        print "bar"

bar = Bar()
bar.main()
# This will print "foo" and not "bar".

rawDescription: Python naming conventions for attributes and methods meant to be overwritten


code:
for thing in doubleDict.itervalues():
        print thing
        print thing['type']
        print thing['name']
        print thing['species']

rawDescription: iterating a two dimentional dict to remove a dict

description: Iterating a two dimentional dict to remove a dict


code:
def del_col(in_path):
    # read file into memory
    file_obj = open(in_path, 'rb')
    readfile = csv.reader(file_obj, delimiter='\t')

    # delete the status column here:

    vals = [row[:1] + row[2:] for row in readfile]
    print vals
    file_obj.close()  # if you are going to use the same file name, close and re-open

    # Now write csv to new file:
    # write data to file
    out_path = in_path + "_out.dat"
    out_obj = open(out_path, 'w')
    writefile = csv.writer(out_obj, delimiter='\t')
    writefile.writerows(vals)
    out_obj.close()

rawDescription: Clear or delete 2nd column in csv with python


code:
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
    print "finished recording"

rawDescription: How to make loops in Python and in this script?

description: Make loops in Python and in this script


code:
class classprop(object):
  def __init__(self, f):
    self.f = classmethod(f)
  def __get__(self, *a):
    return self.f.__get__(*a)()

class buh(object):
  @classprop
  def bah(cls): return 23

print buh.bah

rawDescription: Is there any way to create a class property in Python?


rawDescription: Arithmetic Operations on Numpy Array

description: Arithmetic Operations on Numpy Array


code:
x,y = max(organizedList, key=lambda x: x[1])

print "The most common number is",x,"which was entered",y,"times."

rawDescription: Finding the max of a list with multiple elements


code:
@app.route('/get_access_token')
def get_access_token():
    print "Get Access Token"
    try:
        oauth_verifier = request.args['oauth_verifier']
        oauth_token = request.args['oauth_token']
        print oauth_token + " & " + oauth_verifier

        token = oauth.Token(oauth_token, request_token_secret) # request_token_secret is global
        token.set_verifier(oauth_verifier)
        client = oauth.Client(consumer, token) #consumer is global

        url = "https://api.copy.com/oauth/access"
        resp, content = client.request(url, "GET")
        print "Resp: ", resp
        print "Content: ", content
        return content

    except Exception as e:
        return e.message()

rawDescription: OAuth Handshake Copy Error

description: OAuth Handshake Copy Error


code:
def start():
    print "Hello whats your name?"
    username = raw_input("> ")
    print "Okay, welcome to the game %s" % username
    print "Do you want to hear the background of the game?"
    print "1. Yes"
    print "2. No"
    while True:                            # Repeat the following block of code infinitely
        background = raw_input("> ")

        if background == "1":
            print "Background goes here."
            break                            # Break out of loop if we get valid input
        elif background == "2":
            print "Background skipped"
            break                            # Break out of loop if we get valid input
        else:
            print "Invalid input. Please enter either '1' or '2'"   # From here, program jumps back to the beginning of the loop

start()

rawDescription: How would you create a option to retry in Python?


code:
import re

def main():
  caselines_index = []
  results = []
  cases = []
  nvp_add_searchterm = "nvp_add\(.+?\)"
  searchterm = "(\$.+?)[\,\)]"
  readlines = []

  with open("file.txt", 'r') as file:
    readfile = file.read()
    for line in readfile.split('\n'):
      readlines.append(line.strip())
    for line in readlines:
      if 'case "' in line:
        caselines_index.append(readlines.index(line))
    print caselines_index
    a = 0
    for line_index in caselines_index:
      int_line_index = int(line_index)
      index_of_line_index = caselines_index.index(line_index)
      case_text = ' '.join(readlines[int_line_index:caselines_index[index_of_line_index + 1]]).strip()
      case = [readlines[int_line_index].strip(), case_text]
      cases.append(case)
  with open("result.txt", 'w+') as result_file:
    for case_list in cases:
      caseline = case_list[0].strip()
      result_file.write(caseline + "\n")
      nvp = re.findall(nvp_add_searchterm, case_list[1].strip())

      for item in nvp:
        result_list = re.findall(searchterm, item)

        for result in result_list:
          if "$*" not in result:
            result_file.write(result + "\n")

if __name__=="__main__":
  main()

rawDescription: Python - How do i write only case statements and instances start with $ from input text file?


code:
import itertools

li1 = ["a","b","c"]
li2 = ["d","e","f"]
li3 = ["q","w","e"]
li4 = ["t", "y"]

for elem in itertools.product(li1, li2, li3, li1, li4, li1):
  print elem

rawDescription: Iterate combinations of characters in multiple lists where the output string is in a specific order


code:
for _ in range(10):
    print '.',
    sys.stdout.flush()
    time.sleep(.2)  # or other time-consuming work

rawDescription: Why `print` content doesn't show immediately in terminal?


code:
import time
import threading

class Worker(threading.Thread):
    def __init__(self, stopper):
        threading.Thread.__init__(self)
        self.stopper = stopper

    def run(self):
        while not self.stopper.is_set():
            print 'Hello from Worker!'
            time.sleep(1)

stop = threading.Event()
worker = Worker(stop)
worker.start()

# ...

stop.set()

rawDescription: Python threading question

description: Python threading question


code:
import numpy as np
import time

max_number = 1000000000

# array for results
arr = np.zeros(max_number, dtype='int8')

# starting time
t0 = time.time()

# some tracking for the time spent
time_spent = []

# go through all possible numbers up to the larges possible factor
for p in range(2, int(np.sqrt(max_number))):
    # if the number of factors for the number > 0, it is not a prime, jump to the next
    if arr[p] > 0:
        continue
    # if we have a prime, we will have to go through all its powers < max_number
    n = p
    while n < max_number:
         # increment the counter at n, 2n, 3n, ...
        arr[n::n] += 1
        # take the next power
        n = n * p
    # track the time spent

print "Time spent calculating the table of number of factors: {0} s".format(time.time()-t0)

# now we have the big primes left, but their powers are not needed any more
# they need to be taken into account up to max_number / 2
j = 0
for p in range(p + 1, (max_number + 1) / 2):
    if arr[p] > 0:
        continue
    arr[p::p] += 1
    if j % 10000 == 0:
        print "{0} at {1} s".format(p, time.time()-t0)
    j += 1

print "Primes up to {0} done at {1} s".format(p, time.time()-t0)
# now we have only big primes with no multiples left, they will be all 1
arr[arr == 0] = 1

print "Factor table done at {0} s".format(time.time() - t0)

# calculate the odd/even balance, note that 0 is not included and 1 has 0 factors
cumulative = np.cumsum(1 - 2 * (arr[1:] & 1), dtype='int32')
print "Total time {0} s".format(time.time()-t0)

rawDescription: A counter example for Polya's conjecture


code:
def distance(v1, v2, d):
    if hasattr(d, '__name__'):
        print d.__name__
    elif hasattr(d, '__class__'):
        print d.__class__.__name__
    else:
        print d   # unsure about this case
    dist = d(v1, v2)
    print dist
    return dist

rawDescription: How to get string representations of classes and functions uniformly?

description: Get string representations of classes and functions uniformly


rawDescription: Python: Lits containg tuples and long int


code:
def findAllURLs():

    with open('manylinks.html', 'r') as f:
        data = f.read()
        start = data.find('href')
        while(start != -1):
            begin = data.find('"',start)
            end = data.find('"',begin+1)
            print data[begin+1:end]
            start = data.find('href',end + 1)

if __name__ == "__main__":
    findAllURLs()

rawDescription: Stop endless while True loop

description: Stop endless while True loop


code: print theYear.search(myString).span()

rawDescription: Python re find index position of first search match


code:
import multiprocessing

class TestClass(object):
    pass

def func():
    obj = TestClass()
    cpname = multiprocessing.current_process().name
    print "{0}, Address: {1}".format(cpname, str(obj))
    return obj

pool = multiprocessing.Pool(2)
results = [pool.apply_async(func) for _ in range(2)]

results = [res.get() for res in results]

pool.close()
pool.join()

print results

rawDescription: Multiprocessing doesn't recreate object

description: Multiprocessing doesn't recreate object


code:
import lxml.builder

E = lxml.builder.ElementMaker()
nfo = E.test()
fanart = E.fanart()
nfo.append(fanart)

items = [('http://image.tmdb.org/t/p/w342/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg','http://image.tmdb.org/t/p/original/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg'),
        ('http://image.tmdb.org/t/p/w342/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg','http://image.tmdb.org/t/p/original/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg'),
        ('http://image.tmdb.org/t/p/w342/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg','http://image.tmdb.org/t/p/original/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg'),
        ('http://image.tmdb.org/t/p/w342/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg','http://image.tmdb.org/t/p/original/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg')]

for (link_thumb, link_orig) in items:
    fanart.append(E.thumb(link_orig,preview=link_thumb))

print lxml.etree.tostring(nfo, pretty_print=True)

rawDescription: Python: lxml formatting

description: Python: lxml formatting


code:
import numpy

class Atom(object):
    def atoms_method(self, foo, bar):
        #...with foo and bar being arrays of Paramsof length m & n
        atom_out = foo + bar
        return atom_out

array = numpy.ndarray((10,),dtype=numpy.object)

for i in xrange(10):
    array[i] = Atom()

for i in xrange(10):
    print array[i].atoms_method(i, 5)

rawDescription: Numpy: Array of class instances

description: Numpy: Array of class instances


code:
for var, obj in locals().items():
    print var, sys.getsizeof(obj)

rawDescription: python- how to display size of all variables

description: Python- how to display size of all variables


code:
import distutils.command.build
from distutils.dist import Distribution

b = distutils.command.build.build(Distribution())
b.initialize_options()
b.finalize_options()

print b.build_temp

# If you're building a library, you might need:
print b.build_lib

# Other values of interest are:
b.build_purelib
b.build_platlib
b.build_scripts
b.build_base

rawDescription: Using Sphinx with a distutils-built C extension


code:
diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
  print k, ':', dict1[k], '->', dict2[k]

rawDescription: Is there a better way to compare dictionary values


code:
from __future__ import with_statement
import inspect

class button(object):
  def __enter__(self):
    # keep track of all that's already defined BEFORE the `with`
    f = inspect.currentframe(1)
    self.mustignore = dict(f.f_locals)

  def __exit__(self, exc_type, exc_value, traceback):
    f = inspect.currentframe(1)
    # see what's been bound anew in the body of the `with`
    interesting = dict()
    for n in f.f_locals:
      newf = f.f_locals[n]
      if n not in self.mustignore:
        interesting[n] = newf
        continue
      anf = self.mustignore[n]
      if id(newf) != id(anf):
        interesting[n] = newf
    if interesting:
      print 'interesting new things: %s' % ', '.join(sorted(interesting))
      for n, v in interesting.items():
        if isinstance(v, type(lambda:None)):
          print 'function %r' % n
          print v()
    else:
      print 'nothing interesting'

def main():
  for i in (1, 2):
    def ignorebefore():
      pass
    with button():
      def testing(i=i):
        return i
    def ignoreafter():
      pass

main()

rawDescription: Finding Functions Defined in a with: Block


code:
print "

".join("{}
{}".format(*data) for data in some_list_of_tuples)

rawDescription: Is there an elegant way to print all items in one way and the last item the other in python


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

rawDescription: Comparing performance between ruby and python code


code:
import re

# List of pairs (regexp, handler)
handlers = []

def handler_for(regexp):
    """Declare a function as handler for a regular expression."""
    def gethandler(f):
        handlers.append((re.compile(regexp), f))
        return f
    return gethandler

@handler_for(r'^<\w+> (.*)')
def handle_message(msg):
    print msg

@handler_for(r'^\*{3} (.*)')
def handle_warning(msg):
    global num_warnings, num_fatals
    num_warnings += 1
    if is_fatal(msg):
        num_fatals += 1

rawDescription: How to make an anonymous function in Python without Christening it?

description: Make an anonymous function in Python without Christening it


code:
seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr = list(seq)
for idx in sorted(pos, reverse=True):
    arr.insert(idx,"*")
print ''.join(arr)

rawDescription: Insert value at multiple specified positions into a python string/array


code:
from itertools import combinations
L = ["one", "two", "three", "four"]
for R in combinations(L, len(L) - 1):
    print " and ".join(R)

rawDescription: A more pythonic way of iterating a list while excluding an element each iteration


code:
s = raw_input("Octal?  ")
digits = map(int, s)
lookup = ['','x','w','wx','r','rx','rw','rwx']
perms = [lookup[d] for d in digits]
rights = ['{}={}'.format(*x) for x in zip('ugo', perms)]
print ','.join(rights)

rawDescription: How simplify list processing in Python?

description: How simplify list processing in Python


code:
@tornado.gen.coroutine
def Test2():
    while True:
        item = yield theQueue.get()
        print 'Test2:', item
        tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True)
        response = yield tmp.fetch(item)
        print 'Test2:', str(response)

# Write another test function called `Test3` and do the exactly same thing with Test2.
@tornado.gen.coroutine
def Test3():
    while True:
        item = yield theQueue.get()
        print 'Test3:', item
        tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True)
        response = yield tmp.fetch(item)
        print 'Test3:', str(response)

Test2()
Test3()
tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado async http client blocks

description: Tornado async http client blocks


code:
if(row[0]) == date:
            wind = row[1][0]
            print wind

rawDescription: Slicing in python in a csv

description: Slicing in python in a csv


code:
with open(myFile,'rb') as file:
    for line in file:
        print line

rawDescription: Modifying files containing SUB/escape characters


code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',2232))
s.listen(1)
while 1:
   conn, addr = s.accept()
   conn.close()
   #do something here
   print "Someone connected"

rawDescription: How to check if someone is comming thru a port

description: Check if someone is comming thru a port


code:
#!/usr/local/bin/python

import sys
from datetime import datetime, time, timedelta
from math import pi, cos, sin

def solar_time(dt, longit):
    return ha

def main():
    if len(sys.argv) != 4:
        print 'Usage: hour_angle.py [YYYY/MM/DD] [HH:MM:SS] [longitude]'
        sys.exit()
    else:
        dt = datetime.strptime(sys.argv[1] + ' ' + sys.argv[2], '%Y/%m/%d %H:%M:%S')
        longit = float(sys.argv[3])

    gamma = 2 * pi / 365 * (dt.timetuple().tm_yday - 1 + float(dt.hour - 12) / 24)
    eqtime = 229.18 * (0.000075 + 0.001868 * cos(gamma) - 0.032077 * sin(gamma) \
             - 0.014615 * cos(2 * gamma) - 0.040849 * sin(2 * gamma))
    decl = 0.006918 - 0.399912 * cos(gamma) + 0.070257 * sin(gamma) \
           - 0.006758 * cos(2 * gamma) + 0.000907 * sin(2 * gamma) \
           - 0.002697 * cos(3 * gamma) + 0.00148 * sin(3 * gamma)
    time_offset = eqtime + 4 * longit
    tst = dt.hour * 60 + dt.minute + dt.second / 60 + time_offset
    solar_time = datetime.combine(dt.date(), time(0)) + timedelta(minutes=tst)
    print solar_time

if __name__ == '__main__':
    main()

rawDescription: Local solar time function from UTC and longitude


code:
class cls(object):
  def __new__(cls):
    return object.__new__(object)
  def __init__(self):
    print 'in __init__'

x = cls()

rawDescription: python: return value from __new__

description: Python: return value from __new__


code:
#!/usr/bin/env python

import re

buffer = '''
\tNow is the time\t
for all good men\r\tto come to the aid\t\r
of their party.
'''

nlinePat = re.compile(r'\r\n?|\n')

bufferPos = 0
nlineCounter = 0

bl = nlinePat.split (buffer)

for line in bl:
    print(line.strip ())
    nlineCounter += 1

print nlineCounter

rawDescription: Easiest way to count cross platform newline patterns


code:
import re

s = """blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14"""

regex = re.compile(r"blablabla (?:(?:checked=)(\d+))? ?(?:(?:unchecked=)(\d+))?")

for line in s.splitlines():
    print regex.match(line).groups()

rawDescription: OR in regular expression?

description: OR in regular expression


code:
file_source = 'source.txt'
source = open(file_source,'r')

while 1:
    for line in source:
        print line
    source.seek(0)

source.close()

rawDescription: Loop over the list many times

description: Loop over the list many times


code:
import threading
import Queue

class MultipleThreadTIO:
    def __init__(self):
        self.queue = Queue.Queue()
        self.current_count = 0
        self.stop_write = threading.Event()

    def write_temp(self):
        while not self.stop_write.isSet():
            self.queue.put(str(self.current_count)+"|")
            self.current_count += 1
        self.stop()

    def read_temp(self):
        while True:
            msg = self.queue.get()
            if msg == 'close':
                break
            else:
                print "READ @: " + msg

    def stop(self):
        self.queue.put('close')

mtio = MultipleThreadTIO()

t1 = threading.Timer(0.1, mtio.write_temp)
t2 = threading.Timer(0.5, mtio.read_temp)

t1.start()
t2.start()

t3 = threading.Timer(5, mtio.stop_write.set)

t3.start()

rawDescription: How to read/write to tempfile from multiple threads

description: Read/write to tempfile from multiple threads


code:
import re

# this function both returns and mutates
# so that each list only has to be flattened once
def flatten(lst):
    new_lst = []
    for i, item in enumerate(lst):
        if isinstance(item, list):
            new_lst.extend(flatten(item))
        else:
            new_lst.append(item)
    lst[:] = new_lst
    return lst

def flatten_symbols(d):
    # split the values using the keys as delimiters
    delims = re.compile('({})'.format('|'.join(d)))
    d = dict((key, delims.split(value)) for key, value in d.iteritems())
    # turn the value lists into recursive lists
    # replacing each occurence of a key with the corresponding value
    for key, value in d.iteritems():
        for i, item in enumerate(value):
            if item in d:
                d[key][i] = d[item]
    # flatten the recursive lists
    return dict((key, ''.join(flatten(value))) for key, value in d.iteritems())

d={'s1':{'a':'b+c','b':'f+g', 'f': 'd+e', 'e': 'h+i'},'s2':{'a':'b+c','b':'f+g'}}

new_d = dict((key, flatten_symbols(subdict)) for key, subdict in d.iteritems())
print new_d

rawDescription: How do I replace values in a dict that are also keys recursively until no keys are left in the values?

description: Replace values in a dict that are also keys recursively until no keys are left in the values


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
    for x in range(xlen):
        colors[x, y] = colortuple[(x + y) % len(colortuple)]

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
        linewidth=0, antialiased=False)

ax.set_zlim3d(-1, 1)
ax.w_zaxis.set_major_locator(LinearLocator(6))
ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.03f'))

plt.draw()
print ax._cachedRenderer

rawDescription: Using matplotlib to plot a 3d plot, draw() takes an additional argument


code:
fh = open("index.html", 'r')
rawString = fh.read()   # read entire file to string
fh.close()

temp =  re.findall("<a  href=\".*?\"", rawString)
if temp:
    for i in range(len(temp)): # process each match
        temp[i] = re.search("\".*?\"", temp[i]).group(0) # remove 'href='
    print temp
else:
    print "Not found"

rawDescription: Parsing a site using Regex in Python

description: Parsing a site using Regex in Python


code:
for i in range(5):
    print "chunky bacon"

rawDescription: Repeating function in python?

description: Repeating function in python


code:
for x in range(22): #Remember that the range function returns integers up to 22-1
    exec "f%02d = open('file%02d.txt', 'w')" % (x, x)

rawDescription: Dynamic filenames

description: Dynamic filenames


code:
eid, iid = -1,-1
search_for='Up_MemRd_Unaligned_mburst_ge_0x8'
with open("input") as f:
    for line in f:
        line = line.rstrip()
        if 'Event ID' in line: eid = line.split(':')[1].strip()
        elif 'InterView ID' in line and name:
            iid = line.split(':')[1].strip()
            print "1.", eid
            print "2.", iid
        elif 'Event Name' in line:
            name = line.split(':')[1].strip(" *")
            if name != search_for: name = ""

rawDescription: Python Pattern Matching and parsing

description: Python Pattern Matching and parsing


code:
import sys
arg = sys.argv[1]                  # get first command line parameter
if arg.isdigit():                  # integer value
    value = int(sys.argv[1])
else:
    try:
        value = float(sys.argv[1]) # try float conversion
    except ValueError:             # if that fails
        value = None               # mark value as unusable
if value is not None:
    print "{:,}".format(value)     # print with thousands separator
else:                              # or, if not a number
    print arg                      # print as-is.

rawDescription: Python script to insert thousand separator


code:
f = open('test1.txt').read().split('P')
apple_counts = [segment.count('apple') for segment in f]
print apple_counts #[1, 2, 1, 1, 3]

rawDescription: Count number of times a substring occures within split txt file


code:
list = []

while True:
    eventNub= raw_input("Enter event: ")
    if len(eventNub) < 1:
        break
    else:
        var1 = raw_input("User input 1: ")
        var2 = raw_input("User input 2: ")
        var3 = raw_input("User Input 3: ")
        var4 = raw_input("User input 4: ")

    list.append({'event':eventNub,'v1':var1,'v2':var2,'v3':var3,'v4':var4})

for each in list:
    print each['event']+'.', each['v1']+',', each['v2']+',', each['v3']+',', each['v4']

rawDescription: New to python and programming. I am trying to figure a loop inside another loop


code:
import usb
from PIL import Image
import time
import os, sys
import win32print
from constants import *
from exceptions import *
class Escpos:
    """ ESC/POS Printer object """
    handle    = None
    device    = None

    def __init__(self,interface=0, in_ep=0x100, out_ep=0x01) :
        self.interface = interface
        self.in_ep     = in_ep
        self.out_ep    = out_ep
        if sys.version_info >= (3,):
            raw_data = bytes ("This is a test\n", "utf-8")
        else:
            raw_data = "This is Shiva's test\n\n\n\n\n\n\n\n\n\n"

        self.hPrinter = win32print.OpenPrinter ("Auto EPSON TM-T88V ReceiptE4 on SYSTEM")
        self.handle = win32print.OpenPrinter ("EPSON TM-T88V")
    def _raw(self, msg):
        try:
            self.hJob = win32print.StartDocPrinter (self.hPrinter, 1, ("test of raw data", None, "RAW"))
            self.hJob = win32print.StartDocPrinter (self.handle, 1, ("test of raw data", None, "RAW"))
            try:
                win32print.WritePrinter(self.handle, msg)
                win32print.WritePrinter(self.hPrinter, msg)
                win32print.EndDocPrinter (self.handle)
                win32print.EndDocPrinter (self.hPrinter)
            finally:
                print self.hJob
        finally:
            print self.hJob

    def _check_image_size(self, size):
        """Check and fix the size of the image to 32 bits"""
        if size % 32 == 0:
            return (0, 0)
        else:
            image_border = 32 - (size % 32)
            if (image_border % 2) == 0:
                return (image_border / 2, image_border / 2)
            else:
                return (image_border / 2, (image_border / 2) + 1)

    def _print_image(self, line, size):
        i = 0
        cont = 0
        buffer = ""

        self._raw(S_RASTER_N)
        buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0)
        self._raw(buffer.decode('hex'))
        buffer = ""

        while i < len(line):
            hex_string = int(line[i:i+8],2)
            buffer += "%02X" % hex_string
            i += 8
            cont += 1
            if cont % 4 == 0:
                self._raw(buffer.decode("hex"))
                buffer = ""
                cont = 0

    def image(self, img):
        """Parse image and then print it"""
        pixels   = []
        pix_line = ""
        im_left  = ""
        im_right = ""
        switch   = 0
        img_size = [ 0, 0 ]

        im_open = Image.open(img)
        im = im_open.convert("RGB")

        if im.size[0] > 512:
            print  "WARNING: Image is wider than 512 and could be truncated at print time "
        if im.size[1] > 255:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1 ) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break
            pix_line += im_right
            img_size[0] += im_border[1]

        self._print_image(pix_line, img_size)

    def barcode(self, code, bc, width, height, pos, font):
        """ Print Barcode """
        # Align Bar Code()
        self._raw(TXT_ALIGN_CT)
        # Height
        if height >=2 or height <=6:
            self._raw(BARCODE_HEIGHT)
        else:
            raise BarcodeSizeError()
        # Width
        if width >= 1 or width <=255:
            self._raw(BARCODE_WIDTH)
        else:
            raise BarcodeSizeError()
        # Font
        if font.upper() == "B":
            self._raw(BARCODE_FONT_B)
        else: # DEFAULT FONT: A
            self._raw(BARCODE_FONT_A)
        # Position
        if pos.upper() == "OFF":
            self._raw(BARCODE_TXT_OFF)
        elif pos.upper() == "BOTH":
            self._raw(BARCODE_TXT_BTH)
        elif pos.upper() == "ABOVE":
            self._raw(BARCODE_TXT_ABV)
        else:  # DEFAULT POSITION: BELOW
            self._raw(BARCODE_TXT_BLW)
        # Type
        if bc.upper() == "UPC-A":
            self._raw(BARCODE_UPC_A)
        elif bc.upper() == "UPC-E":
            self._raw(BARCODE_UPC_E)
        elif bc.upper() == "EAN13":
            self._raw(BARCODE_EAN13)
        elif bc.upper() == "EAN8":
            self._raw(BARCODE_EAN8)
        elif bc.upper() == "CODE39":
            self._raw(BARCODE_CODE39)
        elif bc.upper() == "ITF":
            self._raw(BARCODE_ITF)
        elif bc.upper() == "NW7":
            self._raw(BARCODE_NW7)
        else:
            raise BarcodeTypeError()
        # Print Code
        if code:
            self._raw(code)
        else:
            raise exception.BarcodeCodeError()

    def text(self, txt):
        """ Print alpha-numeric text """
        if txt:
            self._raw(txt)
        else:
            raise TextError()

    def set(self, align='left', font='a', type='normal', width=1, height=1):
        """ Set text properties """
        # Align
        if align.upper() == "CENTER":
            self._raw(TXT_ALIGN_CT)
        elif align.upper() == "RIGHT":
            self._raw(TXT_ALIGN_RT)
        elif align.upper() == "LEFT":
            self._raw(TXT_ALIGN_LT)
        # Font
        if font.upper() == "B":
            self._raw(TXT_FONT_B)
        else:  # DEFAULT FONT: A
            self._raw(TXT_FONT_A)
        # Type
        if type.upper() == "B":
            self._raw(TXT_BOLD_ON)
            self._raw(TXT_UNDERL_OFF)
        elif type.upper() == "U":
            self._raw(TXT_BOLD_OFF)
            self._raw(TXT_UNDERL_ON)
        elif type.upper() == "U2":
            self._raw(TXT_BOLD_OFF)
            self._raw(TXT_UNDERL2_ON)
        elif type.upper() == "BU":
            self._raw(TXT_BOLD_ON)
            self._raw(TXT_UNDERL_ON)
        elif type.upper() == "BU2":
            self._raw(TXT_BOLD_ON)
            self._raw(TXT_UNDERL2_ON)
        elif type.upper == "NORMAL":
            self._raw(TXT_BOLD_OFF)
            self._raw(TXT_UNDERL_OFF)
        # Width
        if width == 2 and height != 2:
            self._raw(TXT_NORMAL)
            self._raw(TXT_2WIDTH)
        elif height == 2 and width != 2:
            self._raw(TXT_NORMAL)
            self._raw(TXT_2HEIGHT)
        elif height == 2 and width == 2:
            self._raw(TXT_2WIDTH)
            self._raw(TXT_2HEIGHT)
        else: # DEFAULT SIZE: NORMAL
            self._raw(TXT_NORMAL)

    def cut(self, mode=''):
        """ Cut paper """
        # Fix the size between last line and cut
        # TODO: handle this with a line feed
        print "The Cut mode is",mode
        self._raw("\n\n\n\n\n\n")
        if mode.upper() == "PART":
            print "The Cut mode PartCut is true"
            self._raw(PAPER_PART_CUT)
        else: # DEFAULT MODE: FULL CUT
            self._raw(PAPER_FULL_CUT)

    def cashdraw(self, pin):
        """ Send pulse to kick the cash drawer """
        if pin == 2:
            self._raw(CD_KICK_2)
        elif pin == 5:
            self._raw(CD_KICK_5)
        else:
            raise CashDrawerError()

    def hw(self, hw):
        """ Hardware operations """
        if hw.upper() == "INIT":
            self._raw(HW_INIT)
        elif hw.upper() == "SELECT":
            self._raw(HW_SELECT)
        elif hw.upper() == "RESET":
            self._raw(HW_RESET)
        else: # DEFAULT: DOES NOTHING
            pass

    def control(self, ctl):
        """ Feed control sequences """
        if ctl.upper() == "LF":
            self._raw(CTL_LF)
        elif ctl.upper() == "FF":
            self._raw(CTL_FF)
        elif ctl.upper() == "CR":
            self._raw(CTL_CR)
        elif ctl.upper() == "HT":
            self._raw(CTL_HT)
        elif ctl.upper() == "VT":
            self._raw(CTL_VT)

rawDescription: how to connect to ethernet printer throught python?

description: Connect to ethernet printer throught python


code:
print "Welcome to my World\n\n"
print "Select your Race play\n"
print "(1)Human\n(2)Elf\n(3)Orc\n(4)Undead\n\n"

char = input("enter a number: ")

if (char == 1):
    print "\nYou select race Human"
    out1 = "Human"
elif (char == 2):
    print "\nYou select race Elf"
    out1 = "Elf"
elif (char == 3):
    print "\nYou select race Orc"
    out1 = "Orc"
elif (char == 4):
    print "\nYou select race Undead"
    out1 = "Undead"
else:
    print "\nPlease Restart and select race!!"

print "Perfect Choice " + out1
print "\n\nNow Select Race"
print "(1)Mage\n(2)Archer\n(3)Warrior\n(4)Paladin\n"

race = input("Please Select One Class From 1 to 4: ")

if (race == 1):
    print "You select class Mage"
    out2 = "Mage"
elif (race == 2):
    print "You select class Archer"
    out2 = "Archer"
elif (race == 3):
    print "You select class Warrior"
    out2 = "Warrior"
elif (race == 4):
    print "you select class Paladin"
    out2 = "Paladin"
else:
    print "Restart and select class"

print "\nNow You are a race %s and class %s" % (out1, out2)

rawDescription: Switch case variable print error python

description: Switch case variable print error python


code:
color = {'white' :'\033[1;37m', 'yellow':'\033[1;33m', 'off' : '\033[0;0m'}
print color['white'] + 'string' + color['off']
print color['yellow'] + 'string' + color['off']
color['yellow'] = '\033[1,33m' #incorrect color code - using a , character instead of ;
print color['yellow'] + 'string' + color['off']

rawDescription: Python: octal escape character \033 from a dictionary value translates in a print statement to a UTF-8 character instead


code:
import re

functions = ["details", "nvp_add"]
caselines_index = []
cases = []
readlines = []

def read(in_file):
  global cases
  global caselines_index
  global readlines
  with open(in_file, 'r') as file:
    for line in file.readlines():
      readlines.append(line.strip())
    for line in readlines:
      case_search = re.search("case\s\".+?\"\:\s", line)
      if case_search:
        caselines_index.append(readlines.index(line))
    print caselines_index
    caselines_index_iter = iter(caselines_index)
    int_line_index = int(next(caselines_index_iter))
    int_next_index = int(next(caselines_index_iter))
    while True:
      try:
        case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
        case = [readlines[int_line_index].strip(), case_text]
        cases.append(case)
        int_line_index = int_next_index
        int_next_index = int(next(caselines_index_iter))
      except StopIteration:
        case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
        case = [readlines[int_line_index].strip(), case_text]
        cases.append(case)
        break

def work():
  for func in functions:
    with open(func+".txt", 'w+') as result_file:
      for case_list in cases:
        caseline = case_list[0].strip()
        result_file.write(caseline + "\n")
        nvp = re.findall(func+"\(.+?\)", case_list[1].strip())

        for item in nvp:
          result_list = re.findall("(\$.+?)[\,\)]", item)

          for result in result_list:
            if "$*" not in result:
              result_file.write(result + "\n")

def main():
  in_file = "input.txt"
  read(in_file)
  work()

if __name__=="__main__":
  main()

rawDescription: Extract case statement and string start with $ from nvp_add function in loop...


code:
days = {"Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4,
        "Friday": 5, "Saturday": 6, "Sunday": 7}
result = {}
with open('schedule.txt', 'rb') as f:
    for line in f:
        d = ast.literal_eval(line)
        result[days[d["day"]]] = d
print result[4]["kids"]

rawDescription: How to retrieve a single item from nested dictionary in python

description: Retrieve a single item from nested dictionary in python


code:
import datetime, json
X = {'data': datetime.datetime.now(), 'number':10}
try:
    print json.dumps(X)
except TypeError:
    print "Sorry, it doesn't works"
print json.dumps(X, default=lambda y:str(y))

rawDescription: Python, parsing thru dict and change data type


code:
import wave, audioop

def merge_wav_at_offset(wav_in1, wav_in2, offset, wav_out):
    """Merge two wave files, with the second wave starting at offset seconds
    The two input wave files should have the same frame rate, channels, depth
    Also, offset should be non-negative and can be floating point."""
    wf1= wave.open(wav_in1, 'rb')
    wf2= wave.open(wav_in2, 'rb')
    wfo= wave.open(wav_out, 'wb')

    wfout.setparams(wf1.getparams())

    frame_rate = wf1.getframerate()
    sample_width= wf1.getsampwidth()
    if offset < 0:
        offset= 0
    prologue_frames= int(frame_rate*offset)
    merge_frames= wf2.getnframes()

    # prologue
    frames_to_read= prologue_frames
    while frames_to_read > 0:
        chunk_size= min(frame_rate, frames_to_read)
        wfo.writeframes(wf1.readframes(chunk_size))
        frames_to_read-= chunk_size

    # merging
    frames_to_read= merge_frames
    while frames_to_read > 0:
        chunk_size= min(frame_rate, frames_to_read)
        frames2= wf2.readframes(chunk_size)

        if frames2:
            frames1= wf1.readframes(chunk_size)
            if len(frames1) != len(frames2): # sanity check
                # obviously you should cater for this case too
                raise NotImplementedError, "offset+duration(wf2) > duration(wf1)"
            merged_frames= audioop.add(frames1, frames2, sample_width)
            wfo.writeframes(merged_frames)
        else: # early end of wf2 data; improbable but possible
            break

        frames_to_read-= chunk_size

    # epilogue
    while True:
        frames= wf1.readframes(frame_rate)
        if not frames: break
        wfo.writeframes(frames)

    for wave_file in wf1, wf2, wfo:
        wave_file.close()

rawDescription: Inserting a WAV at a certain point in an audio file using python


code:
tree = """Root
  Branch1
    LeafA
    LeafB
  Branch2
    LeafC
      LeafZ
    LeafD"""

aDict = {}
iDict = {}
for line in tree.split("\n"):
    key = line.lstrip(" ")
    indent = (len(line) - len(key)) / 2
    if indent == 0:
        aDict[key] = None
    else:
        aDict[key] = iDict[indent - 1]
    iDict[indent] = key

print aDict
# {'LeafD': 'Branch2', 'LeafA': 'Branch1', 'Branch2': 'Root', 'LeafC': 'Branch2', 'LeafB': 'Branch1', 'Branch1': 'Root', 'Root': None, 'LeafZ': 'LeafC'}

rawDescription: Convert a space-delimited tree to useful dict in python


code:
letter = raw_input("Type a letter: ")
d={}
d['a']=  20
d['b'] = 50
d['c'] = 90

if letter in d:
    print d[letter]

rawDescription: assigning letters number values

description: Assigning letters number values


code: print filehandler.url

rawDescription: Python: Retrieve original url from a url fileobject


code:
#!/usr/bin/env python

import requests
import urllib
from lxml import etree

session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36'})

tokenRequest = session.get('https://paydirect.link2gov.com/NYCParking-Plate/ItemSearch')

parser = etree.HTMLParser()
tree = etree.fromstring(tokenRequest.text, parser)
verificationToken = tree.xpath('//form//input[@name="__RequestVerificationToken"]/@value')[0]

sessionCookies = tokenRequest.cookies

payload = {
    '__RequestVerificationToken': verificationToken,
    'ItemSearchQuestionUserInput[0].QuestionAnswer': 'myplate',
    'Questions[0].IsRequired': 'True',
    'Questions[0].Options': '',
    'Questions[0].DefaultAnswer': '',
    'Questions[0].Sequence': 1,
    'Questions[0].Text': 'PlateNumber',
    'Questions[0].Type': 'Text',
    'ItemSearchQuestionUserInput[1].QuestionAnswer': 'NY',
    'Questions[1].IsRequired': 'True',
    'Questions[1].Options': '',
    'Questions[1].DefaultAnswer': '',
    'Questions[1].Sequence': 2,
    'Questions[1].Text': 'State',
    'Questions[1].Type': 'Text',
    'ItemSearchQuestionUserInput[2].QuestionAnswer': '',
    'Questions[2].IsRequired': 'False',
    'Questions[2].Options': '',
    'Questions[2].DefaultAnswer': '',
    'Questions[2].Sequence': 3,
    'Questions[2].Text': 'PlateType',
    'Questions[2].Type': 'Text',
    'SubmitButton': 'Continue'
}

raw = urllib.urlencode(payload)
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
}
plateRequest = session.post('https://paydirect.link2gov.com/NYCParking-Plate/ItemSearch/Submit', data=raw, cookies=sessionCookies, headers=headers)

print plateRequest.text

rawDescription: python requests POST cookie session

description: Python requests POST cookie session


code:
try:
   Browser.follow_link(text_regex="Next")
except Exception:
   print "No more next button; terminating loop (but not dying mysteriously)"
   break

rawDescription: mechanize opening multiple pages

description: Mechanize opening multiple pages


code:
import wx

app = wx.App(redirect=False)
top = wx.Frame(None)
sizer = wx.GridBagSizer()

def createHelpWindow(event):
    import wx
    locale = wx.Locale(wx.LANGUAGE_ENGLISH)
    frame = wx.Frame(None, wx.ID_ANY, " Help contents", style=wx.MINIMIZE_BOX | wx.CAPTION | wx.CLOSE_BOX) # A Frame is a top-level window.
    frame.Center()
    frame.SetBackgroundColour('LIGHTGREY')
    frame.SetSize(800,600)
    sizer = wx.GridBagSizer()
    # Add control tree
    treeHelp = wx.TreeCtrl(frame, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TR_DEFAULT_STYLE )
    sizer.Add(treeHelp,(1,1),(19,23),wx.EXPAND)
    # Add description box
    helpDisplay = wx.StaticText( frame, wx.ID_ANY, "", wx.DefaultPosition, wx.DefaultSize, 0, )
    sizer.Add(helpDisplay,(1,26),(1,1),wx.EXPAND)
    # Create image object
    chooseMessageImage = wx.StaticBitmap( frame, wx.ID_ANY, wx.NullBitmap, wx.Point( 300,110 ),wx.DefaultSize, 0)
    def OnSelChanged(event):
        locale = wx.Locale(wx.LANGUAGE_ENGLISH)
        item =  event.GetItem()
        # Display the selected item text in the text widget
        print "selected ", treeHelp.GetItemText(item)
        if treeHelp.GetItemText(item) == 'TFT':
            helpSecondDisplay.SetLabel("""test page for landing page""")
            chooseMessageImage.SetBitmap(wx.NullBitmap) # Set image object to null
        #################### End main #########################
        elif treeHelp.GetItemText(item) == 'Main page':
            helpSecondDisplay.SetLabel("""test txt for main page""")
            chooseMessageImage.SetBitmap(wx.Bitmap( "create_images/add_message.png", wx.BITMAP_TYPE_ANY)) # Set image to some src
            frame.Refresh()
    treeHelp.Bind(wx.EVT_TREE_SEL_CHANGED, OnSelChanged)
    helpSecondDisplay = wx.StaticText( frame, wx.ID_ANY, "Lorem ipsum", wx.DefaultPosition, wx.DefaultSize, 0, )
    sizer.Add(helpSecondDisplay,(3,26),(1,1),wx.EXPAND)
    root = treeHelp.AddRoot('TFT')
    rootMainPage = treeHelp.AppendItem(root, 'Main page')
    treeHelp.Expand(root)
    # Wrap it up
    frame.SetSizer(sizer)
    frame.Center()
    frame.Show(True)     # Show the frame.

# Bind the method
helpButton = wx.Button(top, wx.ID_ANY, u"help",  style=wx.BU_EXACTFIT )
sizer.Add(helpButton,(0,0),(1,1))
top.Bind(wx.EVT_BUTTON, createHelpWindow, helpButton)
top.Sizer = sizer
top.Sizer.Fit(top)
top.Show()
app.MainLoop()

rawDescription: How can I update a wxStaticBitamp?

description: Update a wxStaticBitamp


code:
import numpy as np
a=np.array([[1,2,3],[10,2,2]])
num_rows, num_cols = a.shape
print num_rows, num_cols

rawDescription: numpy, how do I find total rows in a 2D array and total column in a 1D array

description: Numpy, how do I find total rows in a 2D array and total column in a 1D array


code:
import re
pattern = re.compile(r"_\d+")
print [pattern.sub("", item) for item in data]

rawDescription: Using regex to remove substrings from list items in python


code:
for n in list_of_files:
    nam = n[2]
    fil = '.'.join([nam, 'fil'])    # adds .fil extension to filename
    with open(fil,'r+') as f:
        if not f.readline():        # check file contents
            print 'empty file:', fil
            f.seek(0)
            f.write('0')

rawDescription: file overwritten in spite of conditional

description: File overwritten in spite of conditional


code:
#!/usr/bin/env python
#@author: Prahlad Yeri
#@description: Small daemon to create a wifi hotspot on linux
#@license: MIT
#python -m hotspotd $*
import hotspotd.main
import sys
import os
import argparse

if __name__ == "__main__":
    #check root or not
    if os.getenv('USER') != 'root':
        print "You need root permissions to do this, sloth!"
        sys.exit(1)

    parser = argparse.ArgumentParser(description='A small daemon to create a wifi hotspot on linux')
    parser.add_argument('-v', '--verbose', required=False, action='store_true')
    parser.add_argument('command', choices=['start', 'stop', 'configure'])
    args = parser.parse_args()
    hotspotd.main.main(args)

rawDescription: Python erratic behaviour: /usr/bin/python: No module named hotspotd.hotspotd


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

def Login_Google(browser, category_root_address):

  browser.get(category_root_address)

  # click to login
  login_link = browser.find_element_by_id('gb_70')
  webdriver.ActionChains(browser).move_to_element(login_link).click(login_link).perform()

  # input your email here
  email = browser.find_element_by_name('Email')
  # you should input your email here
  email.send_keys('')

  # input your password here
  pwd = browser.find_element_by_name('Passwd')
  # you should input your password for your email here
  pwd.send_keys('')
  pwd.send_keys(Keys.RETURN)

  print 'Login Success'

if __name__ == '__main__':
  root_address = 'https://play.google.com/store/apps/category/TRAVEL_AND_LOCAL?hl=en'

  driver = webdriver.Chrome()
  Login_Google(driver, root_address)

rawDescription: Any python framework to make auto posting/tasking?


code:
data = ["paris", "barcelona", "kolkata", "new york"]
import random
print [random.sample(data, 2) for _ in xrange(5)]

rawDescription: generate categorical dataset in python

description: Generate categorical dataset in python


code:
headers = {"Accept-Language": "en-US,en;q=0.5"}
r = requests.get("https://mobile.bet365.com/sport/default.aspx", headers=headers)
print r.text

rawDescription: python do not follow redirect

description: Python do not follow redirect


code:
inputValues = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]]

tree = {}
numberOfChildren = {}
for (f, t) in inputValues:
  if not tree.has_key(f):
    tree[f] = []
  tree[f].append(t)
  if not numberOfChildren.has_key(t):
    numberOfChildren[t] = 0
  numberOfChildren[t] += 1

roots = [c for c in tree if c not in numberOfChildren]
permutations = []

def findPermutations(node, currentList):
  global tree
  global permutations
  if not tree.has_key(node):
    permutations.append(currentList)
    return
  for child in tree[node]:
    l = list()
    l.extend(currentList)
    l.append(child)
    findPermutations(child, l)

for r in roots:
  findPermutations(r, [r])

print permutations

rawDescription: Traversing an unusual tree in Python

description: Traversing an unusual tree in Python


code:
def curl_progress(total, existing, upload_t, upload_d):
    try:
        frac = float(existing)/float(total)
    except:
        frac = 0
    print "Downloaded %d/%d (%0.2f%%)" % (existing, total, frac)

def curl_limit_rate(url, filename, rate_limit):
    """Rate limit in bytes"""
    import pycurl
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.setopt(c.MAX_RECV_SPEED_LARGE, rate_limit)
    if os.path.exists(filename):
        file_id = open(filename, "ab")
        c.setopt(c.RESUME_FROM, os.path.getsize(filename))
    else:
        file_id = open(filename, "wb")

    c.setopt(c.WRITEDATA, file_id)
    c.setopt(c.NOPROGRESS, 0)
    c.setopt(c.PROGRESSFUNCTION, curl_progress)
    c.perform()

rawDescription: Python URLRetrieve Limit Rate and Resume Partial Download


code:
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def startNewVoting(request):
  from querystring_parser import parser
  p = parser.parse(request.POST.urlencode())
  for key, track in p['tracks'].iteritems():
    print track
    # save to db...

rawDescription: Parsing json object sent with Ajax GET method in Django


code:
import sys
from code import InteractiveConsole

class FileCacher:
    "Cache the stdout text so we can analyze it before returning it"
    def __init__(self):
        self.reset()

    def reset(self):
        self.out = []

    def write(self, line):
        self.out.append(line)

    def flush(self):
        output = '\n'.join(self.out)
        self.reset()
        return output

class Shell(InteractiveConsole):
    "Wrapper around Python that can filter input/output to the shell"
    def __init__(self):
        self.stdout = sys.stdout
        self.cache = FileCacher()
        InteractiveConsole.__init__(self)
        return

    def get_output(self):
        sys.stdout = self.cache

    def return_output(self):
        sys.stdout = self.stdout

    def push(self, line):
        self.get_output()
        # you can filter input here by doing something like
        # line = filter(line)
        InteractiveConsole.push(self, line)
        self.return_output()
        output = self.cache.flush()
        # you can filter the output here by doing something like
        # output = filter(output)
        print output  # or do something else with it
        return

if __name__ == '__main__':
    try:
        import IPython
        IPython.embed()
    except:
        sh = Shell()
        sh.interact()

rawDescription: Using IPython interchangeably with code module if IPython exists


code:
u = ['abc', 'de', 'fghi', 'jklm', 'n', '']
v = []
for item in u:
     v.append(len(item))
print v

rawDescription: initializing members of a list

description: Initializing members of a list


code:
import zipfile
import zlib
import os

src = open( doc, "rb" )
zf = zipfile.ZipFile( src )
for m in  zf.infolist():

    # Examine the header
    print m.filename, m.header_offset, m.compress_size, repr(m.extra), repr(m.comment)
    src.seek( m.header_offset )
    src.read( 30 ) # Good to use struct to unpack this.
    nm= src.read( len(m.filename) )
    if len(m.extra) > 0: ex= src.read( len(m.extra) )
    if len(m.comment) > 0: cm= src.read( len(m.comment) )

    # Build a decompression object
    decomp= zlib.decompressobj(-15)

    # This can be done with a loop reading blocks
    out= open( m.filename, "wb" )
    result= decomp.decompress( src.read( m.compress_size ) )
    out.write( result )
    result = decomp.flush()
    out.write( result )
    # end of the loop
    out.close()

zf.close()
src.close()

rawDescription: How do you unzip very large files in python?

description: Unzip very large files in python


rawDescription: How do I insert a cookie in Python for web scraping?

description: Insert a cookie in Python for web scraping


code:
import sys
print "".join(sorted(sys.stdin.readlines(), key=lambda x:int(x.split()[-1])))

rawDescription: Sorting a file by a specific field

description: Sorting a file by a specific field


code:
import Tkinter

def context_menu(event, menu):
    widget = event.widget
    index = widget.nearest(event.y)
    _, yoffset, _, height = widget.bbox(index)
    if event.y > height + yoffset + 5: # XXX 5 is a niceness factor :)
        # Outside of widget.
        return
    item = widget.get(index)
    print "Do something with", index, item
    menu.post(event.x_root, event.y_root)

root = Tkinter.Tk()
aqua = root.tk.call('tk', 'windowingsystem') == 'aqua'

menu = Tkinter.Menu()
menu.add_command(label=u'hi')

listbox = Tkinter.Listbox()
listbox.insert(0, *range(1, 10, 2))
listbox.bind('<2>' if aqua else '<3>', lambda e: context_menu(e, menu))
listbox.pack()
root.mainloop()

rawDescription: tkinter Listbox item binding

description: Tkinter Listbox item binding


code:
import time
import sys
from qt4 import QtWebKit
from qt4 import QtCore
from qt4 import QtGui
from bs4 import BeautifulSoup

header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'} #Needed to prevent 403 error on Wikipedia

class Render(QtWebKit.QWebPage):
    def __init__(self, url):
        self.app = QtGui.QApplication(sys.argv)
        QtWebKit.QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QtCore.QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()

while True:
    url = 'http://youneednothing.com/'
    r = Render(url)
    content = unicode(r.frame.toHtml())

    soup = BeautifulSoup(content)
    print soup
    time.sleep(10)

rawDescription: I've tried the following infinite loop in my code, but it seem not work


code:
myList = []
for fitsName in glob.glob('*.fits'):
    hdulist = pyfits.open(fitsName)
    a = hdulist[0].header['JD'] - 2400000.5
    myList.append(a)
    hdulist.close()

for item in sorted(myList):
    print item

rawDescription: Sorting a Result in Python

description: Sorting a Result in Python


code:
group_id_element =  next(element for element in xmldoc.getElementsByTagName("groupId")
                         if element.parentNode == xmldoc.documentElement)

print group_id_element.childNodes[0].nodeValue

rawDescription: Not recursive (single node level) getElementsByTagName in Python xml.dom


code:
import os

from PyQt4.QtCore import QCoreApplication, QSocketNotifier, SIGNAL

def readAllData(fd):
        bufferSize = 1024
        while True:
                data = os.read(fd, bufferSize)
                if not data:
                        break
                print 'data read:'
                print repr(data)

a = QCoreApplication([])

fd = os.open('foo.txt', os.O_RDONLY)
notifier = QSocketNotifier(fd, QSocketNotifier.Read)
a.connect(notifier, SIGNAL('activated(int)'), readAllData)

a.exec_()

rawDescription: How do I watch a serial port with QSocketNotifier (linux)?

description: Watch a serial port with QSocketNotifier (linux)


code:
x='My Father is an American, and he is handsome. My Mother is from North America and she is nice'

y = x.split()[1:]
for (i,j) in enumerate(y):
    if j.startswith('America'):
        print y[i-1]

an
North

rawDescription: Identifying the string in front of a given sequence of a word


code:
#!/usr/bin/env python

import argparse
import re

parser = argparse.ArgumentParser(description="Python tool for generating performance statistics from Archivematica's Automation-tools log file")
parser.add_argument('-i', '--input', type=file, help='log file to read')
args = parser.parse_args()

if not (args.input):
    parser.error('you did not specify a log file')

log = args.input

x = 0
regex1 = re.compile("New transfer candidates: set\(\['(.+)'\]\)")
for line in log:
    if 'New transfer candidates' in line:
        m = regex1.search(line)
        if m:
            print m.group(1)
        x = x+1
print x

rawDescription: parsing logs - how to read part of line

description: Parsing logs - how to read part of line


code:
with open('data.txt') as f:
    lines = []
    while True:
        line = list(islice(f, 10)) #islice returns an iterator ,so you convert it to list here.
        if line:
            #do something with current set of <=10 lines here
            lines.append(line)       # may be store it
        else:
            break
    print lines

rawDescription: Multiline file read in Python

description: Multiline file read in Python


code:
import os
import zipfile

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print 'zipping %s as %s' % (os.path.join(dirname, filename),
                                        arcname)
            zf.write(absname, arcname)
    zf.close()

zip("src", "dst")

rawDescription: python : zip file and avoid directory structure

description: Python : zip file and avoid directory structure


code:
a = db.col.find()
bjects = []
for object in a:
       objects.append(object)

for i in objects:
    for q in objects:
        if i['_id'] <>  q['_id'] and i['user_id'] == q['user_id']:
            edges.insert({'source':i['id'],'target': q['id']})

rawDescription: Create edges database based on similar id


code:
name = "josh"
for i in name:
    print i
    # print(i) # python 3

rawDescription: trying to advance from java to Python with no luck

description: Trying to advance from java to Python with no luck


code:
import os
print "Test File 1"
os.system("sudo python /home/ubuntu/MyFolder/TestFile2.py")
#It will run TestFile2.py as Python Script

rawDescription: How To Run A Python File From Another Python File


code:
import socket
import threading

def receive_loop(client):
    print "Entered receive_loop method"
    while True:
        data = client.recv(1024)
        if not data:
            break
        print "A client sent " + data

def main():
    port = 1725
    ip = '127.0.0.1'
    print "Connection from : %s:%s" % (ip, port)
    client = socket.socket()
    client.connect((ip, port))
    receive = threading.Thread(target=receive_loop, args=(client,))
    receive.start()
    while True:
        data = raw_input("Enter command:")
        client.send("Client sent: " + data)

if __name__ == '__main__':
    main()

rawDescription: Two clients don't connect successfully to the server


code:
#!/usr/bin/python
import time

def procedure():
    time.sleep(2.5)

# measure process time
t0 = time.clock()
procedure()
print time.clock() - t0, "seconds process time"

# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"

rawDescription: Timing a HTTP / database request: time.time() or time.clock()?


code:
today = datetime.today()
def get_data():
    """ @return: [(student, followup), (student, followup), ...] """
    q = (session.query(Student) # get all students
        .outerjoin(Followup, and_(Student.id == Followup.student_id, func.date(Followup.next_date)==today)) # @NOTE: check for today might need to be different depending on the database used. Current code should work for mysql
        .options(contains_eager(Student.followup)) # let SA know that "followup" is loaded (line above)
        .filter(Student.status == "active") # filter only for active students
        )
    res = [(s, s.followup) for s in q.all()]
    return res

data = get_data()

# debug
for s, f in data:
    print s.name
    for _f in f:
        print "  ", _f

rawDescription: Best way to get the todays notifications for each user

description: Get the todays notifications for each user


code:
def from_string(s):
    "Convert dotted IPv4 address to integer."
    return reduce(lambda a,b: a<<8 | b, map(int, s.split(".")))

def to_string(ip):
    "Convert 32-bit integer to dotted IPv4 address."
    return ".".join(map(lambda n: str(ip>>n & 0xFF), [24,16,8,0]))

ip = '90.1.0.0'
count = 12000
block_size = 1024

ip_int = from_string(ip)
while count > 0:
    delta = min(count, block_size)
    print to_string(ip_int), delta
    ip_int += delta
    count -= delta

rawDescription: Dividing IP range into chunk of 1024 using python


code:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.download.dir",'xx/yy')
fp.set_preference('browser.helperApps.neverAsk.saveToDisk', "text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream")
driver = webdriver.Firefox(fp)

# selenium login code ...

driver_cookies = driver.get_cookies()
cookies_copy = {}
for driver_cookie in driver_cookies:
    cookies_copy[driver_cookie["name"]] = driver_cookie["value"]
r = requests.get('url',cookies = cookies_copy)
print r.text

rawDescription: How to read a file downloaded by selenium webdriver in python

description: Read a file downloaded by selenium webdriver in python


rawDescription: Sans-serif Font for Axes Tick-labels with Latex


code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = 'MOO.'
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite://'  # In memory.
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    def __repr__(self):
        return '<User {}>'.format(self.name)

class Suspect(db.Model):
    __tablename__ = 'suspect'
    id = db.Column(db.Integer, primary_key=True)
    steam_name = db.Column(db.String)

    def __repr__(self):
        return '<Suspect {}>'.format(self.steam_name)

class List(db.Model):
    __tablename__ = 'list'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', backref=db.backref('lists'))
    suspects = db.relationship('SuspectList', backref='list')
    def __repr__(self):
        return '<List {}>'.format(self.name)

class SuspectList(db.Model):
    __tablename__ = 'suspect_list'
    list_id = db.Column(db.Integer, db.ForeignKey('list.id'), primary_key=True)
    suspect_id = db.Column(db.Integer, db.ForeignKey('suspect.id'), primary_key=True)
    comment = db.Column(db.String)
    suspect = db.relationship('Suspect', backref=db.backref("suspect_list"))

    def __repr__(self):
        return '<SL: %s %s %s>' % (self.list, self.suspect, self.comment)

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        hacker = Suspect(steam_name='Bob')
        cracker = Suspect(steam_name='Alice')
        carol = User(name='Carol')
        carols_list = List(name='Carols', user=carol)

        hacker_suspect = SuspectList(suspect=hacker, comment='RED HAIR')
        cracker_suspect = SuspectList(suspect=cracker, comment='RED EYES')

        carols_list.suspects.append(hacker_suspect)
        carols_list.suspects.append(cracker_suspect)

        db.session.add(carols_list)  # Trust SQLAlchemy to add all related.
        db.session.commit()

        ## Querying:

        my_list = List.query.filter(User.name == 'Carol').first()
        for record in my_list.suspects:
            print '{} reported {} with comment {}'.format(
                record.list.user.name,
                record.suspect.steam_name,
                record.comment
            )

        # Carol reported Bob with comment RED HAIR
        # Carol reported Alice with comment RED EYES

rawDescription: Adding a comments field to database with flask/SQLAlchemy?


code:
from rdflib import Graph
from rdflib.namespace import RDFS

g = Graph()
g.parse("test.owl")

# n is a subclass name and its class name is good-behaviour
# which i want to be the result
n = "pity"

for subj, obj in g.subject_objects(predicate=RDFS.subClassOf):
    if n in subj:
        print obj.rsplit('#')[-1]
    else:
        print 'not found'

rawDescription: retrieving the class name of a specific subclass in owl

description: Retrieving the class name of a specific subclass in owl


code:
import json
import re

PATTERNS = {
    '^R1??':      "Residential Districts",
    'C\d-\d':     "Commercial Districts",
    'M\d-\d$':    "Manufacturing Districts",
    'M1-\d/R\d*': "Mixed Manufacturing & Residential Districts",
    # ...
}

def return_code(codes):
    """takes in a list of codes and returns a json dictionary of codes
    and corresponding descriptions
    """
    descriptions = []
    for code in codes:
        for pattern, desc in PATTERNS.items():
            if re.match(pattern, code):
                descriptions.append({"code": code, "description": desc})
                # We found a matching pattern, no need to test the others
                break
        else:
            print "Code '%s' did not match any pattern!" % code
    return json.dumps(descriptions)

print return_code(['M1-1', 'ZNA'])

rawDescription: checking if a value falls within a range of alphanumeric values

description: Checking if a value falls within a range of alphanumeric values


code:
def foo():
    import traceback
    print 'foo called from', traceback.extract_stack(limit=2)[0][2]
    # previous foo() code

rawDescription: How to get method call detail from the python hotshot profiling module?

description: Get method call detail from the python hotshot profiling module


code:
for v in Table.values():
    print v["From"]

rawDescription: Looping through nested key:value pairs

description: Looping through nested key:value pairs


code:
from PySide import QtCore
from PySide import QtGui

class AdvComboBox(QtGui.QComboBox):
    def __init__(self, parent=None):
        super(AdvComboBox, self).__init__(parent)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setEditable(True)

        # add a filter model to filter matching items
        self.pFilterModel = QtGui.QSortFilterProxyModel(self)
        self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.pFilterModel.setSourceModel(self.model())

        # add a completer
        self.completer = QtGui.QCompleter(self)
        #Set the model that the QCompleter uses
        # - in PySide doing this as a separate step worked better
        self.completer.setModel(self.pFilterModel)
        # always show all (filtered) completions
        self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)

        self.setCompleter(self.completer)

        # connect signals

        def filter(text):
            print "Edited: ", text, "type: ", type(text)
            self.pFilterModel.setFilterFixedString(str(text))

        self.lineEdit().textEdited[unicode].connect(filter)
        self.completer.activated.connect(self.on_completer_activated)

    # on selection of an item from the completer, select the corresponding item from combobox
    def on_completer_activated(self, text):
        print "activated"
        if text:
            print "text: ", text
            index = self.findText(str(text))
            print "index: ", index
            self.setCurrentIndex(index)

    # on model change, update the models of the filter and completer as well
    def setModel(self, model):
        super(AdvComboBox, self).setModel(model)
        self.pFilterModel.setSourceModel(model)
        self.completer.setModel(self.pFilterModel)

    # on model column change, update the model column of the filter and completer as well
    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.pFilterModel.setFilterKeyColumn(column)
        super(AdvComboBox, self).setModelColumn(column)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)

    combo = AdvComboBox()

    names = ['bob', 'fred', 'bobby', 'frederick', 'charles', 'charlie', 'rob']

    # fill the standard model of the combobox
    combo.addItems(names)
    combo.setModelColumn(0)
    combo.resize(300, 40)
    combo.show()

    sys.exit(app.exec_())

rawDescription: QComboBox with autocompletion works in PyQt4 but not in PySide


code:
for item in iter_through_this:
    print sorted(separate_list, key=lambda n: item % n)

rawDescription: using sorted(list, key=function()) with variables

description: Using sorted(list, key=function()) with variables


code:
for i in range(len(words_list)):
  if(words_list[i] == word):
     words_list[i] = "*" * len(word)
     print words_list[i]
print words_list

rawDescription: Why doesn't assigning a new value to a list element inside an if block (which is inside a for loop) not change the actual list itself?


code:
from datetime import datetime
print datetime.strptime(timestring, '%Y-%m-%dT%H:%M:%SZ')

rawDescription: How do I turn this date into a python datetime object?

description: Turn this date into a python datetime object


code:
import csv
reader = csv.reader(open('match_log.txt','rb'), dialect='excel', delimiter='|')

filenameVariable = []
data = {}

for row in reader:
  filenameVariable.append(row[0])
  data[row[0]] = dict(item.split(',') for item in row[1:])

print data
print filenameVariable

rawDescription: Dictionary Appending in Python

description: Dictionary Appending in Python


code:
import thesis,pyodbc

# SQL Server settings
drvr = '{SQL Server Native Client 10.0}'
host = 'POLIVEIRA-PC\\MSSQLSERVER2008'
user = 'username'
pswd = 'password'

# Establish a connection to SQL Server
cnxn = pyodbc.connect(driver=drvr, server=host, uid=user, pwd=pswd) # Setup     connection

# Prepare condition
tags = thesis.sensors().keys()
condition = ' WHERE Tag_ID=' + tags[0]
for tag in tags[1:]:
    condition += ' OR Tag_ID=' + tag

# Extract data from each database
for db in thesis.db_list():
    # Prepare query
    table = '[' + db + '].dbo.tBufferAux'
    query  = 'SELECT Data, Tag_ID, Valor FROM ' + table + condition + '    ORDER BY Data ASC'
    # Check if query's output is empty
    cursor = cnxn.cursor()
    cursor.execute(query)
    if cursor.rowcount == 0:
        print db, 'has no records!'
    else:
        filename = 'Dataset_' + db + '.txt'
        filepath = thesis.out_dir() + filename
        with open(filepath,'w') as file:
            while cursor.fetchone():
                file.write(str(record.Data) + ' ' + str(record.Tag_ID) + ' ' + str(record.Valor) + '\n')

# Close session
cnxn.close()

rawDescription: Optimize script with Pyodbc method

description: Optimize script with Pyodbc method


code:
from sharepoint import SharePointSite, basic_auth_opener
import urllib2
from ntlm import HTTPNtlmAuthHandler

user = 'domain\username'
password = "password"

server_url = "http://sharepoint/"
site_url = server_url + "sites/publishing/sales/"

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, site_url, user, password)
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)

site = SharePointSite(site_url, opener)

salesList = site.lists['Sales Distribution']

fileList = salesList.get_rows(folder='/sites/publishing/sales/Sales_Distribution/Data')

print "================================="

url = fileList[5].as_dict()['EncodedAbsUrl']
file = fileList[5].open()

content = urllib2.urlopen(url)
print content.read()

rawDescription: 400 error when downloading file from sharepoint rest api


code:
import sys
for line in sys.stdin:
    print line

rawDescription: How to receive arguments via shell pipe in python?

description: Receive arguments via shell pipe in python


code:
test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}
for i in test.items():
    print i

for i in test:
    print i

for i in test.values():
    print i

for i in test.values():
    for j in i:
        print j

rawDescription: how to iterate dictionary in python?

description: Iterate dictionary in python


rawDescription: Python: join lines that contain a specific string


code:
def copytree(src, dst, symlinks=False, ignore=None):
    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.
    If exception(s) occur, an Error is raised with a list of reasons.

    If the optional symlinks flag is true, symbolic links in the
    source tree result in symbolic links in the destination tree; if
    it is false, the contents of the files pointed to by symbolic
    links are copied.

    The optional ignore argument is a callable. If given, it
    is called with the `src` parameter, which is the directory
    being visited by copytree(), and `names` which is the list of
    `src` contents, as returned by os.listdir():

        callable(src, names) -> ignored_names

    Since copytree() is called recursively, the callable will be
    called once for each directory that is copied. It returns a
    list of names relative to the `src` directory that should
    not be copied.

    XXX Consider this example code rather than the ultimate tool.

    """
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

rawDescription: cp -r from_dir/* to_dir with python

description: Cp -r from_dir/* to_dir with python


code:
while True:
    sleep_now = False
    try:
        print "WRITER:Getting"
        line,offset = self.queue.get(True, 5)
        #Process the line just read
        proc_line = self.process_line(line)
        if proc_line:
            #Must write it to DB. Put it into DB Queue
            if self.dbqueue.full():
                #DB Queue is full, put data into DB before putting more data
                self.empty_dbqueue()
            self.dbqueue.put(proc_line)
            #Keep a track of the maximum offset in the queue
            self.queue_offset = offset if offset > self.queue_offset else self.queue_offset
    except Queue.Empty:
        #Looks like writing queue is empty. Just check if DB Queue is empty too
        print "WRITER: Empty Read Queue"
        self.empty_dbqueue()

rawDescription: File Processor using multiprocessing

description: File Processor using multiprocessing