code:
import re

s = ('Printed: 2013-07-12 05:09 PM '
     'QC Product: PROT2 CON '
     'Level: Level 3 '
     'Priority: QC Method RF '
     'Result 174 IU/mL '
     'Lot Number: 3BQH01 '
     'Sample ID: 3BQH01 '
     'Instrument ID: DV330681 '
     'QC Range 158.0 - 236.0 '
     'Comment Completed: 2013-07-12 17:09:14 '
     'Comment: Trigger: Manual Trigger '
     'Operator C160487AUR '
     'Time of Run 2013-07-12 17:09:14 '
     'Reagent 13049MA')

rgx = re.compile('QC Product *: *(.+?)(?<=\S) +'
                 'Level *: *(.+?)(?<=\S) +'
                 'Priority *:.+?'
                 'Sample ID *: *(.+?)(?<=\S) +'
                 'Instrument ID')

print rgx.search(s).groups()

rawDescription: Find strings after search in txt file

description: Find strings after search in txt file


code:
import os
folder_list_path = 'C:\Users\jack\Desktop\cleanUp'
for folder in os.listdir(folder_list_path):
    print folder
    subdir=os.path.join(folder_list_path,folder)
    for file in os.listdir(subdir):
        path=os.path.join(subdir,file)
        if os.path.isfile(path) and file.startswith("P"):
            print 'Removing file that starts with P...'
            os.unlink(path)

rawDescription: Removing files from a list of folders

description: Removing files from a list of folders


code:
units_ability = [(1L,), (2L,)] # units_abilities = (Session....all())
[x for (x,) in units_ability]

rawDescription: SQLAlchemy: How to get result in a list while querying single columns of table using all()?


code:
import os
print os.getenv('APPDATA')

rawDescription: easiest way to get %appdata% path variable in python

description: Easiest way to get %appdata% path variable in python


code:
import xlrd
import os.path

registry_doc = xlrd.open_workbook('/tmp/s.xlsx')
findings_doc = xlrd.open_workbook('/tmp/f.xlsx')

findings_sheet = findings_doc.sheet_by_index(0)
registry_sheet = registry_doc.sheet_by_index(0)

findings = {findings_sheet.cell_value(i, 0) for i in range(0, findings_sheet.nrows)}

for r in range(0, registry_sheet.nrows):
   cell_col1=registry_sheet.cell_value(rowx=r,colx=0)
   if cell_col1 in findings:
       print registry_sheet.cell_value(r,2)
       print registry_sheet.cell_value(r,3)
       print registry_sheet.cell_value(r,4)

rawDescription: xlrd lookup Excel values in other Excel file

description: Xlrd lookup Excel values in other Excel file


code:
findres = [5, 7, 15, 22]
contacts = list('abcdefghijklmnopqrstuvwxyz') # dummy list

result = [ contacts[index] for index in findres ]
print result

# ['f', 'h', 'p', 'w']

rawDescription: list being printed out weirdly python

description: List being printed out weirdly python


code:
class Base(object):
    def foo(self):
        print 'Base'

class Child1(Base):
    def foo(self):
        super(Child1, self).foo()
        print 'Child1'

class Child2(Base):
    def foo(self):
        super(Child2, self).foo()
        print 'Child2'

class GrandChild(Child1, Child2):
    def foo(self):
        super(Child2, self).foo()
        print 'GrandChild'

Base().foo()
# outputs:
# Base

Child1().foo()
# outputs:
# Base
# Child1

Child2().foo()
# outputs:
# Base
# Child2

GrandChild().foo()
# outputs:
# Base
# Child1
# Child2
# GrandChild

rawDescription: Does anybody has a good example of how to use super() to Pass Control to Other Classes?


code:
from collections import Counter
import csv
import os
import glob

i = 1
k = 0
file_counts = Counter()

with open('points.txt', 'rb') as f:
    reader = csv.reader(f)
    print "missing files"
    for row in reader:
        file_counts.update([row[1]])
        if not os.path.isfile("img_resize/" + str(row[1])):
            print row[1], i
            k += 1
        i += 1

j = len(list(glob.iglob('img_resize/*.jpg')))

print "total files in folder ", j
print "total files in csv ", i
print
print "duplicates"

for filename, count in file_counts.items():
    if count > 1:
        print count, filename

rawDescription: Discrepancy in the number of files

description: Discrepancy in the number of files


code:
import xml.etree.ElementTree as ET
import urllib2
from xml.dom import minidom

url = 'http://192.168.1.80/api/current'

try:
    usock = urllib2.urlopen(url)
    xmldoc = minidom.parse(usock)
    usock.close()
    data = xmldoc.toxml()
    root = ET.fromstring(data)

    for ele in root.findall('SUBSCRIBER'):
        print 'MAC = ' + ele.find('SUB_MAC_ADDR').text + ', IP = ' + ele.find('SUB_IP').text + ', Location = ' + ele.find('LOCATION').text

except Exception as e:
    print e.getcode()

rawDescription: python code to get xml from server and process it's elements

description: Python code to get xml from server and process it's elements


code:
def get_file_dictionary(folder):
    """ Return a dictionary of zip files in the given folder as tuples in the form: (basename, full path, size) """
    return {os.path.splitext(os.path.split(x)[1])[0].split('__')[0] : (x, os.path.getsize(x)) for x in glob.glob(folder + '*.zip')}

DirTemp = "/var/www/vhosts/italysat.eu/anon_ftp/incoming/"
DirArc = "/var/www/vhosts/italysat.eu/settings.italysat.eu/BackupDTT/"
DirArcScartati = "/var/www/vhosts/italysat.eu/settings.italysat.eu/BackupDTT_scartati/"

incoming = get_file_dictionary(DirTemp)
existing = get_file_dictionary(DirArc)

for base_name_inc, (full_name_inc, size_inc) in incoming.items():
    try:
        full_name_exist, size_exist = existing[base_name_inc]

        if size_inc > size_exist:
            print "Transfer {} -> {}".format(full_name_inc, full_name_exist)
            os.remove(full_name_exist)
            shutil.copy2(full_name_inc, full_name_exist)
        else:
            discard = os.path.join(DirArcScartati, os.path.split(full_name_inc)[1])
            print "Discard {} -> {}".format(full_name_inc, discard)
            shutil.copy2(full_name_inc, discard)
    except KeyError, e:
        new_entry = os.path.join(DirArc, os.path.split(full_name_inc)[1])
        print "Transfer new {} -> {}".format(full_name_inc, new_entry)

    os.remove(full_name_inc)

rawDescription: Compare files with a zip list and figure out if it is larger


code: result = result.map(lambda (k, (s, (n1, n2))): ','.join([s, str(int(n1)), str(float(n2))]))

rawDescription: How to reformat the Spark Python Output

description: Reformat the Spark Python Output


code:
# Read the whole "second file" into a set X.
with open('foo') as fp:
    names = set(fp)

# Read the "first" file line by line.
with open('bar') as fp:
    for line in fp:

        # For each line, extract the part before the comma.
        name = line.split(',')[0]

        # If this part is in the set X, print whatever is desired.
        if name in names:
             print line

rawDescription: Printing the contents and index location of one file by matching it with other file using python


code: for i in range(4): print bin(1 << i)

rawDescription: How does the shift "1<<i" work in Python?


code:
from selenium.webdriver.firefox import webdriver

browser = webdriver.WebDriver()
browser.get('https://www.hidemyass.com/proxy-list')

rows = browser.find_elements_by_xpath('//table[@id="listtable"]//tr')
for row in rows[1:]:
    cells = row.find_elements_by_tag_name('td')
    print cells[1].text

browser.close()

rawDescription: Scraping with Beautiful Soup: Why won't the get_text method return the text of this element?


code:
import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
  pickle.dump(a, handle)

with open('filename.pickle', 'rb') as handle:
  b = pickle.load(handle)

print a == b

rawDescription: How can I use pickle to save a dict?

description: Use pickle to save a dict


code:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.mime.application import MIMEApplication
from email.MIMEImage import MIMEImage
import io
import gzip

msg = MIMEMultipart()
msg['Subject'] = 'ANALYSIS REPORT'

msg.attach(MIMEText('report attached'))

filename = "report.txt"
with open(filename, 'rb') as f, io.BytesIO() as b:
    g = gzip.GzipFile(mode='wb', fileobj=b)
    g.writelines(f)
    g.close()
    attachment = MIMEApplication(b.getvalue(), 'x-gzip')
    attachment['Content-Disposition'] = 'attachment; filename=report.txt.gz'
msg.attach(attachment)

smtpObj = smtplib.SMTP('mail.my-domain.com', 25)
print smtpObj.sendmail(sender, receivers, msg.as_string())
print "e-mail Successfully Sent!"

rawDescription: e-mail large text file

description: E-mail large text file


code:
def dump(f):
    def decorated(self, *args, **kwargs):
        print 'Class: {0}'.format(self.__class__.__name__)
        print 'Args passed to decorated function: {0}'.format(args)
        print 'Keyword args passed to decorated function: {0}'.format(kwargs)
        return f(self, *args, **kwargs)
    return decorated

class Test(object):
    """
    >>> Test().test('arg1', 'arg2', kwarg1='kwval1')
    Class: Test
    Args passed to decorated function: ('arg1', 'arg2')
    Keyword args passed to decorated function: {'kwarg1': 'kwval1'}
    """
    @dump
    def test(*args, **kwargs):
        pass

rawDescription: How to know name of class in decorator for function-method?

description: Know name of class in decorator for function-method


code:
import mechanize

br = mechanize.Browser()
resp = br.open("http://www.mysitewithcookies.com/")
print resp.info()  # headers
print resp.read()  # content

rawDescription: Browser simulation - Python

description: Browser simulation - Python


code:
from bs4 import BeautifulSoup
from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor

data = """

"""
text_to_find = 'This text has to be found'

soup = BeautifulSoup(data)

for script in soup.find_all('script'):
    parser = Parser()
    tree = parser.parse(script.text)
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Assign):
            value = getattr(node.right, 'value', '')
            if text_to_find in value:
                print value

rawDescription: Finding JavaScript variable with certain string with BeautifulSoup


code:
import json

json_text = """
{
    "name": "Joe Smith",
    "link": "http://www.facebook.com/joey",
    "location": {
        "id": "105590706140862",
        "name": "Fairfield, Iowa"
    }
}"""

obj = json.loads(json_text)
print obj["location"]["name"]

rawDescription: How to fetch dictionaries within dictionaries in a JSON string?

description: Fetch dictionaries within dictionaries in a JSON string


code:
import urllib2
from bs4 import BeautifulSoup

pages = []
for x in range(1, 450):
    numb = str(x)
    url = "http://www.mysite.here?pageNo=" + numb
    page = urllib2.urlopen(url).read()
    pages.append(BeautifulSoup(page, "html.parser"))

print pages

rawDescription: Parsing a range of urls using Urllib2 or Beautifulsoup


code:
import types

class container():
    def __init__(self):
        self.info = "undefiend info attribute"

    def use(self):
        print self.info

class tree():
    def __init__(self):

        # create container instance
        b = container()

        # change b's info attribute
        b.info = "b's info attribute"

        # bound method test is set as use of b and in this case unbound, i think
        b.use = types.MethodType(self.test.im_func, b, b.__class__)

        # should read b's info attribute and print it
        # should output: test: b's info attribute but test is bound in some way to the tree object
        print b.use()

    # bound method test
    def test(self):
        return "test: "+self.info

if __name__ == "__main__":
    b = tree()

rawDescription: Method assignment and objects

description: Method assignment and objects


code:
import os
import stat
import sys

MODE = "775"

def mode_matches(mode, file):
    """Return True if 'file' matches 'mode'.

    'mode' should be an integer representing an octal mode (eg
    int("755", 8) -> 493).
    """
    # Extract the permissions bits from the file's (or
    # directory's) stat info.
    filemode = stat.S_IMODE(os.stat(file).st_mode)

    return filemode == mode

try:
    top = sys.argv[1]
except IndexError:
    top = '.'

try:
    mode = int(sys.argv[2], 8)
except IndexError:
    mode = MODE

# Convert mode to octal.
mode = int(mode, 8)

for dirpath, dirnames, filenames in os.walk(top):
    dirs = [os.path.join(dirpath, x) for x in dirnames]
    for dirname in dirs:
        if mode_matches(mode, dirname):
            print dirname

rawDescription: check permissions of directories in python

description: Check permissions of directories in python


code:
for item in employeeList:
  print "Employee name is: %s" % (item[0])
  if item[0] == input and item[1] >= 500:
    print "This person is a manager."
  else:
    print "This person is not a manager."

rawDescription: Python tuple search

description: Python tuple search


rawDescription: How to remove an element from a set?

description: Remove an element from a set


code:
class Node():
    def __init__(self,data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right
class BSTree():
    def __init__(self):
        self.root = None

    def __add(self,node,data):
        if self.root is None:
            self.root = Node(data)
        if node is None:
            return Node(data)
        else:
            if data < node.data:
                node.left = self.__add(node.left,data)
            elif data > node.data:
                node.right = self.__add(node.right,data)
            return node

    def add(self,data):
        self.__add(self.root,data)

    def __preorder(self,node):
        if node is not None:
            print node.data
            self.__preorder(node.left)
            self.__preorder(node.right)

    def preorder(self):
        self.__preorder(self.root)

    def __inorder(self,node):
        if node is not None:
            self.__inorder(node.left)
            self.__inorder(node.right)
            print node.data

    def inorder(self):
        self.__inorder(self.root)

    def __postorder(self,node):
        if node is not None:
            self.__postorder(node.left)
            print node.data
            self.__postorder(node.right)

    def postorder(self):
        self.__postorder(self.root)

    def pprint(self,Node,indent):
        if Node is not None:
            self.pprint(Node.right, indent+1)
            print indent*"     ",Node.data
            self.pprint(Node.left, indent+1)
    def leafcount(self,Node):
        if Node is None:
            return 0
        if self.atLeaf(Node):
            return 1
        else:
            return self.leafcount(Node.left)+self.leafcount(Node.right)

if __name__=="__main__":

    y = BSTree()

    for pres\
        in ["OBAMA","BUSHW","CLINTON","BUSHG","REGAN","CARTER","FORD","NIXON","JOHNSON"]:
        y.add(pres)

    y.pprint(y.root,0)

rawDescription: unpredicted output binary search tree in python

description: Unpredicted output binary search tree in python


code:
import sys, os, string, threading
import paramiko

cmd = "grep -h 'king' /opt/data/horror_20100810*"

outlock = threading.Lock()

def workon(host):

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username='xy', password='xy')
    stdin, stdout, stderr = ssh.exec_command(cmd)
    stdin.write('xy\n')
    stdin.flush()

    with outlock:
        print stdout.readlines()

def main():
    hosts = ['10.10.3.10', '10.10.4.12', '10.10.2.15', ] # etc
    threads = []
    for h in hosts:
        t = threading.Thread(target=workon, args=(h,))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

main()

rawDescription: Creating multiple SSH connections at a time using Paramiko


code:
a = "Hello"
print a[0]
print a[4]

rawDescription: Finding the character occupying a particular index in a string


code:
total_cost = int(input('Please enter a total_cost:'))
if total_cost>=500:

   print"You have won a discount by 15 percent"
   total_cost *= 0.85

elif total_cost>100:

   print"You have won a discount by 10 percent"
   total_cost *= 0.9

elif total_cost>=50:

   print"You have won a discount by 5 percent"
   total_cost *= 0.95

else:
   print 'you total cost is not in the range of discount!'
print 'Now the total cost is ', total_cost

rawDescription: If-Elif-Else Python (Discount Scenario)

description: If-Elif-Else Python (Discount Scenario)


code:
import os
def get_files(directory, prefix=[]):
    for filename in directory.keys():
        path = prefix+[filename]
        if not isinstance(directory[filename], dict):
            print os.path.join(*path)
        else:
            get_files(directory[filename], path)

rawDescription: Find a key in a python dictionary and return its parents


code:
from multiprocessing import Pool

def F(x):
    return x * x

class SeriesInstance(object):
    def __init__(self):
        self.numbers = [1,2,3]
        self.F = F

    def run(self):
        p = Pool()
        out = p.map(self.F, self.numbers)
        p.close()
        p.join()
        return out

if __name__ == '__main__':
    print SeriesInstance().run()

rawDescription: Pool within a Class in Python

description: Pool within a Class in Python


code:
import weakref
import gc

class MyObject(object):
    def my_method(self):
        print 'my_method was called!'

obj = MyObject()
r = weakref.ref(obj)

gc.collect()
assert r() is obj #r() allows you to access the object referenced: it's there.

obj = 1 #Let's change what obj references to
gc.collect()
assert r() is None #There is no object left: it was gc'ed.

rawDescription: Weak References in python

description: Weak References in python


code:
dict1 = {
  'D1K1': ('v1', 'v2'),
  'D1K2': ('v3', 'v4')
}

dict2 = {
  'D2K1': ('v1', 'v2'),
  'D2K2': ('v3', 'v4')
}

# reverse dict2. this randomly chooses one of the possible mappings
# if there are more than one key with the same value..
inv2 = dict((v, k) for k, v in dict2.items())

# this assumes that there will always be a reverse mapping in dict2
# for all values in dict1 (use inv2.get(v, default_value) if that is
# not the case).
print dict((k, inv2[v]) for k, v in dict1.items())

rawDescription: python 2 dictionaries into 1 dictionary join based on their values

description: Python 2 dictionaries into 1 dictionary join based on their values


code:
import csv
with open('toverdpython.csv', 'rb') as toverd:
    reader = csv.reader(toverd, delimiter='|', quoting=csv.QUOTE_NONE)

    # get the header
    inputHeader = next(reader)

    # get the rest
    inputRows = [row for row in reader]

# just to vreify...
print header
for row in inputRows:
    print ', '.join(row)

rawDescription: Python 2.7- Storing Each Row Of A CSV As A Separate List/Dictionary


code:
h = int(raw_input("Please enter the height of the triangle: "))
for i in mytri(h):
    print " " * (h * 2), i
    h -= 1

rawDescription: Formatting Pascal's triangle

description: Formatting Pascal's triangle


code:
#....
if form.is_valid():
   username = request.POST.get('username')
   password = request.POST.get('password1')
   new_user = form.save()
   new_user = authenticate(username=username,password=password)
   login(request, new_user)

   # ------------------------------------
   if request.GET.get('next'):
      return HttpResponseRedirect(request.GET.get('next'))
   # ------------------------------------

   return HttpResponseRedirect(reverse('index'))
else:
   print form.errors
#...

rawDescription: Django Sign up redirect to last page not working


code:
import re
s = """some words
other words
//for nv version
    tf = new TextField();
    tf.width = 600;
    tf.height = 300;
    tf.textColor = 0x00ffff;
    tf.mouseEnabled = false;
    this.addChild(tf);
    Sys.__consoleWindowFuncBasic = log;
//nv end
yet some other words
"""
p = r"//for nv version(.*?)//nv end\n"  # reluctant instead of greedy
print re.sub(p, "", s, flags=re.S) # use re.S to make `.` matchs `\n`

rawDescription: how to delete lines between specific signs in python?

description: Delete lines between specific signs in python


code:
from Tkinter import *
import random

def right():
    canvas.coords(Ro1, ctr_list[1], ctr_list[2],
                       ctr_list[1]+10, ctr_list[2]+10)
##    canvas.update()
    ctr_list[0] += 1
    ctr_list[1] += 10
    ctr_list[2] += 10
    print ctr_list
    if ctr_list[0] < 12:
        window.after(500, right)
##    time.sleep(0.1)

window = Tk()
canvas = Canvas(window, width = 1200, height = 800, bg = 'yellow')
canvas.pack()
canvas.pack(padx = 10, pady = 10)
Button(window, text="Quit", command=window.quit).pack(side="bottom")

a1 = 120
a2 = 120
a3 = 60
a4 = 60
Lm1 = canvas.create_rectangle(a1, a2, a3, a4, fill = 'green')

b1 = 530
b2 = 530
b3 = 600
b4 = 600
Lm2 = canvas.create_rectangle(b1, b2, b3, b4, fill = 'green')

##Tr1 = canvas.create_rectangle(85,85,85+10,85+10, fill = 'blue')
##Tr2 = canvas.create_rectangle(560,560,560+10,560+10, fill = 'blue')

list1 = ["Tr1", "Tr2"]
Treasure1 = random.choice(list1)

if Treasure1 == "Tr1":
    print "TR1"
    ctr_list = [0, a1-30, a3+30]
else:
    print "Tr2"
    ctr_list = [0, b1+30, b3-30]

Tr = canvas.create_rectangle(ctr_list[1], ctr_list[2],
                       ctr_list[1]+10, ctr_list[2]+10, fill="blue")

Ro1 = canvas.create_rectangle(20, 20, 20+10, 20+10)
right()

window.mainloop()

rawDescription: Tkinter in python - object detection (not collision)


code:
import threading
import Queue

def worker(in_q, out_q):
    """ threadsafe worker """
    abort = False
    while not abort:
        try:
            # make sure we don't wait forever
            task = in_q.get(True, .5)
        except Queue.Empty:
            abort = True
        else:
            # process task
            response = task
            # return result
            out_q.put(response)
            in_q.task_done()
# one queue to pass tasks, one to get results
task_q = Queue.Queue()
result_q = Queue.Queue()
# start threads
t = threading.Thread(target=worker, args=(task_q, result_q))
t.start()
# submit some work
task_q.put("hello")
# wait for results
task_q.join()
print "result", result_q.get()

rawDescription: Have Python wait for a function to finish before proceeding with the program


code:
import exrex
print exrex.getone('(ex)r\\1')

# prints 'exrex'

rawDescription: How to generate strings from regular expression in C or Python?

description: Generate strings from regular expression in C or Python


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        layout.setMargin(15)
        layout.setSpacing(10)
        for text in 'One Two Three Four Five'.split():
            layout.addWidget(QtGui.QPushButton(text, self))
        self.rubberband = QtGui.QRubberBand(
            QtGui.QRubberBand.Rectangle, self)
        self.setMouseTracking(True)

    def mousePressEvent(self, event):
        self.origin = event.pos()
        self.rubberband.setGeometry(
            QtCore.QRect(self.origin, QtCore.QSize()))
        self.rubberband.show()
        QtGui.QWidget.mousePressEvent(self, event)

    def mouseMoveEvent(self, event):
        if self.rubberband.isVisible():
            self.rubberband.setGeometry(
                QtCore.QRect(self.origin, event.pos()).normalized())
        QtGui.QWidget.mouseMoveEvent(self, event)

    def mouseReleaseEvent(self, event):
        if self.rubberband.isVisible():
            self.rubberband.hide()
            selected = []
            rect = self.rubberband.geometry()
            for child in self.findChildren(QtGui.QPushButton):
                if rect.intersects(child.geometry()):
                    selected.append(child)
            print 'Selection Contains:\n ',
            if selected:
                print '  '.join(
                    'Button: %s\n' % child.text() for child in selected)
            else:
                print ' Nothing\n'
        QtGui.QWidget.mouseReleaseEvent(self, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: How to use QRubberBand with QRect Class in PyQt?

description: Use QRubberBand with QRect Class in PyQt


code:
if len(set(list2)) !=len(list2):
    print 'Contain duplicates'
else:
    print 'No duplicates'

rawDescription: How do I return a custom statement after finding a duplicate in a list?

description: Return a custom statement after finding a duplicate in a list


code:
def question():
    for x in xrange(sheet.nrows): #iterates over all rows
        newtprint = set()
        for i in xrange(len(newton)): #col1
            for n in xrange(len(james)): #col2
                if newton[i] == james[n]:
                    newtprint.add(path[n]) #adds specified col4 value into set
        print newtprint, x #writes current set being written and row it's written into
        sheety.write(x, 1, str(newtprint)) #writes into col2 based on col4 sets
        wb.save('C:/.../names.xls')

rawDescription: Python - Printing only once from a nested loop


code:
price = input("Enter Price ")
cash = input("Enter Cash ")
coins = [100, 50, 20, 10, 5, 1, 0.5]
change = cash-price
i = 0
while i<len(coins):
    print int(change/coins[i]),str(" X "),coins[0+i]
    if change>0:
        change = change-(int(change/coins[i])*coins[i])
    else:
        change = max(change,0)
    i=i+1

rawDescription: Python - Receipt-like output

description: Python - Receipt-like output


code:
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

import numpy as np
import math
import time

verts = np.array([[0.,0.],[0.,1.],[1.,1.],[1.,0.],[0.,0.]])

codes = [Path.MOVETO,
         Path.LINETO,
         Path.LINETO,
         Path.LINETO,
         Path.CLOSEPOLY,
         ]

path = Path(verts, codes)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show(block=False)
i=0.0
while i<100:
#for i in range(100):
    ax.clear()
    x=math.sin(i)
    y=math.cos(i)

    print x, y

    verts2=np.copy(verts)
    for j in range(len(verts)):
        verts2[j]=verts[j]+np.array([x,y])
    path = Path(verts2, codes)
    patch = patches.PathPatch(path, facecolor='orange', lw=2)
    ax.add_patch(patch)
    plt.draw()
    i+=0.1

rawDescription: Draw moving polygons with matplotlib

description: Draw moving polygons with matplotlib


code:
import urllib
import sys

print urllib.__file__
print sys.path

rawDescription: Get the runpath of a python console-script


rawDescription: Adding elements back to a list of list

description: Adding elements back to a list of list


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        menubutton = tk.Menubutton(self, text="Choose wisely",
                                   indicatoron=True, borderwidth=1, relief="raised")
        menu = tk.Menu(menubutton, tearoff=False)
        menubutton.configure(menu=menu)
        menubutton.pack(padx=10, pady=10)

        self.choices = {}
        for choice in ("Iron Man", "Superman", "Batman"):
            self.choices[choice] = tk.IntVar(value=0)
            menu.add_checkbutton(label=choice, variable=self.choices[choice],
                                 onvalue=1, offvalue=0,
                                 command=self.printValues)
    def printValues(self):
        for name, var in self.choices.items():
            print "%s: %s" % (name, var.get())

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How do I enable multiple selection of values from a combobox?

description: Enable multiple selection of values from a combobox


code:
# For efficiency, if you're on Python 2, include this line so zip is a generator that produces pairs on demand, rather than eagerly slurping the whole file
from future_builtins import zip

with open('myinput') as f:
    # Creates a generator that produces only the final space separated value for each line (could be anything; not checking for hex)
    final_hex = (line.rsplit(None, 1)[-1] for line in f)
    # By using the same generator twice, we get the 1st, 3rd, 5th, etc. from one
    # and the 2nd, 4th, 6th, etc. from the other.
    for hexa, hexb in zip(final_hex, final_hex):
        print("something something", hexa, hexb) # Python 3 print function
        print "something something", hexa, hexb  # Python 2 print statement

rawDescription: Python loop to get data from every line of file and convert it to dec


code:
class First(object):
    def __init__(self):
        super(First, self).__init__()
        print "first"

class Second(object):
    def __init__(self):
        super(Second, self).__init__()
        print "second"

class Third(First, Second):
    def __init__(self):
        super(Third, self).__init__()
        print "that's it"

rawDescription: How does multiple inheritance work with the super() and different __init__() arguments?


code:
bs = BeautifulSoup("
text
")
bs.find("div").name = "h2"

print bs # "
text
"

rawDescription: Replace a <div> tag to <h2> tag using BeautifulSoup


code:
import numpy as np

k=1

# segmentation
seg = np.zeros((100,100), dtype='int')
seg[30:70, 30:70] = k

# ground truth
gt = np.zeros((100,100), dtype='int')
gt[30:70, 40:80] = k

dice = np.sum(seg[gt==k])*2.0 / (np.sum(seg) + np.sum(gt))

print 'Dice similarity score is {}'.format(dice)

rawDescription: How to calculate dice coefficient for measuring accuracy of image segmentation in python

description: Calculate dice coefficient for measuring accuracy of image segmentation in python


code:
from bs4 import BeautifulSoup

data = """

Abc:  test1

Def:  test2

"""
temp = BeautifulSoup(data)

#get individual  elements
strongs = temp.select('.myTestCode > strong')

#map each  element to it's text content concatenated with the text node that follow
result = map(lambda x: x.text + x.nextSibling.strip(), strongs)

#join all separated by comma and print
print ', '.join(result)

#print output:
#Abc: test1, Def: test2

rawDescription: To split html code using beautifulsoup for the required format


code:
import os
from subprocess import PIPE, STDOUT, Popen

lines = []
p = Popen(cmd, bufsize=1, stdin=open(os.devnull), stdout=PIPE, stderr=STDOUT)
for line in iter(p.stdout.readline, ''):
      print line,          # print to stdout immediately
      lines.append(line)   # capture for later
p.stdout.close()
p.wait()

rawDescription: Need to avoid subprocess deadlock without communicate


code:
def filter(request):
    val=request.POST.get('designation')
    val2=request.POST.get('choices')
    val3=request.POST.get('textField')
    print val
    print val2,val3
    if val2=='Designation':

        newData = EmployeeDetails.objects.filter(designation=request.POST.get('textField'))
        print val2
    elif val2=='Name':
        newData = EmployeeDetails.objects.filter(userName=request.POST.get('textField'))
        print val2
    elif val2=='EmployeeID':
        newData = EmployeeDetails.objects.filter(employeeID=request.POST.get('textField'))
        print val2
    elif val2=='Project':
        newData = EmployeeDetails.objects.filter(project=request.POST.get('textField'))
        print val2
    elif val2=='DateOfJoin':
        newData = EmployeeDetails.objects.filter(dateOfJoin=request.POST.get('textField'))
        print val2
    else:
        print "Data Not Found"

    return render_to_response('filter.html',{'newData':newData,'val2':val2})

rawDescription: Filtering in Django

description: Filtering in Django


code:
import re
r = re.compile(r'(?P<words>\w+(?:\s+\S+)*?)\s*(?P<num>\d+)?\r\n')
for s in ('Foo & Bar 555\r\n', 'Hello World\r\n', 'Spam     99\r\n',
          'Number 1 666\r\n'):
  print s, r.match(s).groupdict()

rawDescription: Regex: Matching a space-joined list of words, excluding last whitespace


code:
for line in f:
    if '!!event!!' in line:
        L0 = line.split()
        for line in f:
            if "flag1" in line:
                L1 = line.split()
            elif "flag2" in line:
                L2 = line.split()
            elif "flag3" in line:
                L3 = line.split()
                break             # continue outer loop
        print 'Event and flag times: ', L0[0], L1[0], L2[0], L3[0]

# Event and flag times:  8:41:08 8:41:10 8:41:12 8:41:16
# Event and flag times:  8:41:22 8:41:23 8:41:24 8:41:27

rawDescription: Loop within loop python

description: Loop within loop python


code:
class Foo(object):
    def foo(self):
        print self.a

class Bar(object):
    foo = Foo.__dict__['foo']

b = Bar()
b.a = 1
b.foo()

rawDescription: How to copy a member function of another class into myclass in python?

description: Copy a member function of another class into myclass in python


code:
import mechanize

def gmaillogin():
    browser = mechanize.Browser(factory=mechanize.RobustFactory())
    browser.set_handle_robots(False)
    r = browser.open("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2&emr=1")
    browser.select_form(nr=0)
    browser.form["Email"] = "emailid"
    browser.form["Passwd"] = "password"
    browser.submit()

    html = browser.response().readlines()

    print browser.response().read()

if __name__ == "__main__":
    gmaillogin()

rawDescription: How to use Python to do web crawling on a website that requires Google account to sign in?

description: Use Python to do web crawling on a website that requires Google account to sign in


code:
a = u"пример"

print urllib.quote_plus(a.encode('utf8'))
## %D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80

print urllib.quote_plus(a.encode('cp1251'))
## %EF%F0%E8%EC%E5%F0

rawDescription: How decode url to windows-1251 in python


code:
print "The result is %s out of %s i.e. %d %%" % (nominator, denominator, percentage)
#                                         ^ extra % to escape the one after

rawDescription: Print special characters

description: Print special characters


code:
import threading, time
def my_threaded_func(arg, arg2):
    print "Running thread! Args:", (arg, arg2)
    time.sleep(10)
    print "Done!"

thread = threading.Thread(target=my_threaded_func, args=("I'ma", "thread"))
thread.start()
print "Spun off thread"

rawDescription: Non blocking python process or thread

description: Non blocking python process or thread


code:
class Stack(object):
    def __init__(self, index, name, disks):
        self.index = index
        self.name = name
        self.disks = disks
    def __str__(self):
        return self.name
    def __repr__(self):
        return 'Stack(%r, %r, %r)' % (self.index, self.name, self.disks)
    def is_adjacent(self, other):
        return other.index in (self.index + 1, self.index - 1)
    def push(self, disk):
        assert len(self.disks) == 0 or self.disks[-1] > disk
        self.disks.append(disk)
    def pop(self):
        return self.disks.pop()

class Hanoi(object):

    def __init__(self, n):
        source = Stack(0, "source", range(n, 0, -1))
        helper = Stack(1, "helper", [])
        target = Stack(2, "target", [])
        self.stacks = [source, helper, target]
        self.hanoi(n, source, target)

    def hanoi(self, n, source, target):
        """Move n disks from source to target using remaining stack"""
        helper = self.stacks[3 - source.index - target.index]
        if n == 0:
            return
        if source.is_adjacent(target):
            self.hanoi(n - 1, source, helper)
            self.move(source, target)
            self.hanoi(n - 1, helper, target)
        else:
            assert helper.is_adjacent(source) and helper.is_adjacent(target)
            self.hanoi(n - 1, source, target)
            self.move(source, helper)
            self.hanoi(n - 1, target, source)
            self.move(helper, target)
            self.hanoi(n - 1, source, target)

    def move(self, s, d):
        assert s.is_adjacent(d)
        disk = s.pop()
        print "moving %d from %s to %s" % (disk, s, d)
        d.push(disk)

Hanoi(5)

rawDescription: Tower of Hanoi with adjacent restriction


code:
import pyPdf

def getPDFContent(path):
    content = ""
    # Load PDF into pyPDF
    pdf = pyPdf.PdfFileReader(file(path, "rb"))
    # Iterate pages
    for i in range(0, pdf.getNumPages()):
        # Extract text from page and add to content
        content += pdf.getPage(i).extractText() + "\n"
    # Collapse whitespace
    content = " ".join(content.replace("\xa0", " ").strip().split())
    return content

print getPDFContent("test.pdf")

rawDescription: Parsing PDF documents

description: Parsing PDF documents


code:
import urllib2
import getpass

FEED_URL = 'https://mail.google.com/mail/feed/atom'

def login(user, passwd):
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(
        realm='New mail feed',
        uri='https://mail.google.com',
        user='{user}@gmail.com'.format(user=user),
        passwd=passwd
    )
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    feed = urllib2.urlopen(FEED_URL)
    print feed.read()

if __name__ == "__main__":
    user = raw_input("Enter username:")
    passwd = getpass.getpass("Enter Password:")
    login(user, passwd)

rawDescription: How to get emails from Gmail on disabled access from IMAP/POP3

description: Get emails from Gmail on disabled access from IMAP/POP3


code:
import itertools
v = (a, b, c)
for d, e, f in itertools.product(*(generate(x) for x in v)):
  print d, e, f

rawDescription: Nested generator functions in python

description: Nested generator functions in python


code:
class materialsClass(object):
    def __init__(self): # create a new class
        self.materials = {} # create a new dictionary under this class
    def materialsChange(self):
        while True:
            q1 = raw_input("Type 'edit' to add or change a material, or 'continue' to continue: ")
            if q1 == 'edit':
                while True:
                    q2 = raw_input("Type 'add' to add a new material, 'edit' to edit amount of a material: ")
                    if q2 == 'add':
                        x = str(raw_input("Enter the Material: "))
                        y = int(0)
                        self.materials[x] = y # this is how to add items to dictionaries sequentially
                        print self.materials
                        break
                    elif q2 == 'edit':
                        x = str(raw_input("Enter your Material: "))
                        y = int(raw_input("Enter your Change: "))
                        self.materials[x] = y
                        print self.materials
                        break
                    else:
                        print "Please Type an Option"
            elif q1 == 'continue': break
            else:
                print "Type an Option!"

        print self.materials

    def materialCounter(self):
        for k in self.materials:
            self.materials[k] = self.materials[k] + 10
        print self.materials

obj=materialsClass() # you do not need to create the class again and again, just once is fine

while True:
    obj.materialsChange()
    obj.materialCounter()

rawDescription: How to access a dictionary in a function that is defined in another function in the same class

description: Access a dictionary in a function that is defined in another function in the same class


code:
def goodness(s):
    return 0 if 'u' in s else s.count('g')

def substrings(s, length):
    "Generate all substrings of given length."
    for i in range(len(s) - length + 1):
        yield s[i:i+length]

print list(substrings('abcdefgh', 3)) # ['abc', 'bcd', 'cde', 'def', 'efg', 'fgh']

def best_slice(s, length):
    """Return the 'best' substring."""
    return max(substrings(s, length), key=goodness)

print best_slice('abcgabgoguffg', 3) # 'gog'

rawDescription: Clarifying simple function

description: Clarifying simple function


rawDescription: Why tuple assignment failed?

description: Why tuple assignment failed


code:
class testThread(Thread):
    def __init__(self, parent):
        self.parent = parent
        Thread.__init__(self)
        self.start()

    def run(self):
        self.value = 1
        while 1:
            print self.value
            time.sleep(1)

class testGUI(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Test", size=(500,270))
        panel = wx.Panel(self, -1)

        self.buttonStart = wx.Button(panel, -1, label="Start thread", pos=(0,0))
        self.buttonChange = wx.Button(panel, -1, label="Change var", pos=(0,30))
        panel.Bind(wx.EVT_BUTTON, self.startThread, id=self.buttonStart.GetId())
        panel.Bind(wx.EVT_BUTTON, self.changeVar, id=self.buttonChange.GetId())

    def startThread(self, event):
        self.the_thread = testThread(self)

    def changeVar(self, event):
        # DO SOMETHING HERE THAT CHANGES 'x' IN THREAD TO 2...
        self.the_thread.value = 2

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = testGUI()
    frame.Show(True)
    app.MainLoop()

rawDescription: How do I change variable in a thread?

description: Change variable in a thread


code:
print "{0}: {1:.2f}".format(s, decimal_value)
#output Percent growth: 10.01

rawDescription: Python: Formatting decimal passed to indexed position in format string


rawDescription: Python encoding/decoding problems

description: Python encoding/decoding problems


code:
import os, sys

def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', pidfile='/var/tmp/daemon.pid'):
    """ Make the current process a daemon.  """

    try:
        # First fork
        try:
            if os.fork() > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write('fork #1 failed" (%d) %s\n' % (e.errno, e.strerror))
            sys.exit(1)

        os.setsid()
        os.chdir(our_home_dir)
        os.umask(0)

        # Second fork
        try:
            pid = os.fork()
            if pid > 0:
                # You must write the pid file here.  After the exit()
                # the pid variable is gone.
                fpid = open(pidfile, 'wb')
                fpid.write(str(pid))
                fpid.close()
                sys.exit(0)
        except OSError, e:
            sys.stderr.write('fork #2 failed" (%d) %s\n' % (e.errno, e.strerror))
            sys.exit(1)

        si = open('/dev/null', 'r')
        so = open(out_log, 'a+', 0)
        se = open(err_log, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())
    except Exception, e:
        sys.stderr.write(str(e))

rawDescription: Can I run a Python script as a service?

description: Run a Python script as a service


code:
import os
import subprocess
import textwrap

# create a batch file with some commands in it
batch_filename = 'commands.bat'
with open(batch_filename, "wt") as batchfile:
    batchfile.write(textwrap.dedent("""
        python hello.py
        if errorlevel 1 (
            @echo non-zero exit code: %errorlevel% - terminating
            exit
        )
        time /t
        date /t
    """))

# execute the batch file as a separate process and echo its output
kwargs = dict(stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
              universal_newlines=True)
with subprocess.Popen(batch_filename, **kwargs).stdout as output:
    for line in output:
        print line,

try: os.remove(batch_filename)  # clean up
except os.error: pass

rawDescription: Python on Windows: Run multiple programs sequentially in one command prompt


code:
CHARSET = "abcdefghijklmnopqrstuvwxyx"
MAX_LENGTH = 6  # generate all strings from CHARSET with length 1 thru MAX_LENGTH
NUM_PROCESSES = None # defaults to all available cores

from itertools import product

# string_gen is what the workers run.  Everything else
# runs in the main program.
def string_gen(prefix, suffix_len, length):
    # Generate all strings of length `length` starting with `prefix`.
    # If length > suffix_len, only the last suffix_len characters
    # need to be generated.
    num_done = 0
    if length <= suffix_len:
        assert prefix == ""
        for t in product(CHARSET, repeat=length):
            result = "".join(t)
            # do something with result
            num_done += 1
    else:
        assert len(prefix) + suffix_len == length
        for t in product(CHARSET, repeat=suffix_len):
            result = prefix + "".join(t)
            # do something with result
            num_done += 1
    return num_done

def record_done(num):
    global num_done
    num_done += num
    print num_done, "done so far"

def do_work(pool, strings_per_chunk=1000000):
    # What's the most chars we can cycle through without
    # exceeding strings_per_chunk?  Could do with this
    # logs, but I'm over-reacting to 1-liner disease ;-)
    N = len(CHARSET)
    suffix_len = 1
    while N**suffix_len <= strings_per_chunk:
        suffix_len += 1
    suffix_len -= 1
    print "workers will cycle through the last", suffix_len, "chars"

    # There's no point to splitting up very short strings.
    max_short_len = min(suffix_len, MAX_LENGTH)
    for length in range(1, max_short_len + 1):
        pool.apply_async(string_gen, args=("", suffix_len, length),
                         callback=record_done)
    # And now the longer strings.
    for length in range(max_short_len + 1, MAX_LENGTH + 1):
        for t in product(CHARSET, repeat=length-suffix_len):
            prefix = "".join(t)
            pool.apply_async(string_gen, args=(prefix, suffix_len, length),
                             callback=record_done)

if __name__ == "__main__":
    import multiprocessing
    pool = multiprocessing.Pool(NUM_PROCESSES)
    num_done = 0
    do_work(pool)
    pool.close()
    pool.join()
    expected = sum(len(CHARSET)**i
                   for i in range(1, MAX_LENGTH + 1))
    assert num_done == expected, (num_done, expected)

rawDescription: Parallelize brute force generation

description: Parallelize brute force generation


code:
import pygame
from pygame.locals import *

def main():
    pygame.init()
    pygame.display.set_mode((480, 360))
    gamepad = pygame.joystick.Joystick(0)
    gamepad.init()

    delay = 1000
    neutral = True
    pressed = 0
    last_update = pygame.time.get_ticks()

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return

        move = False
        if gamepad.get_axis(1) == 0:
            neutral = True
            pressed = 0
        else:
            if neutral:
                move = True
                neutral = False
            else:
                pressed += pygame.time.get_ticks() - last_update
        if pressed > delay:
            move = True
            pressed -= delay
        if move:
            print "move"
        last_update = pygame.time.get_ticks()

if __name__ == "__main__":
    main()
    pygame.quit()

rawDescription: pygame.key.set_repeat for Joystick

description: Pygame.key.set_repeat for Joystick


code:
def foo(bar, baz):
  print 'hello {0}'.format(bar)
  return 'foo' + baz

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)

async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo

# do some other stuff in the main process

return_val = async_result.get()  # get the return value from your function.

rawDescription: how to get the return value from a thread in python?

description: Get the return value from a thread in python


code:
import urllib
from bs4 import BeautifulSoup

import requests

url = "http://www.padtube.com/Audio-Files-Player/30-01-1-2.html"
#pageurl = urllib.urlopen(url)

pageurl = requests.post(url, data = {
    'page': 2
})

pageurl = pageurl.text

soup = BeautifulSoup(pageurl)

for b in soup.select("table#dl-tbl-list th a[href]"):
    print b['href']

rawDescription: How to get all application link in every page?

description: Get all application link in every page


code:
import bs4

f = open("test.html")
soup = bs4.BeautifulSoup(f)

for textarea in soup.find_all('textarea'):
    print textarea.get_text()

rawDescription: Python- Regular expression to match" <textarea> </textarea> " and anything between them


code:
foo="""Interface        group           vlan    ver
fa1/6            239.0.0.3       2       2
fa1/2            239.0.0.1       1       2
fa1/1            239.0.0.0       3       2
fa1/6            239.0.0.1       1       2
"""

def parse_lines(lines):
  headers = lines[0].split()
  entries = []
  for r in lines[1:]:
    if not len(r): continue    # skip blank lines
    vals = r.split()
    e = dict(zip(headers,vals))
    entries.append(e)
  return entries

def doit():
  entries = parse_lines(foo.split("\n"))
  ports = {}
  for e in entries:
    vlan = e["vlan"]
    if not (vlan in ports): ports[vlan] = []
    ports[vlan].append( e["Interface"] )
  print "%6s %s" % ("vlan", "ports")
  for vlan in ports:
    print "%6s %s" % (vlan, ', '.join(ports[vlan]))

doit()

rawDescription: Pythonic parsing of table?

description: Pythonic parsing of table


code:
import spynner
from PyQt4.QtCore import QUrl
from PyQt4.QtNetwork import QNetworkRequest, QNetworkAccessManager

url = "http://localhost:8080/niklas/test.php"
data = "foo=bar"
headers = { "Content-Type": "application/x-www-form-urlencoded" }

req = QNetworkRequest(QUrl(url))
for k, v in headers.items():
    req.setRawHeader(k, v)

browser = spynner.Browser()
browser.webframe.load(req, QNetworkAccessManager.PostOperation, data)
browser._wait_load()

print browser.html

rawDescription: How to run a POST request programmatically in python with a GUI ? (spynner, webkit...)

description: Run a POST request programmatically in python with a GUI ? (spynner, webkit...)


code:
import urllib, re

source = urllib.urlopen('http://www.cbssports.com/nba/draft/mock-draft').read()

## every image name is an abbreviation composed by capital letters, so...
for link in re.findall('http://sports.cbsimg.net/images/nba/logos/30x30/[A-Z]*.png', source):
    print link

    ## the code above just prints the link;
    ## if you want to actually download, set the flag below to True

    actually_download = False
    if actually_download:
        filename = link.split('/')[-1]
        urllib.urlretrieve(link, filename)

rawDescription: Extract image links from the webpage using Python


code:
opt_param = request.args.get("something")
if opt_param is None:
    print "Argument not provided"

rawDescription: How to check for the existence of a get parameter in flask

description: Check for the existence of a get parameter in flask


code:
tarname = tar_path + "/" + client_id + "_" + dt.datetime.now().strftime("%Y%m%d_%H%M%S") + ".tar.gz"
print tarname
tar = tarfile.open (tarname, "w:gz")
for name, dir in archive_list:
  print "Adding %s" % (name)
  tar.add(name, arcname=client_id)
tar.close()

rawDescription: Python trying to iterate over one element of multidimensional list


code:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class MulticastPingPong(DatagramProtocol):

    def startProtocol(self):
        """
        Called after protocol has started listening.
        """
        # Set the TTL>1 so multicast will cross router hops:
        self.transport.setTTL(5)
        # Join a specific multicast group:
        self.transport.joinGroup("228.0.0.5")

    def datagramReceived(self, datagram, address):
        print "Datagram %s received from %s" % (repr(datagram), repr(address))
        if datagram == "Client: Ping":
            # Rather than replying to the group multicast address, we send the
            # reply directly (unicast) to the originating port:
            self.transport.write("Server: Pong", address)

# We use listenMultiple=True so that we can run MulticastServer.py and
# MulticastClient.py on same machine:
reactor.listenMulticast(8005, MulticastPingPong(),
                        listenMultiple=True)
reactor.run()

rawDescription: How to receive UDP packets in Python without dropping

description: Receive UDP packets in Python without dropping


code:
class myClass(object):

    def __init__(self):
        self.a = ''

    def A(self):
        self.a = 'A'
        print self.a

    def B(self):
        print self.a + ' in B'

def main():
    stuff = myClass()
    stuff.A()
    stuff.B()

if __name__ == '__main__':
    main()

rawDescription: Help Defining Global Names

description: Help Defining Global Names


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

class paletteTableview(QAbstractTableModel):
    def __init__(self, test_data, parent=None):
        super(paletteTableview, self).__init__(parent)
        self.__test_data = test_data

    def rowCount(self, parent):
        return len(self.__test_data)

    def columnCount(self, parent):
        return len(self.__test_data[0])

    def data(self,index,role):
        if role == Qt.DisplayRole:

            row = index.row()
            column = index.column()
            value = self.__test_data[row][column]
            return value

        if role == Qt.DecorationRole:
            row = index.row()
            column = index.column()

            value = self.__test_data[row][column]
            print "data:" , index.row() , index.column() , value
            #print value

            value = QColor(value)
            #print value
            pixmap = QPixmap(26,26)
            pixmap.fill(value)

            icon = QIcon(pixmap)
            return icon

class MainWindow(QMainWindow):
    def __init__( self  , parent = None ):
        super( MainWindow , self ).__init__(parent)

        self.tv = QTableView(self)
        self.dm = paletteTableview( data( 4 , 5 ) )
        self.tv.setModel( self.dm )
        self.setCentralWidget(self.tv)

def data(row,column):
    import random

    test_data = []
    temp_data= []
    for i in range(row):
        for j in range(column):
            temp_data.append( "#%06X" % random.randint( 0 , 0xFFFFFF ) )
        test_data.append(temp_data)
        temp_data = []
    return test_data

def main():
    app = QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Query on Table View - Model/View programming


code:
s = pd.Series(np.random.choice([0,1,2], 10))
print s
print list(s.index[s != 0])

rawDescription: Choosing particular values from a Pandas Series


code:
class Test(object):
    def __getitem__(self, arg):
        return str(arg)*3

test = Test()

print test[0]
print test['kitten']

rawDescription: Create a python object that can be accessed with square brackets


code:
sin,sout,serr = ssh.exec_command("while true; do uptime; done")

def line_buffered(f):
    line_buf = ""
    while not f.channel.exit_status_ready():
        line_buf += f.read(1)
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ''

for l in line_buffered(sout):
    print l

rawDescription: paramiko with continuous stdout

description: Paramiko with continuous stdout


code:
#!/bin/python

import random

#create 40 random grades
grades = [(float(int(float(20*random.random())))/2)+0.5 for i in xrange(40)]

#count the occurrence of each grade
histogram = []
for i in sorted(set(grades)): histogram.append([int(i*50),grades.count(i)])

#some grid information
gridsize = 500
griddiv = 20
topleft = 50

#graph title
print 'text', '"','Histogram of Grades','"', 220, 25

#x axis title
for i in range(1,21):
    print 'text', '"',float(i)/2,'"', (i+1)*25, 570

#y axix title
for i in range(0,11):
    print 'text', '"',i,'"', 25, 600-(i+1)*50

#grid
print 'grid', topleft, topleft, gridsize, gridsize, griddiv, griddiv

#chart rectangles
print 'color 0 140 0'
for i in histogram:
    print 'fillrect',i[0]-25+topleft, gridsize-(50*i[1])+topleft,gridsize/griddiv,50*i[1],'b'+str(i[0])
    print 'fillrect', 'color','b'+str(i[0])

rawDescription: input data to create histogram in Quickdraw

description: Input data to create histogram in Quickdraw


code:
import os,sys,fnmatch,shutil

root = r"G:\desktop\Project\lyr\ab"
groups_list = []
for dirname, dirnames, filenames in os.walk(root):
    for subdirname in dirnames:
        groups_list.append(subdirname)
        if groups_list.count(subdirname) >= 2: # if there are 2 or more duplictes
            dir_to_delete = os.path.join(dirname, subdirname)
            print subdirname, 'appears', groups_list.count(subdirname), 'times'
            print dir_to_delete
            shutil.rmtree(dir_to_delete)

rawDescription: Delete folders and sub folders sharing the same name using python 2.7 - Error


code:
libc = CDLL('libc.so')

# Some constants
PROT_READ = 1
PROT_WRITE = 2
PROT_EXEC = 4

def executable_code(buffer):
    """Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.
    The pointer should be freed with libc.free() when finished"""

    buf = c_char_p(buffer)
    size = len(buffer)
    # Need to align to a page boundary, so use valloc
    addr = libc.valloc(size)
    addr = c_void_p(addr)

    if 0 == addr:
        raise Exception("Failed to allocate memory")

    memmove(addr, buf, size)
    if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):
        raise Exception("Failed to set protection on buffer")
    return addr

code_ptr = executable_code(buffer)
fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))
print fptr(1234)
libc.free(code_ptr)

rawDescription: Python ctypes and function calls

description: Python ctypes and function calls


code:
def breakRNA(seqRNA, *breakPoint):
    seqRNAList = []
    noOfBreakPoints = len(breakPoint)
    for breakPt in range(noOfBreakPoints):
        for index in breakPoint:
            seqRNAList.append(seqRNA[:index])
            seqRNA = seqRNA[index:]
        break
    return seqRNAList

test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
print test

rawDescription: How can I insert spaces at certain locations in a string (Python 2.7)?

description: Insert spaces at certain locations in a string (Python 2.7)


code:
# first try with exceptions
def nonempty( iter ):
    """ returns `iter` if iter is not empty, else raises TypeError """
    try:
        first = next(iter)
    except StopIteration:
        raise TypeError("Emtpy Iterator")
    yield first
    for item in iter:
        yield item

# a version without exceptions. Seems nicer:
def isempty( iter ):
    """ returns `(True, ())` if `iter` if is empty else `(False, iter)`
         Don't use the original iterator! """
    try:
        first = next(iter)
    except StopIteration:
        return True, ()
    else:
        def iterator():
            yield first
            for item in iter:
                yield item
        return False, iterator()

for x in ([],[1]):
    # first version
    try:
        list(nonempty(iter(x))) # trying to consume a empty iterator raises
    except TypeError:
        print x, "is empty"
    else:
        print x, "is not empty"

    # with isempty
    empty, it = isempty(iter(x))
    print x,  "is", ("empty" if empty else "not empty")

rawDescription: Idiomatic way of taking action on attempt to loop over an empty iterable


code:
class something(object):
    def __init__(self, name=None, someobjects=[]):
        self.name = name
        self.someobjects = someobjects

    def total(self):
        return len(self.someobjects)

listofpeoplewhoarethisclass = [something("john", [1,2,3])]

for person in listofpeoplewhoarethisclass:
    print person.name, person.total(), len(person.someobjects)

rawDescription: Python - len(somelist) returns different value than method in class


code:
import subprocess as sub

p = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
    print row.rstrip()   # process here

rawDescription: Handling tcpdump output in python

description: Handling tcpdump output in python


code:
import matplotlib.pyplot as plt;plt.rcdefaults()
from numpy.random import rand
from numpy import arange
import numpy as np

def libra_execution_time():
    data = np.genfromtxt('C:\\programming\\Python27\\libra_graphs\\File\\histogram.csv',delimiter=',')

    hash_diff,key_diff,binary_diff = 0,0,0

    hash_time_lst,key_time_lst,binary_time_lst = [],[],[]

    for row in data:
        if not np.isnan(row[7]):
            hash_diff = row[7]-hash_diff
    hash_time_lst.append(hash_diff)

    for row in data:
        if not np.isnan(row[8]):
            key_diff = row[8]-key_diff
    key_time_lst.append(key_diff)

    for row in data:
        if not np.isnan(row[9]):
            binary_diff = row[9]-binary_diff
    binary_time_lst.append(binary_diff)

    print "#Hash Partitioner--->" ,hash_time_lst,len(hash_time_lst)
    print "#Key Field Partitioenr--->", key_time_lst,len(key_time_lst)
    print "#Binary Partitioner--->",binary_time_lst,len(binary_time_lst)

    #x_lst = (hash_time_lst + key_time_lst + binary_time_lst)
    #print x_lst
    job_time = {"Hash Time":hash_time_lst,"Key_Time":key_time_lst,"Binary Time":binary_time_lst}
    print job_time
    print job_time.keys(),job_time.values()

    y_pos = np.arange(len(job_time.values()))
    print "Y position",y_pos
    val = np.array(job_time.values())
    print val

    plt.barh(y_pos,val ,align='center',height = 0.5 ,color=('r','y','g'))
    plt.yticks(y_pos,job_time.keys())

    plt.xlabel('Time(seconds)')
    plt.ylabel('Performance--->')
    plt.title('Job Execution LIBRA')

    plt.show()

libra_execution_time()

rawDescription: Python MatPlotlib barchart- Resize width


code:
from scipy.spatial import ConvexHull
from matplotlib.path import Path

hull = ConvexHull( points )

hull_path = Path( points[hull.vertices] )

print hull_path.contains_point((1,2)) # Is (1,2) in the convex hull?

rawDescription: Check if points lies inside a convex hull


code:
# gets all files under ROOT_INPUT_PATH with FILE_EXTENSION and tries to extract text from them into ROOT_OUTPUT_PATH with same filename as the input file but with INPUT_FILE_EXTENSION replaced by OUTPUT_FILE_EXTENSION
from win32com.client import Dispatch
from win32com.client.dynamic import ERRORS_BAD_CONTEXT

import winerror

# try importing scandir and if found, use it as it's a few magnitudes of an order faster than stock os.walk
try:
    from scandir import walk
except ImportError:
    from os import walk

import fnmatch

import sys
import os

ROOT_INPUT_PATH = None
ROOT_OUTPUT_PATH = None
INPUT_FILE_EXTENSION = "*.pdf"
OUTPUT_FILE_EXTENSION = ".txt"

def acrobat_extract_text(f_path, f_path_out, f_basename, f_ext):
    avDoc = Dispatch("AcroExch.AVDoc") # Connect to Adobe Acrobat

    # Open the input file (as a pdf)
    ret = avDoc.Open(f_path, f_path)
    assert(ret) # FIXME: Documentation says "-1 if the file was opened successfully, 0 otherwise", but this is a bool in practise?

    pdDoc = avDoc.GetPDDoc()

    dst = os.path.join(f_path_out, ''.join((f_basename, f_ext)))

    # Adobe documentation says "For that reason, you must rely on the documentation to know what functionality is available through the JSObject interface. For details, see the JavaScript for Acrobat API Reference"
    jsObject = pdDoc.GetJSObject()

    # Here you can save as many other types by using, for instance: "com.adobe.acrobat.xml"
    jsObject.SaveAs(dst, "com.adobe.acrobat.accesstext")

    pdDoc.Close()
    avDoc.Close(True) # We want this to close Acrobat, as otherwise Acrobat is going to refuse processing any further files after a certain threshold of open files are reached (for example 50 PDFs)
    del pdDoc

if __name__ == "__main__":
    assert(5 == len(sys.argv)), sys.argv # <script name>, <script_file_input_path>, <script_file_input_extension>, <script_file_output_path>, <script_file_output_extension>

    #$ python get.txt.from.multiple.pdf.py 'C:\input' '*.pdf' 'C:\output' '.txt'

    ROOT_INPUT_PATH = sys.argv[1]
    INPUT_FILE_EXTENSION = sys.argv[2]
    ROOT_OUTPUT_PATH = sys.argv[3]
    OUTPUT_FILE_EXTENSION = sys.argv[4]

    # tuples are of schema (path_to_file, filename)
    matching_files = ((os.path.join(_root, filename), os.path.splitext(filename)[0]) for _root, _dirs, _files in walk(ROOT_INPUT_PATH) for filename in fnmatch.filter(_files, INPUT_FILE_EXTENSION))

    # patch ERRORS_BAD_CONTEXT as per https://mail.python.org/pipermail/python-win32/2002-March/000265.html
    global ERRORS_BAD_CONTEXT
    ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)

    for filename_with_path, filename_without_extension in matching_files:
        print "Processing '{}'".format(filename_without_extension)
        acrobat_extract_text(filename_with_path, ROOT_OUTPUT_PATH, filename_without_extension, OUTPUT_FILE_EXTENSION)

rawDescription: "Not implemented" Exception when using pywin32 to control Adobe Acrobat


code:
def memoized(f):
    cache={}
    def ret(*args):
        if args in cache:
            return cache[args]
        else:
            answer=f(*args)
            cache[args]=answer
            return answer
    return ret

@memoized
def fibonacci(n):
    if n==0 or n==1:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2)

print fibonacci(100)

rawDescription: Memoization Handler

description: Memoization Handler


code:
output = "/home/alvarofeal/Desktop/prueba_sub.avi"
output = re.sub(r'(.*\/)*', "", output)
print output

rawDescription: python: function sub of re module

description: Python: function sub of re module


code:
my_float_dict = dict()
with open('my_float_strings.txt','r') as f:
    for line in f:

        string_list = line.split(',')

        index = int(string_list[0])

        line_float_list = []
        for field in string_list[1:]:
            line_float_list.append(round(float(field),2))

        my_float_dict[index] = line_float_list

print my_float_dict

rawDescription: Python: How can read as float numbers a series of strings from a text file?


code:
labels = ['A', 'B', 'C', 'D']
suffixes = ['left', 'right']

result = (', '.join(label+suffix for label in labels) for suffix in suffixes)

for line in result:
    print line

rawDescription: What is the correct way to build an output string by iterating over several elements in a list?


code:
## ARGUMENTS
import argparse
import getpass

parser = argparse.ArgumentParser()
parser.add_argument("--environment", help="Environment to change queue",
                    default=None)
parser.add_argument("--queue", help="Queue to change", default=None)
parser.add_argument("--limit", help="Limit value", default=None)
args = parser.parse_args()

current_user = getpass.getuser()

environment = args.environment if args.environment else raw_input("Environment you are in: ")
queue = args.queue if args.queue else raw_input("Queue you wish to modify: ")
limit = args.limit if args.limit else raw_input("Limit value of Queue: ")

print environment, queue, limit

rawDescription: python - use argparse but have option for raw_input

description: Python - use argparse but have option for raw_input


code:
root = LXML.parse(xml_file_location)
elements_list = root.xpath(".//*[@*[contains(., $text)]]", text = string_to_search )
print "Found: %s strings in the xml file" %len(elements_list)
for node in elements_list:
    print "\nFound:\n%s" %LXML.tostring(node).split("\n")[0]
    parent = node.getparent()
    if node.tag == "record":
        path = node.get("path") # nodes of type: "record" hold the attribute: "path"
    elif node.tag == "field":
        path = node.get("name") # nodes of type: "field" hold the attribute: "name"
    else:
        print "unclear node type adding empty string"
        path = ""
    full_path = path
    while parent.get("path") != "":
        parent_path = parent.get("path")
        full_path = parent_path + "." + full_path
        parent = parent.getparent()
    print "Full path: %s" %full_path

rawDescription: python xml search by attribute value

description: Python xml search by attribute value


code:
import re

def RemoveBannedWords(toPrint,database):
    statement = toPrint
    pattern = re.compile("\\b(Good|Bad|Ugly)\\W", re.I)
    return pattern.sub("", toPrint)

toPrint = 'Hello Ugly Guy, Good To See You.'

print RemoveBannedWords(toPrint,bannedWord)

rawDescription: Better way to remove multiple words from a string?


code: print my_string[0:100]

rawDescription: Output first 100 characters in a string

description: Output first 100 characters in a string


code:
# i omitted "data = your string" here

def data_value(person_name, prop_name, new_value = None):
    global data
    start_person = data.find("Name=" + person_name + "\n")
    while start_person != -1:
        end_person = data.find("Name=", start_person + 1)
        start_value = data.find(prop_name + "=", start_person, end_person)
        if start_value != -1:
            start_value += len(prop_name) + 1
            end_value = data.find("\n", start_value, end_person)
            if new_value == None:
                return data[start_value:end_value]
            else:
                data = data[:start_value] + str(new_value) + data[end_value:]
        start_person = data.find("Name=" + person_name + "\n", end_person)
    return None

print data_value("Mark", "Pay")    # Output: None (missing person)
print data_value("Bob", "Weight")  # Output: None (missing property)
print data_value("Bob", "Pay")     # Output: "500" (current value)
data_value("Bob", "Pay", 1234)     # (change it)
print data_value("Bob", "Pay")     # Output: "1234" (new value)

data_value("John", "Pay", 555)     # (change it in both Johns)

rawDescription: Find string and replace the next few lines with something


code:
class IRC:
    def Connect(self):
        try:
            HOST = sys.argv[1]
            PORT = sys.argv[2]
        except IndexError:
            print "Usage: "+sys.argv[0]+" [server] [port]\n"
            sys.exit(1)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((HOST, PORT))

class Pong(threading.Thread):
    def __init__(self,ircclass):
        self.myirc = ircclass
    def Pong(self):
        while 1:
            self.myirc.s.send("Test")

gIRC = IRC
gIRC.connect()
myPong = Pong(gIRC)

rawDescription: Sharing variables between two classes in Python


code:
y = [[[] for i in range(n)] for i in range(n)]
print y

rawDescription: Python 2.7 creating a multidimensional list


code:
t='Sat, 17 May 2014 18:42:02 GMT'
from datetime import datetime
str_time= datetime.strptime(t,'%a, %d  %B %Y %H:%M:%S GMT')
updated_time= str_time.replace(hour=str_time.hour+3)
print updated_time

rawDescription: How to get correct GMT `last_modifed` of AWS S3 key using `boto` API?

description: Get correct GMT `last_modifed` of AWS S3 key using `boto` API


code:
import random
keys = my_dict.keys()
random.shuffle(keys)
for key in keys:
    print key, my_dict[key]

rawDescription: Randomizing a dictionary in python

description: Randomizing a dictionary in python


code:
def do_something():
    print 'doing something...'

def maybe_do_it(hesitant=False):
    if hesitant:
        exec "do_something = lambda: 'did nothing'"
    result = do_something()
    print result

maybe_do_it(False)    # doing something...
maybe_do_it(True)    # did nothing

rawDescription: In Python, variables inside if conditions hide the global scope even if they are not executed?


code:
import json

data = "[{\"index\":\"1\",\"username\":\"a\",\"fname\":\"a\",\"lname\":\"a\",\"email\":\"a1@xyz.com\",\"sysadmin\":true},{\"index\":\"2\",\"username\":\"ab\",\"fname\":\"ab\",\"lname\":\"ab\",\"email\":\"ab1@xyz.com\",\"sysadmin\":false}]";
data = json.loads(data)

for i in xrange(len(data)):
    if data[i].get('index') == "1":
        print data[i]

rawDescription: How to fetch a column from a Json format array in Python

description: Fetch a column from a Json format array in Python


code:
import urllib2
print urllib2.unquote('%B9%F3%D6%DD%C3%A9%CC%A8').decode('gbk')

rawDescription: Unescape the chinese characters in url?

description: Unescape the chinese characters in url


code:
#!/usr/bin/env python

import urllib2
from bs4 import BeautifulSoup

html_content = urllib2.urlopen("http://www.demo.com/index.php")

soup = BeautifulSoup(html_content, "lxml")

# COMMENTS COUNT
count_comment = soup.find("span", "sidebar-comment__label")
count_comment
count_comment_final = count_comment.find_next("meta")

# READ COUNT
count_read = soup.find("span", "sidebar-read__label js-read")
count_read
count_read_final = count_read.find_next("meta")

# PRINT RESULT
print count_comment_final['content'].split(':')[1]
print count_read_final['content'].split(':')[1]

rawDescription: Parse and get result with special formatting with BeautifulSoup


code:
import urllib2
from bs4 import BeautifulSoup

# Download webpages 2010 webpage

y = 2010
url = 'http://www.baseball-reference.com/teams/BOS/'+ str(y) +'-pitching.shtml'
print 'Download from :', url

#dowlnload
filehandle = urllib2.urlopen(url)

fileout = 'YEARS'+str(y)+'.html'
print 'Save to : ', fileout, '\n'

#save file to disk
f = open(fileout,'w')
f.write(filehandle.read())
f.close()

# Read and parse the html file

# Parse information about the age of players in 2000

y = 2010

filein = 'YEARS' + str(y) + '.html'
print(filein)
soup = BeautifulSoup(open(filein))

table = soup.find_all('table', attrs={'id': 'team_pitching'}) #' non_qual' ''

for t in table:

    i = 1
    entries = t.find_all('tr', attrs={'class' : ''}) #' non_qual' ''
    print(len(entries))
    for entry in entries:
        columns = entry.find_all('td')
        printString = str(i) + ' '
        for col in columns:
            try:
                if ((',' in col['csk']) and (col['csk'] != '')):
                    printString = printString + col.text
                    i = i + 1
                    print printString
            except:
                pass

rawDescription: Why I cannot parse this HTML page in Python?


code:
class Example:
    def __init__(self, name, variable):
        self.n = name
        self.v = variable

obj_dict = {}
obj_dict['tempclass'] = Example("tempclass", 1)
obj_dict['class1'] = Example("class1", 2)

def function1(obj_dict, stringforobj):
    obj = obj_dict.get(stringforobj)
    if obj is not None:
        print obj.v
    else:
        print "Notfound"

inpt = raw_input()
function1(obj_dict, inpt)

rawDescription: Is it possible to change string into class with some function or command?


code:
#Main Loop
while True:
    #Set number of Gigs
    totstor=raw_input("Enter the amount of storage on the desired disk (In gb): ")
    #Just in case you get bored
    if totstor=='quit':
        break
    try:
        #Do the math
        gigs=int(totstor)
        gigs=round(gigs)
        kilos=gigs*1048576
        kilos=kilos/25
        kilos=round(kilos)
        kilos=str(kilos)
        kilos=kilos.strip('.0')
        print 'Space for about '+kilos+' standard jpg image files available'
    #If an error occurs, let em' know
    except:
        print 'Invalid Number!'
        print '\n'
    print '\n'
#Bye
quit()

rawDescription: Python Program to tell amount of image files that will fit on a disk/flash drive


code:
import re
date_reg = "([0-9]{2}\/[0-9]{2}\/[0-9]{4} [0-9]{2}\:[0-9]{2}\:[0-9]{2} (?:AM|PM))"
def split_by_date(text_iter):
    date = None
    lines = []
    for line in text_iter:
        if re.match(date_reg, line):
            if lines or date:
                yield (date, lines)
            date = datetime.strptime(line.strip(), '%m/%d/%y %H:%M:%S')
            lines = []
        else:
            lines.append(line)

    yield (date, lines)

for date, lines in split_by_date(f):
    # here you have lines for each encountered date
    for line in lines:
        print line

rawDescription: Processing textfile in chunks, where each chunk is separated by timestamp


code:
from multiprocessing.dummy import Process, Queue

def process(inq, outq):
    while True:
        n = inq.get()
        try:
            if n % 2 == 0:
                outq.put(n)  # Queue up for printing
            elif n % 3 == 0:
                inq.put(12)  # Queue up for future processing
            elif n % 5 == 0:
                inq.put(14)  # Queue up for future processing
        finally:
            inq.task_done()

def printer(q):
    while True:
        m = q.get()
        try:
            print "("+str(m)+")",
        finally:
            q.task_done()

def main():
    workqueue = Queue()
    printqueue = Queue()
    printworker = Process(target=printer, args=(printqueue,))
    printworker.daemon = True
    printworker.start()

    for i in range(4):
        processor = Process(target=process, args=(workqueue, printqueue))
        processor.daemon = True
        processor.start()

    li = [1,2,3,4,5,6,7,8,9]

    for x in li:
        workqueue.put(x)  # optionally, put all items before starting processor threads so initial work is processed strictly before generated work
    workqueue.join()  # Wait for all work, including new work, to be processed
    printqueue.join()  # Then wait for all the results to be printed

if __name__ == '__main__':
    main()

rawDescription: python: multiprocessing.dummy using imap_unordered to iterate thru a growing/modifying list

description: Python: multiprocessing.dummy using imap_unordered to iterate thru a growing/modifying list


code:
from itertools import izip

file1 = open("test", "r")
file2 = open("test2", "r")

def lazy(file):
    for line in file:
        #do something with the line
        yield line

for lines in izip(lazy(file1), lazy(file2)):
    print lines

rawDescription: How do I transpose/pivot a csv file with python *without* loading the whole file into memory?

description: Transpose/pivot a csv file with python *without* loading the whole file into memory


rawDescription: Generation of values above diagonal numpy array


code:
from twisted.internet import reactor
from twisted.web import client

def processResult(page):
    print "I got some data", repr(page)
    reactor.callLater(0.1, reactor.stop)
def dealWithError(err):
    print err.getErrorMessage()
    reactor.callLater(0.1, reactor.stop)

class ProxyClientFactory(client.HTTPClientFactory):
    def setURL(self, url):
        client.HTTPClientFactory.setURL(self, url)
        self.path = url

factory = ProxyClientFactory('http://url_you_want')
factory.deferred.addCallbacks(processResult, dealWithError)

reactor.connectTCP('proxy_address', 3142, factory)
reactor.run()

rawDescription: Does python twisted framework HttpClient access proxy?


code:
import subprocess
p = subprocess.Popen(["ping.exe","www.google.com"], stdout = subprocess.PIPE)
print p.communicate()[0]

rawDescription: Measuring ping latency of a server - Python


code:
result = session.execute("""SELECT spam, eggs FROM blah WHERE moo='foo'""")
for row in result:
    print "spam = %s" % row.spam
    print "eggs = %s" % row.eggs

rawDescription: Database Connection Manager for Pyramid using minimal SQLAlchemy


code:
data = {}

for l in open('input').readlines():
    key, value = l.split("=")
    vector_name = key.split("_")[0]
    vector = data.get(vector_name,[])
    vector.append(value)
    data[vector_name] = vector

print data

rawDescription: Parsing Multiple Fields to Single Color Vector in Python


code:
def func(**kw):
    d = {'key0' : 0, 'key1' : 1}
    d.update(**kw)
    print "updated %s"%kw.keys()

func(kw0=0, kw1=1)

rawDescription: Getting keys that were updated with the using a dictionaries update method


code:
with open("words.txt") as words:
    wlist=[(ln,word.strip()) for ln,word in enumerate(words,1)]

with open("files.txt") as files:
    flist=[(ln,file.strip()) for ln,file in enumerate(files,1)]

for filenum, filename in flist:
    with open(filename) as fdata:
        for fln,line in enumerate(fdata,1):
            for wln, word in wlist:
                if word in line:
                    print "%d => %d" % (wln, fln)

rawDescription: How do I grep for words coming from a file in files listed in a file?

description: Grep for words coming from a file in files listed in a file


code:
# Define class named MyStuff which inherits from object
class MyStuff(object):

    # Define initializer method for class MyStuff
    # This method accepts 2 arguments: self and order
    # self will hold newly created instance of MyStuff
    def __init__(self, order):
        # Assign a string value to field tangerine of current instance
        self.tangerine="And now a thousand years between"
        # Assign a string value to field order of current instance
        self.order="order"
        # Note that second argument (order) was not used

    # Define apple method for class MyStuff
    # This method accepts 1 argument: self
    # self will hold the instance of MyStuff
    def apple(self):
        # Print a string to standard output
        print "I AM CLASSY APPLE!"

# Create instance of MyStuff
# Initializer is called implicitly and self is set to new instance
# Second argument (order) is missing, so you get exception
thing=MyStuff()
# Correct invocation would be
thing = MyStuff("some string value")
# Call method apple of MyStuff instance - statement correct but won't be reached
# due to former exception
thing.apple()

# Print value of field tangerine of MyStuff instance to standard output - again
# statement correct but won't be reached due to former exception
print thing.tangerine

rawDescription: Class init and arguments

description: Class init and arguments


code:
import sympy

def main():
   e = sympy.sympify(raw_input("input equation here: "))
   g = input("number to substitute for g: ")
   print 'e=',e.subs({'g':g})

rawDescription: Python equation substitution

description: Python equation substitution


code:
x="$a first answer$b second answer$c third answer$d fourth answer$SOLUTION: a"
print [i for i in re.split(r"\$\S+",x) if i]

rawDescription: Python regex with string tokenization

description: Python regex with string tokenization


code:
def distswith(fn='fit'):
    """prints out distributions with '.fit' methods.
    where any class with a '._pdf' method is considered a distribution
    """
    import scipy.stats
    for fn in dir(scipy.stats):
        fns=eval('dir(scipy.stats.'+fn+')')
        if '_pdf' in fns and 'fit' in fns:
            print fn

rawDescription: scipy: Which distributions have a "fit" function implemented?

description: Scipy: Which distributions have a "fit" function implemented


code:
def raise_wrapper(wrapped_method=None):
    def method(tmp_instance, *args, **kawrgs):
        raise AttributeError("'%s' object has no attribute '%s'" % (
                type(tmp_instance._parent).__name__, tmp_instance._key))
    if wrapped_method:
        method.__doc__ = wrapped_method.__doc__
    return method

class TemporaryValue(object):
    def __init__(self, parent, key):
        self._parent = parent
        self._key = key

    def __setattr__(self, key, value):
        if key in ('_parent', '_key'):
            return object.__setattr__(self, key, value)

        newval = ObjectLike()
        object.__setattr__(self._parent, self._key, newval)
        return object.__setattr__(newval, key, value)

    __eq__ = raise_wrapper(object.__eq__)
    # __del__ = raise_wrapper()
    # __repr__ = raise_wrapper(object.__repr__)
    __str__ = raise_wrapper(object.__str__)
    __lt__ = raise_wrapper(object.__lt__)
    __le__ = raise_wrapper(object.__le__)
    __eq__ = raise_wrapper(object.__eq__)
    __ne__ = raise_wrapper(object.__ne__)
    __cmp__ = raise_wrapper()
    __hash__ = raise_wrapper(object.__hash__)
    __nonzero__ = raise_wrapper()
    __unicode__ = raise_wrapper()
    __delattr__ = raise_wrapper(object.__delattr__)
    __call__ = raise_wrapper(object.__call__)

class ObjectLike(object):
    def __init__(self):
        pass

    def __getattr__(self, key):
        newtmp = TemporaryValue(self, key)
        object.__setattr__(self, key, newtmp)
        return newtmp

    def __str__(self):
        return str(self.__dict__)

o = ObjectLike()
o.foo.bar = 'baz'
print o.foo.bar
print o.not_set_yet
print o.some_function()
if o.unset > 3:
    print "yes"
else:
    print "no"

rawDescription: Python override __getattr__ for nested assignment, but not for referencing?


code:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print dictionary

rawDescription: Map two lists into a dictionary in Python


code:
print parsed_json["next_cursor_str"]
# 1395095221152647652

rawDescription: Twitter API cursoring in Python

description: Twitter API cursoring in Python


code:
from ipywidgets import Checkbox, interactive
from IPython.display import display

l = ["Dog", "Cat", "Mouse"]
chk = [Checkbox(description=a) for a in l]

def updatePlot(**kwargs):
    print [(k,v) for k, v in kwargs.iteritems()]

interact(updatePlot, **{c.description: c.value for c in chk})

rawDescription: ipywidgets: how to update plot with multiple series based on checkbox selection

description: Ipywidgets: how to update plot with multiple series based on checkbox selection


code: print soup.find('a', href = re.compile(r'.*follow\?page.*'))

rawDescription: beautifulsoup can't find href in file using regular expression

description: Beautifulsoup can't find href in file using regular expression


code:
from pyparsing import *

street_number = Word(nums)('street_number')
street_suffix = oneOf("ST RD DR LN AVE WAY")('street_suffix')
street_name = OneOrMore(~street_suffix + Word(alphas))('street_name')

address = street_number + street_name + street_suffix
result = address.parseString("444 PARK GARDEN LN")
print result.dump()

rawDescription: PyParsing non-greedy match

description: PyParsing non-greedy match


code: print candidate[minid[0]]

rawDescription: getting the element of array while performing Euclidian calculation

description: Getting the element of array while performing Euclidian calculation


code:
d = {}
d['a'] = 0
d['b'] = 60
d['c'] = 100
d['d'] = 160
d['e'] = 200
d['f'] = 240
d['g'] = 280
d['h'] = 320
d['i'] = 400
d['j'] = 420
d['k'] = 500
d['l'] = 520
d['m'] = 540
d['n'] = 620
d['o'] = 640
d['p'] = 660
d['q'] = 700
d['r'] = 720
d['s'] = 780
d['t'] = 800
d['u'] = 840
d['v'] = 860
d['w'] = 880
d['x'] = 940
d['y'] = 960
d['z'] = 980

dict = {}
dict['a'] = 1
dict['b'] = 2
dict['c'] = 3
dict['d'] = 4
dict['e'] = 5
dict['f'] = 6
dict['g'] = 7
dict['h'] = 8
dict['i'] = 9
dict['j'] = 10
dict['k'] = 11
dict['l'] = 12
dict['m'] = 13
dict['n'] = 14
dict['o'] = 14
dict['p'] = 15
dict['q'] = 15
dict['r'] = 16
dict['s'] = 17
dict['t'] = 18
dict['u'] = 18
dict['v'] = 18
dict['w'] = 19
dict['x'] = 19
dict['y'] = 19

first_name = raw_input("what is your first name inital?: ")
middle_initial = raw_input("What is your middle initial?: ")

if first_name in dict.keys():
  value_to_add  = dict.get(first_name)

if middle_initial in d.keys():
 next_value_to_add = d.get(middle_initial)

print value_to_add,next_value_to_add
values_added = value_to_add + next_value_to_add
print values_added

rawDescription: Using 2 dictionaries in python

description: Using 2 dictionaries in python


code:
ifile = 'bin_503_07.csv'

with open(ifile, 'rb') as f:
    reader = csv.reader(f)
    reader.next()  #skips first line
    previous_row = reader.next()  # load first actual line
    for row in reader:   # this already calls "next()"
        print previous_row
        print row
        print   # no need to print "\n", empty "print" already does that
        previous_row = row  # "advance" by replacing previous with current

rawDescription: python csv iteration; printing row 1 and 2, then 2 and 3 and so on

description: Python csv iteration; printing row 1 and 2, then 2 and 3 and so on


code:
from functools import wraps

def decorator(f):
    @wraps(f)
    def _decorator():
        print 'decorator active'
        f()
    return _decorator

@decorator
def foo():
    '''the magic foo function'''
    print 'this is function foo'

help(foo)

rawDescription: Python Decorator Problem with Docstrings


code:
#client
import socket
s = socket.socket()
s.connect(("localhost",3000))
f=open ("tranmit.jpg", "rb")
l = f.read(1024)
while (l):
    s.send(l)
    l = f.read(1024)
s.shutdown(socket.SHUT_WR)
reply =s.recv(1024) # Feedback: would like the receive feedback from the server.
print reply
s.close()

rawDescription: send and receive a file in python sockets

description: Send and receive a file in python sockets


code:
def is_list(p):
    return isinstance(p, list)

def deep_reverse(a):
    a.reverse()
    for i in a:
        if is_list(i):
            deep_reverse(i)  # <=== This is what changed
            print a

rawDescription: Python deep reverse in a list

description: Python deep reverse in a list


code:
from collections import Counter
print Counter(data[k][hash_value] for k in data for hash_value in data[k])
# Counter({u'0.0.0.2': 2, u'127.0.0.1': 1})

rawDescription: Counter in nested dictionary Python

description: Counter in nested dictionary Python


code:
def OnDoubleClick(event):
    item = tree.identify("item", event.x, event.y)
    print "you clicked on", tree.item(item)["text"]

rawDescription: Get the text of a treeview item using it's Id - Treeview Tkinter


code:
import cStringIO
from xml.etree.ElementTree import iterparse

fakefile = cStringIO.StringIO("""<temp>
  <email id="1" Body="abc"/>
  <email id="2" Body="fre"/>
  <email id="998349883487454359203" Body="hi"/>
</temp>
""")
for _, elem in iterparse(fakefile):
    if elem.tag == 'email':
        print elem.attrib['id'], elem.attrib['Body']
    elem.clear()

rawDescription: Iteratively parse a large XML file without using the DOM approach


code:
from threading import Thread
class Worker(Thread):
    def __init__(self):
        Thread.__init__(self) #Runs the thread's constructor

    #Method that is run when the new thread starts
    def run(self):
        #Whatever data processing you have to do can go here
        while True:
            print "Hello from Worker"

w = Worker()
w.start() #Starts a new thread which executes the object's run function

rawDescription: Handling multiple end-users using threading in python


code:
from sqlalchemy.orm import lazyload
joe = (s2.query(User)
    .options(lazyload('addresses'))
    .filter_by(name = "Joe").one())
for addr in joe.addresses:
    print addr.address

rawDescription: Can SQLAlchemy eager/joined loads be suppressed once set up?


code:
from nltk.corpus import wordnet as wn
fish_words = set()
fish_types = set()
for i in wn.all_synsets():
  # if 'fish' exist in a word.
  x = [j for j in i.lemma_names if "fish" in j]
  fish_words.update(x)
  # if a word ends with 'fish'
  y = [j for j in i.lemma_names if "fish" in j[-4:]]
  fish_types.update(y)

print fish_types
print [i.replace("_"," ")[:-4].strip() for i in fish_types]

rawDescription: Extracting a particular type of string from a text file using nltk


code:
soup = BeautifulSoup('your_XML_string')
print soup.find('text').string

rawDescription: How to get XML tag value in Python

description: Get XML tag value in Python


code:
class MyTestClassBase(object):
    # Inherit from `object` so unittest doesn't think these are tests which
    # should be run

    @classmethod
    def setUpClass(cls):
        print "doing expensive setup with", cls.param

    def test_one(self):
        self.assertEqual(self.param, 1)

params = [('test1', 1), ('test2', 2)]

for name, param in params:
    cls_name = "TestMyTestClass_%s" %(name, )
    globals()[cls_name] = type(cls_name, (MyTestClassBase, unittest.TestCase), {
        "param": param,
    })

rawDescription: Python Testing how to run parameterised Testcases and pass a parameter to setupClass


code:
from itertools import groupby

words = ['ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat',  'cbcbbaat', 'caaccbabbt']
for w in words:
    match = False
    if w.startswith('c') and w.endswith('t'):
        temp = w[1:-1]
        s = set(temp)
        match = s <= set('abc') and len(s) == len(list(groupby(temp)))
    print w, "matches" if match else "doesn't match"

rawDescription: Python pattern-matching. Match 'c[any number of consecutive a's, b's, or c's or b's, c's, or a's etc.]t'


code:
lst = [generate_individual(10) for _ in range(N)] #You will need to define N before (or use a constant)
print lst

rawDescription: How do I make a list

description: Make a list


code: print sorted(mydictionary.items(), key=operator.itemgetter(1), reverse=True)[:10]

rawDescription: Sort entries of dictionary in decreasing order and print first n entries


code:
import urllib
import urllib2
import simplejson
import datetime

authURL = "http://api.sample.com/authenticate"
values = {"username" : "user@sample.com",
          "password" : "sample"}

data = urllib.urlencode(values)

req = urllib2.Request(authURL, data)
response = urllib2.urlopen(req)

authToken = simplejson.load(response)["output"]

day = str(datetime.date.today())
dataURL = "http://api.sample.com/data/day/" + day + "/authToken/" + authToken

print simplejson.load(urllib2.urlopen(dataURL))

rawDescription: CURL / Ruby Alternative in Python to fetch data from API


code:
nums = (1, 2, 3, 4)
print "debug: %r" % (nums, )
print "debug: %r" % nums

rawDescription: Why tuple is being used in string format


code:
path = []
for event, elem in ET.iterparse(file_path, events=("start", "end")):
    if event == 'start':
        path.append(elem.tag)
    elif event == 'end':
        # process the tag
        if elem.tag == 'name':
            if 'members' in path:
                print 'member'
            else:
                print 'nonmember'
        path.pop()

rawDescription: ElementTree iterparse strategy

description: ElementTree iterparse strategy


code:
from multiprocessing import Pool

def encrypt(i):
    return bin(i)[2:].zfill(10).decode('hex')

if __name__ == '__main__':
    pool = Pool(processes=4)  # adjust to number of cores
    result = pool.map(encrypt, range(1000))
    print result

rawDescription: Python: Multi-processing a function call inside for loop so that each call runs independently


code:
def read_file():
    if os.path.exists('InputFile.bak'):
        # try:
        with open('InputFile.bak', 'rb') as fname:
            while True:
                try:
                    item_name = cPickle.load(fname)
                    for k, v in item_name.iteritems():
                        print v[0], "\t", v[1],"\t", k
                except EOFError:
                    break
    else:
        item_name = {}

if __name__ == '__main__':
    read_file()

rawDescription: Reading data from file using Python cPickle


code:
import re
myFile = open('syslog','r')
ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', myFile.read() )
print ip

rawDescription: Python - splitting a log and searching for something specific


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class CodeCheckspider(CrawlSpider):
    name = "code_check"

    allowed_domains = ["www.codecheck.info"]
    start_urls = ['http://www.codecheck.info/']

    rules = [
        Rule(LinkExtractor(allow=r'\.kat$'), follow=True),
        Rule(LinkExtractor(allow=r'/id_\d+/'), callback='parse_product'),
    ]

    def parse_product(self, response):
        title = response.xpath('//title/text()').extract()[0]
        print title

rawDescription: Scrapy crawl and follow links within href


code:
from fractions import gcd
def lcm(x,y): return x*y/gcd(x,y)
print reduce(lcm,range(1,21))

rawDescription: Optimizing Python code for Project Euler #5


code:
import argparse as ap

def main():
    parser = ap.ArgumentParser(description="My Script")
    parser.add_argument("--myArg")
    args, leftovers = parser.parse_known_args()

    if args.myArg is not None:
        print "myArg has been set (value is %s)" % args.myArg

rawDescription: Check if argparse optional argument is set or not


code:
import pyparsing as pp

integer = pp.Word(pp.nums).setParseAction(lambda m:int(m[0]))
expr = pp.Forward()
expr << pp.nestedExpr(content=pp.OneOrMore(integer | expr))
manyExpr = pp.OneOrMore(expr)

print manyExpr.parseString('(2 (10 (5 11))) (5 6) (4)')
    #returns [[2, [10, [5, 11]]], [5, 6], [4]]

rawDescription: Issue in Parsing Lisp input to python

description: Issue in Parsing Lisp input to python


code:
def add_comments(request):
    if 'application/x-www-form-urlencoded' in request.META['CONTENT_TYPE']:
        print 'hi'
        data = json.loads(request.body)
        comment = data.get('comment', None)
        id = data.get('id', None)
        title = data.get('title', None)

        post = Post.objects.get(id = id)
        com = Comment()
        com. comments = comment
        com.title = post
        com.save()

rawDescription: Django saving json value to database/model


code:
class NotificationService():
    def __init__(self, path, callback):
        self.path = path
        self.callback = callback

    def start(self):
        mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE \
            | pyinotify.IN_MODIFY
        w = pyinotify.WatchManager()
        wdd = w.add_watch(self.path, mask, rec=True, auto_add=True)
        self.__notifier = pyinotify.ThreadedNotifier(w, fs_event_handler(self.callback))
        self.__notifier.start()
        print 'Service Running...'

    def run(self):
        self.start()

    def stop(self):
        self.__notifier.stop()
        print 'Service Stopped'

rawDescription: enabling start, stop feature for a folder watcher program

description: Enabling start, stop feature for a folder watcher program


code:
def binarySearch(alist, value):

    first = 0
    last = len(alist)-1
    found = False
    while first<=last and not found:
        midpoint = (first + last)//2
        if value == alist[midpoint]:
            found =  True
        else:
            if value < alist[midpoint]:
                last = midpoint-1
            else:
                if value > midpoint:
                    first = midpoint+1
    return found

if binarySearch([1,2,3,4,5,6,7,8],3):
    print "found"

rawDescription: Binary Search python 3.5

description: Binary Search python 3.5


code:
# x = range(6)
x = ["this", "is", "an", "example", "list"]

for prv, nxt in zip(x, x[1:]):
    print prv, nxt

rawDescription: How to select sequential elements from a list?

description: Select sequential elements from a list


code:
from bs4 import BeautifulSoup as BS
soup = BS(html)
print soup.find("a", "nextpostslink").attrs['href']
# returns u'http://cinemassacre.com/category/avgn/page/2/'

rawDescription: Python regex, matching too much

description: Python regex, matching too much


code:
webview.connect('navigation-policy-decision-requested', _on_navigation)
webview.connect('new-window-policy-decision-requested', _on_navigation)

def _on_navigation(webview, frame, request, action, decision):
    print 'Tried to navigate to {}'.format(request.props.uri)
    return False  # not handled, proceed with default action

rawDescription: Embed html button in GTK3 app?

description: Embed html button in GTK3 app