code:
import compiler

def recursive_parse(node,substitutions):

    # look for left hand side of equation and test
    # if it is a variable name

    if hasattr(node.left,"name"):
        if node.left.name in substitutions.keys():
            node.left = substitutions[node.left.name]
    else:

        # if not, go deeper
        recursive_parse(node.left,substitutions)

    # look for right hand side of equation and test
    # if it is a variable name

    if hasattr(node.right,"name"):
        if node.right.name in substitutions.keys():
            node.right = substitutions[node.right.name]
    else:

        # if not, go deeper
        recursive_parse(node.right,substitutions)

def main(input):

    substitutions = {
        "r":"sqrt(x**2+y**2)"
    }

    # each of the substitutions needs to be compiled/parsed
    for key,value in substitutions.items():

        # this is a quick ugly way of getting the data of interest
        # really this should be done in a programatically cleaner manner
        substitutions[key] = compiler.parse(substitutions[key]).getChildNodes()[0].getChildNodes()[0].getChildNodes()[0]

    # compile the input expression.
    expression = compiler.parse(input)

    print "Input:        ",expression

    # traverse the selected input, here we only pass the branch of interest.
    # again, as with above, this done quick and dirty.
    recursive_parse(expression.getChildNodes()[0].getChildNodes()[0].getChildNodes()[1],substitutions)

    print "Substituted:  ",expression

if __name__ == "__main__":
    input = "t = r*p"
    main(input)

rawDescription: Parsing an equation with sub-formulas in python


code:
import qrtools
qr = qrtools.QR()
qr.decode("horn.png")
print qr.data

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

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


code:
for k, v in cgi_fields.items():
    print k, v

rawDescription: Parsing responses from web.py

description: Parsing responses from web.py


code: print wh

rawDescription: What type of list is best for calling specific items?


code:
#!/usr/bin/python
''' This program takes in a relations file and a food text files as inputs
and can be used to update the food text file based on changes in either of these'''

relations = {}
foodDict = {}

# Mapping ingredients to each other in the relations dictionary
with open("relations.txt") as r:
    relationlist=r.read().splitlines()
    for relation in relationlist:
        item, equatedTo = relation.split(': ')
        ingredientsAndCoefficients = equatedTo.split(' + ')
        listIngredients = []
        for ingredient in ingredientsAndCoefficients:
            coefficient, item2 = ingredient.split(' x ')
            # A list of sets of amount and type of ingredient
            listIngredients.append((float(coefficient),item2))
        relations.update({item:listIngredients})

# Creating a food dictionary with values from food.txt and mapping to the relations dictionary
with open("food.txt") as g:
    foodlist=g.read().splitlines()
    for item in foodlist:
        food,value = item.split(': ')
        foodDict.update({food:value})
    for food in relations.keys():
        # (Raw) Ingredients with no left hand side value in relations.txt will not change here.
        value = 0.
        for item2 in range(len(relations[food])):
            # Calculating new value for complex here.
            value += relations[food][item2][0]* float(foodDict[relations[food][item2][1]])
        foodDict.update({food: value })

# Altering the food.txt with the new dictionary values
with open("food.txt",'w') as g:
    for key in sorted(foodDict.keys()):
        g.write(key + ': ' + str (foodDict[key])+ '\n')
        print key + ': ' + str(foodDict[key])

rawDescription: How do I replace lines in a file using data contained elsewhere in the same file?

description: Replace lines in a file using data contained elsewhere in the same file


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

x = [0,1,2,3]
y = [3,2,1,0]

ax.scatter(x,y)

d = ax.collections[0]

d.set_offset_position('data')

print d.get_offsets()

rawDescription: Get positions of points in PathCollection created by scatter()


code:
import collections

with open("data") as f:
        lines=(line.strip().split() for line in f)
        header=next(lines)
        combinations=collections.Counter(
                ", ".join(header[i]
                        for i in xrange(len(combination))
                                if combination[i] != '0')
                        for combination in lines)
        for key, value in combinations.iteritems():
                print value, '\t', key

rawDescription: Computing the combinations for presence or absence of a factor in a table


code:
from collections import defaultdict
paircount = defaultdict(int)
pairtime = defaultdict(float)
pairper = defaultdict(float)
timeavg = defaultdict(float)

#get number of pair occurrences and total time
with open('input.txt', 'r') as f, open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        paircount[pair] += 1
        pairtime[pair] += float(line[2])

    for pair, freq in paircount.iteritems():
        timeavg = pairtime[pair] / freq
        o.write("%s %s %s %s %s \n" % (pair[0], pair[1], freq, pairtime[pair], timeavg))

print 'done'

rawDescription: Find Average of timestamp

description: Find Average of timestamp


code:
import xml.etree.ElementTree

stop_escape   = lambda text: text.replace("&#", "|STOP_ESCAPE|")
resume_escape = lambda text: text.replace("|STOP_ESCAPE|", "&#")

xml_text = """
<root>
    <mytag>
        data_with_space
    </mytag>
</root>"""
root = xml.etree.ElementTree.fromstring(stop_escape(xml_text))
mytag_txt = resume_escape(root.find("mytag").text)
print "original text: ", repr(mytag_txt)
print "stripped text: ", repr(mytag_txt.strip())

rawDescription: How can I differentiate regular whitespaces and escaped ones ( ) when parsing XML with xml.etree.ElementTree (python)

description: Differentiate regular whitespaces and escaped ones ( ) when parsing XML with xml.etree.ElementTree (python)


rawDescription: Compare values of two arrays in python

description: Compare values of two arrays in python


code:
file_read = csv.DictReader(open('/tmp/test.csv', 'rb'),
    ['name','street','area'], delimiter=';')

for row in file_read:
    print row

rawDescription: Python adding headers to CSV

description: Python adding headers to CSV


rawDescription: Dictionary help in Python

description: Dictionary help in Python


code:
for link in soup.select('a[href^=/livechess/game?id=]'):
    print link['href']

rawDescription: Game scraping python regular expression

description: Game scraping python regular expression


code:
def find_parent(search_term,collection,parent=None):
  if isinstance(collection,dict):
    for key,value in collection.iteritems():
      if key.lower() == search_term.lower():
        print "the parent of %s is %s" % (key,parent)
        return parent
      if isinstance(value,list):
        for v in value:
          parent = find_parent(search_term,v,key)
          if parent is not None: return parent

my_child = "two"
tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] }
find_parent(my_child,tree)

rawDescription: Why does my recursive function return "None"?


code:
def aForwardShiftingDependenceLOOP(): # proposed code-revision
    aStopWATCH.start()                # ||||||||||||||||||.start
    for thisPtr in range( 1, len( sig ) ):
        #        |vvvvvvv|------------# FORWARD-SHIFTING-LOOP DEPENDENCE
        prevPtr = thisPtr - 1  #|vvvvvvv|--STEP-SHIFTING avoids Numpy syntax
        if ( sig[ thisPtr] < out[prevPtr] ):
            out[  thisPtr] = out[prevPtr] * beta
        else:
            out[  thisPtr] = out[prevPtr] * alpha + ( aConst * sig[thisPtr] )
    usec = aStopWATCH.stop()          # ||||||||||||||||||.stop
    print usec, " [usec]"
aForwardShiftingDependenceLOOP()
def anOriginalForLOOP():
    aStopWATCH.start()
    for n in range( 1, len( sig ) ):
        if ( np.abs( sig[n] ) >= out[n-1] ):
            out[n] = out[n-1] * alpha + ( 1 - alpha ) * np.abs( sig[n] )
        else:
            out[n] = out[n-1] * beta
    usec = aStopWATCH.stop()
    print usec, " [usec]"
anOriginalForLOOP()

rawDescription: Vectorize a python loop over a numpy array


code:
import re
fabric = ['Combed Cotton', 'Polyester', 'Organic Cotton', 'Bamboo Viscose']
fabric_type = ['Brushed 3-ply', 'Fine Jersey']

test_cases = [
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Certified Organic Cotton Jersey 145 g / 4.3 oz.",
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Certified Organic Cotton Pique 180 g / 5.3 oz.",
    "100% Certified Organic Cotton Pique 180 g / 5.3 oz.",
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Certified Organic Cotton Fine Jersey 115g / 3.4 oz.",
    "100% Certified Organic Cotton Fine Jersey 115g / 3.4 oz.",
    "100% Organic Cotton Brushed 3-ply 310 g / 9.1 oz.",
    "100% Organic Cotton Brushed 3-ply 310 g / 9.1 oz.",
    "100% Organic Cotton Brushed 3-ply 290 g / 8.6 oz.",
    "100% Organic Cotton Brushed 3-ply 290 g / 8.6 oz.",
    "100% Certified Organic Cotton Brushed 3-ply 280-300g / 8.3-8.9 oz.",
    "100% Certified Organic Cotton Brushed 3-ply 280-300g / 8.3-8.9 oz.",
    "100% Certified Organic Cotton Brushed 3-ply 280-300g / 8.3-8.9 oz.",
    "100% Certified Organic Cotton Brushed 3-ply 280-300g / 8.3-8.9 oz.",
    "100% Certified Organic Cotton Brushed 3-ply 280-300g / 8.3-8.9 oz.",
    "100% Organic Cotton Plain Weave 120 g / 3.5 oz.",
    "100% Organic Cotton Twill Weave 170 g / 5.1 oz.",
    "100% Certified Organic Cotton Jersey 155 g / 4.6 oz.",
    "100% Combed Cotton Interlock 240g / 7.2 oz.",
    "100% Combed Cotton Interlock 200g / 6 oz.",
    "100% Combed Cotton Jersey 165g / 4.95 oz.  (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Interlock 240g / 7.2 oz.",
    "100% Combed Cotton 1x1 Rib 240g / 7.2 oz.",
    "100% Combed Cotton Jersey 150g / 4.5 oz",
    "100% Combed Cotton Jersey 155g / 4.65 oz.  (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 85% Cotton 15% Viscose)",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 85% Cotton 15% Viscose)",
    "100% Combed Cotton Jersey 150g / 4.5 oz (Melange Grey: 74% Cotton 26% Polyester)",
    "100% Combed Cotton Jersey 160g / 4.8 oz.",
    "100% Combed Cotton Sheer Jersey 90g / 2.65 oz.",
    "100% Combed Cotton Sheer Jersey 115g / 3.4 oz.",
    "70% Bamboo Viscose 30% Organic Cotton Fine Jersey 115g / 3.4 oz.",
    "70% Bamboo Viscose 30% Organic Cotton Fine Jersey 115g / 3.4 oz.",
    "70% Bamboo Viscose 30% Organic Cotton Jersey 150g / 4.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "45% Combed Cotton 45% Modal 10% Lycra Elastane Jersey 240g / 7.2 oz.",
    "100% Organic Cotton Canvas Weave 340g",
    "100% Tencel Lyocell Fine Jersey 120g / 3.5 oz.",
    "100% Tencel Lyocell Fine Jersey 120g / 3.5 oz.",
    "100% Tencel Lyocell Fine Jersey 120g / 3.5 oz.",
    "100% Combed Cotton Fine Jersey 115g",
    "100% Certified Organic Cotton Brushed 3-ply 280 / 8.3 oz.",
    "100% Certified Organic Cotton Interlock 200 / 5.9 oz.",
    "100% Certified Organic Cotton Interlock 200 / 5.9 oz.",
    "100% Certified Organic Cotton Interlock 200 / 5.9 oz.",
    "100% Certified Organic Cotton Interlock 200 / 5.9 oz.",
    "100% Organic Cotton Brushed 3-ply 290 g / 8.6 oz.",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 60% Cotton 40% Polyester)",
    "80% Combed Cotton 20% Polyester Brushed 3-Ply 320g / 9.4 oz",
    "80% Combed Cotton 20% Polyester Brushed 3-Ply 320g / 9.4 oz",
    "100% Tencel Lyocell Fine Jersey 120g / 3.5 oz",
    "100% Tencel Lyocell Fine Jersey 120g / 3.5 oz",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 60% Cotton 40% Polyester)",
    "Printed on FSC Mix certified paper using vegetable inks",
    "96% Cotton 4% Polyester Fine Speckled Jersey 130-150 g/m2",
    "96% Cotton 4% Polyester Fine Speckled Jersey 130-150 g/m2",
    "100% Combed Cotton Supersoft Jersey 175 g/m2",
    "60% Combed Cotton 40% Polyester Brushed 3-ply 280 g/m2",
    "60% Combed Cotton 40% Polyester Brushed 3-ply 280 g/m2",
    "100% Combed Cotton Supersoft Jersey 175 g/m2",
    "100% Combed Cotton Supersoft Jersey 175 g/m2",
    "100% Combed Cotton Jersey 135 g/m2 (Mélange Grey: 60% Cotton 40% Polyester) Jersey 135 g/m2",
    "70% Bamboo Viscose 30% Organic Cotton Jersey 150 g/m2",
    "70% Bamboo Viscose 30% Organic Cotton Jersey 115 g/m2",
    "100% Organic Cotton Jersey 155 g/m2",
    "100% Organic Cotton Jersey 155 g/m2",
    "60% Recycled Organic Cotton 40% Recycled Polyester Jersey 165g / 4.95 oz.",
    "60% Recycled Organic Cotton 40% Recycled Polyester Jersey 165g / 4.95 oz.",
    "60% Recycled Organic Cotton 40% Recycled Polyester Brushed 2-ply 280 / 8.3 oz.",
    "60% Recycled Organic Cotton 40% Recycled Polyester Twill Weave 220 g / 6.5 oz.",
    "60% Recycled Organic Cotton 40% Recycled Polyester Twill Weave 220 g / 6.5 oz.",
    "100% Combed Cotton Interlock 240g / 7.2 oz.",
    "100% Combed Cotton Jersey 165g / 4.95 oz.  (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Sheer Jersey 115g / 3.4 oz.",
    "100% Combed Cotton Jersey 150g / 4.5 oz",
    "100% Combed Cotton Jersey 155g / 4.65 oz.  (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Jersey 150 g/m2 (Mélange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 60% Cotton 40% Polyester)",
    "50% Cotton, 50% Polyester Jersey 160g / 4.7 oz.",
    "50% Cotton, 50% Polyester Jersey 160g / 4.7 oz.",
    "100% Combed Cotton Sheer Jersey 90g / 2.65 oz.",
    "100% Combed Cotton Sheer Jersey 90g / 2.65 oz.",
    "100% Combed Cotton Sheer Jersey 105g / 3.15 oz.",
    "100% Combed Cotton Sheer Jersey 115g / 3.4 oz.",
    "70% Bamboo Viscose 30% Organic Cotton Fine Jersey 115g / 3.4 oz.",
    "70% Bamboo Viscose 30% Organic Cotton Jersey 150g / 4.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester Brushed 3-ply 320 g/m2",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester Brushed 3-ply 320 g / 9.4 oz",
    "80% Combed Cotton 20% Polyester 320g / 9.4 oz.",
    "80% Combed Cotton 20% Polyester Brushed 3-Ply 320g / 9.4 oz",
    "80% Combed Cotton 20% Polyester Brushed 3-Ply 320g / 9.4 oz",
    "100% Tencel Lyocell Fine Jersey 120g / 3.5 oz.",
    "100% Combed Cotton Fine Jersey 115g / 3.4 oz. (Melange Grey: 60% Cotton 40% Polyester)",
    "100% Certified Organic Cotton Interlock 200 g/m2",
    "100% Certified Organic Cotton Interlock 200 g/m2",
    "100% Certified Organic Cotton Interlock 200 g/m2",
    "100% Certified Organic Cotton Interlock 200 g/m2",
    "100% Combed Cotton Jersey 150g / 4.5 oz (Melange Grey: 74% Cotton 26% Polyester)",
    "100% Combed Cotton Jersey 150g / 4.5 oz",
    "100% Combed Cotton Jersey 130g / 3.8 oz",
    "100% Combed Cotton Jersey 130g (Mélange Grey: 85% Cotton 15% Viscose)",
    "100% Combed Cotton  Jersey 150g (Mélange Grey: 85% Cotton 15% Viscose) (Other Mélange: 60% Cotton 40% Polyester)",
    "100% Combed Cotton Jersey 150g / 4.5 oz",
    "100% Combed Cotton Jersey 150g / 4.5 oz",
    "                                             | 99% Cotton 1% Viscose)",
    "100% Combed Cotton Jersey 130g",
    " |0% Combed Cotton Fine Jersey 115g (Mélange Grey: 85% Cotton 15% Viscose) (Mélange White: 99% Cotton 1% Viscose)",
    "80% Combed Cotton 20% Polyester Brushed 3-Ply 320g / 9.4 oz",
    "100% Combed Organic Cotton Jersey 155g / 4.6 oz",
    "100% Combed Cotton Jersey 130g"
]

fabric_rx = re.sub("\s+","\s+","|".join(fabric))
fabric_type_rx = re.sub("\s+","\s+","|".join(fabric_type))

expr = "(?:\d{1,3}\%\s(?:"+ fabric_rx +")(?:\s+))|(?:"+ fabric_type_rx +"(?:\s+))|(?:.{2,})"
rx = re.compile(expr)

for test in test_cases:
    try:
        results = re.findall(rx, test)
        for idx, item in enumerate(results):
            results[idx] = item.strip()
        print results
    except:
        print "Format error: %s" % test

rawDescription: python split using re and a lookup to a list

description: Python split using re and a lookup to a list


code:
names = ['Anna', 'Grant', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
b_names = filter(lambda s: s.startswith('B'), names)
print b_names

rawDescription: How to use filter() on a string and get multiple word occurences?

description: Use filter() on a string and get multiple word occurences


code:
import numpy as np
import pandas as pd

def fill_column(house):
    house = house.copy()
    non_nans = house[~house.apply(np.isnan)]
    start, end = non_nans.index[0], non_nans.index[-1]
    house.ix[start:end] = house.ix[start:end].fillna(method='ffill')
    return house

house1 = pd.Series([np.nan, np.nan, np.nan, 200000, 200000, np.nan, np.nan, 200000, 190000, np.nan, np.nan, np.nan])
print fill_column(house1)

rawDescription: Using pandas to fill gaps only, and not NaNs on the ends


code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def one_second(event):
    global count
    count += 1
    print "Working %s" % count

def onclick(event):
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
    event.button, event.x, event.y, event.xdata, event.ydata)

count = 0
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', onclick)
plt.plot([0,1,2],[5,10,15])
ani = animation.FuncAnimation(fig, one_second, repeat=True, interval=1000)
plt.show()

rawDescription: Matplotlib event handling without use of `show()`


code:
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")

# 1. Win32_DiskDrive
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_DiskDrive WHERE InterfaceType = \"USB\"")
DiskDrive_DeviceID = colItems[0].DeviceID.replace('\\', '').replace('.', '')
DiskDrive_Caption = colItems[0].Caption

print 'DiskDrive DeviceID:', DiskDrive_DeviceID

# 2. Win32_DiskDriveToDiskPartition
colItems = objSWbemServices.ExecQuery("SELECT * from Win32_DiskDriveToDiskPartition")
for objItem in colItems:
    if DiskDrive_DeviceID in str(objItem.Antecedent):
        DiskPartition_DeviceID = objItem.Dependent.split('=')[1].replace('"', '')

print 'DiskPartition DeviceID:', DiskPartition_DeviceID

# 3. Win32_LogicalDiskToPartition
colItems = objSWbemServices.ExecQuery("SELECT * from Win32_LogicalDiskToPartition")
for objItem in colItems:
    if DiskPartition_DeviceID in str(objItem.Antecedent):
        LogicalDisk_DeviceID = objItem.Dependent.split('=')[1].replace('"', '')

print 'LogicalDisk DeviceID:', LogicalDisk_DeviceID

# 4. Win32_LogicalDisk
colItems = objSWbemServices.ExecQuery("SELECT * from Win32_LogicalDisk WHERE DeviceID=\"" + LogicalDisk_DeviceID + "\"")
print 'LogicalDisk VolumeName:', colItems[0].VolumeName
print

# putting it together
print DiskDrive_Caption
print colItems[0].VolumeName, '(' + LogicalDisk_DeviceID + ')'

rawDescription: Python: get name of a USB flash drive device [windows]


code:
class MyBase(object):
    def p(self):
        print [(attr, getattr(self, attr)) for attr in dir(self)
            if not callable(getattr(self, attr)) and not attr.startswith('__')]

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

description: Access a class field values in its base class


code:
def print_all_fields_starting_with(obj, starter):
    fields = [x for x in obj._meta.get_all_field_names() if x.startswith(starter)]
    for field in fields:
        print getattr(obj, field)

rawDescription: In model save() how to get all field starting with 'foo'


code: print list(generateOutput(input, 0, -2))

rawDescription: Algorithm to offset a list of data

description: Algorithm to offset a list of data


code:
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']

print [x for w in l for x in w.split()].index('1word2')

rawDescription: Absolute position from relative

description: Absolute position from relative


code:
print u'Hello World!'
print (u'Hello World',)

rawDescription: how to delete the "u and ' ' " before the of database table display by python

description: Delete the "u and ' ' " before the of database table display by python


code:
import heapq
from operator import itemgetter
import random
d = {'any{}'.format(i): random.randrange(5000) for i in range(1243)}
for key, value in heapq.nlargest(30, d.iteritems(), key=itemgetter(1)):
    print '{:<7} {:>4}'.format(key, value)

rawDescription: How to find to 30 biggest numbers from 1000 in dict?

description: Find to 30 biggest numbers from 1000 in dict


code:
from BeautifulSoup import BeautifulSoup
import urllib2

base_url = 'http://www.ksl.com'
url = base_url + '/index.php?nid=443'
model = "Honda" # this is the name of the model to look for

# Load the page and process with BeautifulSoup
handle = urllib2.urlopen(url)
html = handle.read()
soup = BeautifulSoup(html)

# Collect all the ad detail boxes from the page
divs = soup.findAll(attrs={"class" : "detailBox"})

# For each ad, get the title
# if it contains the word "Honda", get the link
for div in divs:
    title = div.find(attrs={"class" : "adTitle"}).text
    if model in title:
        link = div.find(attrs={"class" : "listlink"})["href"]
        link = base_url + link
        # Now you have a link that you can download and scrape
        print title, link
    else:
        print "No match: ", title

rawDescription: Fill out javascript with python?

description: Fill out javascript with python


code:
p = Point(1, 2, 3)
p.classification = 50  # calls the second `classification` method, the setter, for you.
print p.classification # calls the first `classification` method, the getter.

rawDescription: Resolving how to give an attribute in a class in Python


rawDescription: Extracting % occurrences in a string

description: Extracting % occurrences in a string


code:
class Quote(db.Model):
    author = db.StringProperty()
    string = db.StringProperty()

class MainHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        quotes = Quote.all()
        path = os.path.join(os.path.dirname(__file__),'quotery.html')
        template_values = {'quotes':quotes,'user':user,'login_url':users.create_login_url('/')}
        self.response.out.write(template.render(path, template_values))

class QuoteHandler(webapp.RequestHandler):

    def __init__(self):
        self.actions = {'fetch':self.fetch, 'random':self.fetch_random}

        #Memcache the number of quotes in the datastore, to minimize datastore calls
        self.quote_count = memcache.get('quote_count')
        if not self.quote_count:
            self.quote_count = self.cache_quote_count()

    def cache_quote_count(self):
        count = Quote.all().count()
        memcache.add(key='quote_count', value=count, time=3600)
        return count

    def get(self, key):
        if key in self.actions:
            action = self.actions[key]
            action()

    def fetch(self):
        for quote in Quote.all():
            print 'Quote!'
            print 'Author: ',quote.author
            print 'String: ',quote.string
            print

    def fetch_random(self):
        max_offset = self.quote_count-1
        random_offset = random.randint(0,max_offset)
        '''self.response.out.write(max_offset)
        self.response.out.write('\n<br/>')
        self.response.out.write(random_offset)'''
        try:
            query = db.GqlQuery("SELECT * FROM Quote")
            quotes = query.fetch(1,random_offset)
            return quotes
            '''for quote in quotes:
                self.response.out.write(quote.author)
                self.response.out.write('\n')
                self.response.out.write(quote.string)'''
        except BaseException:
            raise

class NewQuote(webapp.RequestHandler):

    def post(self):
        author = self.request.get('quote_author')
        string = self.request.get('quote_string')

        if not author or not string:
            return False
        quote = Quote()
        quote.author = author
        quote.string = string
        quote.put()
        QuoteHandler().cache_quote_count()
        self.redirect("/")
        #return True

class QuotesView(webapp.RequestHandler):

    def __init__(self):
        self.actions = {'all':self.view_all,'random':self.view_random,'get':self.view_single}

    def get(self, key):
        if not key or key not in self.actions:
            self.view_all()
        if key in self.actions:
            action = self.actions[key]
            action()

    def view_all(self):
        print 'view all'

    def view_random(self):
        quotes = QuoteHandler().fetch_random()
        template_data = {}

        for quote in quotes:
            template_data['quote'] = quote

        template_path = os.path.join(os.path.dirname(__file__),'base_view.html')
        self.response.out.write(template.render(template_path, template_data))

    def view_single(self):
        print 'view single'

def main():
    application = webapp.WSGIApplication([('/quote/new',NewQuote),(r'/quotes/(.*)',QuotesView),(r'/quote/(.*)',QuoteHandler),('/', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)

rawDescription: Is this the correct way of doing/handling url rewrite in App Engine/ Python?


code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
magical_class = "Nd92KSx3u2"

class WebPage(QObject):
    def __init__(self, data, parent=None):
        super(WebPage, self).__init__(parent)
        self.output = []
        self.data = data
        self.page = QWebPage()
        self.page.loadFinished.connect(self.process)

    def start(self):
        self.page.mainFrame().setHtml(self.data)

    @Slot(bool)
    def process(self, something=False):
        self.page.setViewportSize(self.page.mainFrame().contentsSize())
        frame = self.page.currentFrame()
        elements = frame.findAllElements('span[class="%s"]' % magical_class)
        for e in elements:
            s = e.toPlainText()
            rect = e.geometry()
            dim = [rect.x(), rect.y(),
                rect.x() + rect.width(), rect.y() + rect.height()]
            if s and rect.width() > 0 and rect.height() > 0: print dim, s

if __name__ == '__main__':
    app = QApplication(sys.argv)
    data = open(sys.argv[1]).read()
    webpage = WebPage(data)
    webpage.start()

rawDescription: generate list of text content with pyqt?

description: Generate list of text content with pyqt


rawDescription: cutting structured numpy arrays

description: Cutting structured numpy arrays


code:
dfs = []
#create empty df for output
d = pd.DataFrame()

for root, dirs, files in os.walk(normSource, topdown=False):
    for name in files:
        print root
        print name
        if name.startswith('201510') and name.endswith('client.csv'):
            #only read columns from list cols
            dfs.append(pd.read_csv(os.path.join(root, name), sep=',', index_col=False, usecols=cols))
            df = pd.concat(dfs, ignore_index=True)

#all files in one dataframe
print df.head()

df['ten_avg'] = df.iloc[:, 30:50].sum(axis=1).astype('int64') / 20
df['twenty_avg'] = df.iloc[:, 30:70].sum(axis=1).astype('int64') / 40
print df.head()

#output to csv, remove index
df.to_csv(OutputCSV, sep=",", index=False)

rawDescription: Concatenating multiple CSV files into a Dataframe and outputing to Master CSV


code:
import gdb

def is_container(v):
    c = v.type.code
    return (c == gdb.TYPE_CODE_STRUCT or c == gdb.TYPE_CODE_UNION)

def is_pointer(v):
    return (v.type.code == gdb.TYPE_CODE_PTR)

def print_struct_follow_pointers(s, level_limit = 3, level = 0):
    indent = ' ' * level

    if not is_container(s):
        gdb.write('%s\n' % (s,))
        return

    if level >= level_limit:
        gdb.write('%s { ... },\n' % (s.type,))
        return

    gdb.write('%s {\n' % (s.type,))
    for k in s.type.keys():
        v = s[k]
        if is_pointer(v):
            gdb.write('%s %s: %s' % (indent, k, v))
            try:
                v1 = v.dereference()
                v1.fetch_lazy()
            except gdb.error:
                gdb.write(',\n')
                continue
            else:
                gdb.write(' -> ')
            print_struct_follow_pointers(v1, level_limit, level + 1)
        elif is_container(v):
            gdb.write('%s %s: ' % (indent, k))
            print_struct_follow_pointers(v, level_limit, level + 1)
        else:
            gdb.write('%s %s: %s,\n' % (indent, k, v))
    gdb.write('%s},\n' % (indent,))

class PrintStructFollowPointers(gdb.Command):
    '''
    print-struct-follow-pointers [/LEVEL_LIMIT] STRUCT-VALUE
    '''
    def __init__(self):
        super(PrintStructFollowPointers, self).__init__(
            'print-struct-follow-pointers',
            gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL, False)

    def invoke(self, arg, from_tty):
        s = arg.find('/')
        if s == -1:
            (expr, limit) = (arg, 3)
        else:
            if arg[:s].strip():
                (expr, limit) = (arg, 3)
            else:
                i = s + 1
                for (i, c) in enumerate(arg[s+1:], s + 1):
                    if not c.isdigit():
                        break
                end = i
                digits = arg[s+1:end]
                try:
                    limit = int(digits)
                except ValueError:
                    raise gdb.GdbError(PrintStructFollowPointers.__doc__)
                (expr, limit) = (arg[end:], limit)
        try:
            v = gdb.parse_and_eval(expr)
        except gdb.error, e:
            raise gdb.GdbError(e.message)

        print_struct_follow_pointers(v, limit)

PrintStructFollowPointers()

rawDescription: gdb-python : Parsing structure's each field and print them with proper value, if exists

description: Gdb-python : Parsing structure's each field and print them with proper value, if exists


code:
from bs4 import BeautifulSoup
import urllib2
#url="http://mywebsite.com/"
#page=urllib2.urlopen(url)

def getdata(col):
    record = []
    for image in col.findAll('img'):
        src = image.get('src')
        record.append(src)
    for a in col.findAll('a'):
        href = a.get('href')
        record.append(href)
    if col.string:
        record.append(col.string.strip())
    return record

def extract():
    url="test.html"
    soup = BeautifulSoup(open(url).read())

    records = []
    tabledata = soup.find("table", {"class" : "class1"})
    for row in tabledata.findAll('tr'):
        cols = row.findAll('td')
        for col in cols:
            record = getdata(col)
            records.extend(record)
    return records

if __name__ == "__main__":
    records = extract()
    print "recorsd:", records
    for v in records:
        print v

rawDescription: Beatifulsoup of href

description: Beatifulsoup of href


code:
def find_weights(W):
    weights = []
    i = 0
    while sum(weights) < W:
        weights.append(3 ** i)
        i += 1
    weights.pop()
    weights.append(W - sum(weights))
    return weights

print find_weights(40)
#output:
[1, 3, 9, 27]

rawDescription: Solving Puzzle in Python

description: Solving Puzzle in Python


code:
other_list = ['foo', 'bar    ', 'baz    ']
filtered_list = [x for x in other_list
                 if not '    ' in x or '    ' in other_list[int(other_list.index(x) -1)]]
print filtered_list

rawDescription: "If...or..." statement inside list comprehension?


code:
artist = network.get_artist("Skinny Puppy")
event = artist.get_upcoming_events()[0]
venue = event.get_venue()
print venue.info

rawDescription: Retrieving Venue Information with pylast and last.fm


code: print [t(tok) for (t, tok) in zip((int, str, int), raw_input().split())]

rawDescription: Typed input in python?

description: Typed input in python


code:
def myPkgs():
    txt = sys.argv # self.myPKG
    reg = re.compile(r"^(?P<Package>.*?)-(?P<Version>\d.*?)\.(?:noarch|x86_64)$")

    pkg_list = []

    for i in txt:
        m = reg.match(i)
        if m:
            pkg_dict = m.groupdict()
            pkg_list.append(pkg_dict)
        else:
            print "No Packet named: %s found" % i

        yield pkg_list

rawDescription: merge multiple regex into one which could "catch them all"

description: Merge multiple regex into one which could "catch them all"


code:
import itertools

for character in itertools.cycle(range(ord('a'), ord('z'))):
    if "(++info++)" not in decoded_str:
        break
    decoded_str = decoded_str.replace("(++info++)", "(++info {0}++)".format(chr(character)), 1)

print decoded_str

rawDescription: Replace a pattern in python

description: Replace a pattern in python


code:
import pandas as pd
dict_data = {
    'AAseq': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'],
    'Biorep': ['A', 'A', 'A'],
    'Techrep': [1, 1, 1],
    'Treatment': ['A', 'B', 'C'],
    'mz':[500.0, 500.5, 501.0]
}
df_a = pd.DataFrame(dict_data)

dict_data = {
    'AAseq': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'],
    'Biorep': ['A', 'A', 'A'],
    'Techrep': [1, 1, 1],
    'Treatment': ['C', 'B', 'A'],
    'inte':[1100.0, 1050.0, 1010.0]
}
df_b = pd.DataFrame(dict_data)

print pd.merge(left=df_a, right=df_b, on=['AAseq', 'Biorep', 'Techrep', 'Treatment'])

rawDescription: Python Pandas concatenate/merge DataFrames using index or column identifiers


code:
def myupdater(current, total):
    print "downloaded {0}/{1} so far".format(current, total)

mega.download('xxx', '/tmp', 'foo', callback=myupdater)

rawDescription: Parsing print in python

description: Parsing print in python


code:
k = [hamming_distance(x, y) for x, y in zip(w,c)]
print k
print sum(k)

rawDescription: Iterative summation of output generated by a function in a for loop (python)


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

print 'number of arguments: ', len(sys.argv)
#we know sys.argv[0] is the script name, let's look at sys.argv[1]
print sys.argv[1]

rawDescription: How to pass Bash variables as Python arguments

description: Pass Bash variables as Python arguments


code:
import networkx as nx
from math import *
import matplotlib.pylab as plt
import itertools as it

def draw_circle_around_clique(clique,coords):
    dist=0
    temp_dist=0
    center=[0 for i in range(2)]
    color=colors.next()
    for a in clique:
        for b in clique:
            temp_dist=(coords[a][0]-coords[b][0])**2+(coords[a][1]-coords[b][2])**2
            if temp_dist>dist:
                dist=temp_dist
                for i in range(2):
                    center[i]=(coords[a][i]+coords[b][i])/2
    rad=dist**0.5/2
    cir = plt.Circle((center[0],center[1]),   radius=rad*1.3,fill=False,color=color,hatch=hatches.next())
    plt.gca().add_patch(cir)
    plt.axis('scaled')
    # return color of the circle, to use it as the color for vertices of the cliques
    return color

global colors, hatches
colors=it.cycle('bgrcmyk')# blue, green, red, ...
hatches=it.cycle('/\|-+*')

# create a random graph
G=nx.gnp_random_graph(n=7,p=0.6)
# remember the coordinates of the vertices
coords=nx.spring_layout(G)

# remove "len(clique)>2" if you're interested in maxcliques with 2 edges
cliques=[clique for clique in nx.find_cliques(G) if len(clique)>2]

#draw the graph
nx.draw(G,pos=coords)
for clique in cliques:
    print "Clique to appear: ",clique
nx.draw_networkx_nodes(G,pos=coords,nodelist=clique,node_color=draw_circle_around_clique(clique,coords))

plt.show()

rawDescription: Graphviz - Drawing maximal cliques

description: Graphviz - Drawing maximal cliques


code:
from itertools import groupby
def key(item):
    return [int(x) for x in item[1].split()[:3]]

master_lst = [['Introduction', '0 11 0 1 0'],
              ['Floating', '0 11 33 1 0'],
              ['point', '0 11 33 1 1'],
              ['numbers', '0 11 33 1 2'],
              ['IEEE', '0 11 58 1 0'],
              ['Standard', '0 11 58 1 1'],
              ['754', '0 11 58 1 2']]

for k,v in groupby(master_lst,key=key):
    print ' '.join(x[0] for x in v) +' ' + ' '.join(str(x) for x in k)

rawDescription: How can I cluster a list of lists in Python based on string indices? Need insight

description: Cluster a list of lists in Python based on string indices? Need insight


code:
class Vec2D(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        my_name = '<unknown>'
        namespace = globals().copy()
        for name,obj in namespace.items():
            if obj is self:
                my_name = name
                break
        return "\n".join(["{!r}:",
                          "  X coordinate is {}",
                          "  Y coordinate is {}"]).format(my_name, self.x, self.y)

if __name__ == '__main__':
    mypoint1 = Vec2D(0,1)
    mypoint2 = Vec2D(1,2)

    print mypoint1
    print mypoint2

rawDescription: how to reach to the instance name of a class?

description: Reach to the instance name of a class


code:
import StringIO
infile = StringIO.StringIO(input)

def count_cycles_in_file(f, n):
    cycles = 0
    while True:
        print 'in_count_cycles_in_file'
        try:
            read_until_start(f, n)
            read_until_end(f, n)
            cycles += 1
        except StopIteration:
            # EOF
            break
        print 'cycles:', cycles
    return cycles

def read_until_start(f, n):
    line = f.readline()
    while line:
        numbers = map(int, line.split(';'))
        if n in numbers:
            return
        line = f.readline()
    # EOF
    raise StopIteration()

def read_until_end(f, n):
    line = f.readline()
    while line:
        numbers = map(int, line.split(';'))
        if not n in numbers:
            return
        line = f.readline()
    # EOF
    raise StopIteration()

rawDescription: identify an event and recurrance of number

description: Identify an event and recurrance of number


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

child = pexpect.spawn("/.main")
for line in child:
    print line,
child.close()

rawDescription: Python C program subprocess hangs at "for line in iter"


code:
res = patt.parseString(test)
print res.desc
print res.numgroups
for ng in res.numgroups: print sum(ng)

rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


rawDescription: Python: Applying common keys from one Dictionary to another


code:
fname = 'dogD.txt'
fh = open(fname)
res = []
for line in fh:
    t2 = line.strip().split()
    res += t2
print res

rawDescription: make one list from multi items in a variable in python

description: Make one list from multi items in a variable in python


code:
a = [ 2,3,4,1]                           # Initialize the array with input
o = []                                   # Have a empty list to hold the output
n = len(a)                               # Get the length of the array
for i in range(n):                       # Loop 'n' times
    x=a[:]                               # Get a copy of the array. '[:]' is the  slicing operator. '[:]' means to copy all the elements of the list to 'x'
    x[i],x[(i+1)%n] = x[(i+1)%n],x[i]    # Swap the adjacent two elements. We require '%' modulus operator to make the list circular
    o.append(x)                          # Add the changed list to the output array
print o                                  # Print the output array

rawDescription: Finding one transposition permutation from a list in Python and C


rawDescription: chunk of data into fixed lengths chunks and then add a space and again add them all as a string

description: Chunk of data into fixed lengths chunks and then add a space and again add them all as a string


code:
import dis
def s(): print "a" "b"
dis.dis(s)
def s(): print "ab"
dis.dis(s)
def s(): print "a"+"b"
dis.dis(s)

rawDescription: Python parser/compiler vs. interpreter, and string concatenation compile-time vs. run-time?


code: print raw_input("input something")

rawDescription: Is it possible to suppress Python's escape sequence processing on a given string without using the raw specifier?


code:
sentinel = range(6)

def anything_but(values):
    values = map(str, values)
    def inner():
        i = raw_input()
        if i in values:
            return None
        return i
    return inner

lines = []
for i in iter(anything_but(sentinel), None):
    lines.append(i)

print lines

rawDescription: Error in input: Python

description: Error in input: Python


code:
def convert(lst):
    return [ [x, convert(y)] if y else x for x, y in lst]

result = convert(stack[0])
print result
# ['a', ['b', ['c', 'd']], ['e', ['f']]]

rawDescription: Python: Read a list with tree depth level and output a tree like nested list


code: print "<%.*s>" % (len(text)-2,text)

rawDescription: variable length of %s with the % operator in python

description: Variable length of %s with the % operator in python


code:
def find_maximum_subarray_bf(a):        #bf for brute force
    p1 = 0
    l = 0           # l for left
    r = 0           # r for right
    max_sum = 0
    for p1 in xrange(len(a)):
        sub_sum = 0
        for p2 in xrange(p1, len(a)):
            sub_sum += a[p2]
            if sub_sum > max_sum:
                max_sum  = sub_sum
                l = p1
                r = p2
    return l, r, max_sum

def find_maximum_subarray_dc(a):        #dc for divide and conquer

    # subfunction
    # given an arrary and three indices which can split the array into a[l:m]
    # and a[m+1:r], find out a subarray a[i:j] where l \leq i \less m \less j \leq r".
    # according to the definition above, the target subarray must
    # be combined by two subarray, a[i:m] and a[m+1:j]
    # Growing Rate: theta(n)

    def find_crossing_max(a, l, r, m):

        # left side
        # ls_r and ls_l indicate the right and left bound of the left subarray.
        # l_max_sum indicates the max sum of the left subarray
        # sub_sum indicates the sum of the current computing subarray
        ls_l = m+1
        ls_r = m
        l_max_sum = None
        sub_sum = 0
        for j in xrange(m,l-1,-1):      # adding elements from right to left
            sub_sum += a[j]
            if sub_sum > l_max_sum:
                l_max_sum = sub_sum
                ls_l = j

        # right side
        # rs_r and rs_l indicate the right and left bound of the left subarray.
        # r_max_sum indicates the max sum of the left subarray
        # sub_sum indicates the sum of the current computing subarray
        rs_l = m+1
        rs_r = m
        r_max_sum = 0
        sub_sum = 0
        for j in range(m+1,r+1):
            sub_sum += a[j]
            if sub_sum > r_max_sum:
                r_max_sum = sub_sum
                rs_r = j

        #combine
        return (ls_l, rs_r, l_max_sum+r_max_sum)

    # subfunction
    # Growing Rate:  theta(nlgn)
    def recursion(a,l,r):           # T(n)
        if r == l:
            return (l,r,a[l])
        else:
            m = (l+r)//2                    # theta(1)
            left = recursion(a,l,m)         # T(n/2)
            right = recursion(a,m+1,r)      # T(n/2)
            crossing = find_crossing_max(a,l,r,m)   # theta(r-l+1)

            if left[2]>=right[2] and left[2]>=crossing[2]:
                return left
            elif right[2]>=left[2] and right[2]>=crossing[2]:
                return right
            else:
                return crossing

    #back to master function
    l = 0
    r = len(a)-1
    return recursion(a,l,r)

if __name__ == "__main__":

    from time import time
    from sys import argv
    from random import randint
    alen = 100
    if len(argv) > 1:
        alen = int(argv[1])
    a = [randint(-100,100) for i in xrange(alen)]

    time0 = time()
    print find_maximum_subarray_bf(a)
    time1 = time()
    print find_maximum_subarray_dc(a)
    time2 = time()
    print "function 1:", time1-time0
    print "function 2:", time2-time1
    print "ratio:", (time1-time0)/(time2-time1)

rawDescription: Theta(n**2) and Theta(n*lgn) algorithm perform unproperly


code:
for section in soup.findAll('h2'):
    nextNode = section
    while True:
        nextNode = nextNode.nextSibling
        try:
            tag_name = nextNode.name
        except AttributeError:
            tag_name = ""
        if tag_name == "p":
            print nextNode.string
        else:
            print "*****"
            break

rawDescription: Find next siblings until a certain one using beautifulsoup


code:
import sys
if sys.maxunicode == 0x10FFFF:
    print 'Python built with UCS4 (wide unicode) support'
else:
    print 'Python built with UCS2 (narrow unicode) support'

rawDescription: Does python support unicode beyond basic multilingual plane?


code:
compile('sum([1, 2, 3])', '', 'single')
exec compile('sum([1, 2, 3])', '', 'single')
compile('print "Hello world"', '', 'exec')
exec compile('print "Hello world"', '', 'exec')

rawDescription: What is a Python code object?

description: What is a Python code object


code:
root = ET.fromstring(xmldata)

stages = root.findall("./ep_150/stage[@department='animation']")

print 'Stages in animation department....\n'

for stage in stages:
    print stage.attrib['name']

stages = root.findall("./ep_150/stage")

print '\n\nreviews for id=p4645\n'

for stage in stages:
    for rev in stage.findall("review[@id='p4645']"):
        print stage.attrib['name'], rev.attrib['name']

rawDescription: How to get parent tag while using XPaths in xml.etree.elementree with python 2.6.4

description: Get parent tag while using XPaths in xml.etree.elementree with python 2.6.4


code: print linedefn.parseString(data).dump()

rawDescription: pyparsing whitespace match issues

description: Pyparsing whitespace match issues


code:
x = ["Foo"]  # Strings are immutable
y = x
x[0] = "Bar"
print y               # ['Bar']
print id(x) == id(y)  # True

rawDescription: Data-Binding in Python?

description: Data-Binding in Python


code:
for row in config_params:
    print row['hostname']

rawDescription: Get value from dict

description: Get value from dict


code:
excel = [u'\u4e00', u'\u4e8c', u'\u4e09']
cmd = u'create vertex v set s = [{}]'.format(u','.join(excel))
cmd
print cmd

rawDescription: escape a string which contains non-ascii

description: Escape a string which contains non-ascii


code:
x, y = function()
print x, y # in Python 3 use print(x, y)

rawDescription: Print to stdout with space's between result?


code:
for div in soup.findAll('div','zitat'):
    for span in div.findAll('span', 'quote_zeile'):
        print span.string

rawDescription: python how to parse html

description: Python how to parse html


code:
for o in range(128):
    print chr(o), hex(o)

rawDescription: Generate a list of hex bytes in Python

description: Generate a list of hex bytes in Python


code:
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.leasingcar.dk/privatleasing/Citro%C3%ABn-Berlingo/eHDi-90-Seduction-E6G')

# wait for visible price to have "Kr." text
wait = WebDriverWait(driver, 10)
price = wait.until(wait_for_visible_element_text_to_contain((By.CSS_SELECTOR, "span.total-price"), "Kr."))
print price.text

rawDescription: Why does selenium return an empty text field?


rawDescription: Extract specific elements from numpy array by column


code:
from collections import defaultdict
import csv
from collections import defaultdict
sample = '''\
Epitope,ID,Frequency,Assay
AVNIVGYSNAQGVDY,123431,27.0,Tetramer
DIKYTWNVPKI,887473,50.0,3H
LRQMRTVTPIRMQGG,34234,11.9,Elispot
AVNIVGYSNAQGVDY,3456,67.0,Tetramer
'''
reader = csv.DictReader(sample.splitlines())
result = defaultdict(lambda: defaultdict(list))
for row in reader:
    epitope = row.pop('Epitope')
    entry = result[epitope]
    for key, value in row.items():
        entry[key].append(value)

from pprint import pprint
for key, value in result.items():
    print key, dict(value)

rawDescription: Nested dictionary from csv python

description: Nested dictionary from csv python


code:
path = "/home/user/puppet/modules/impuls-test/templates"
components = path.split(os.sep)
print str.join(os.sep, components[:components.index("modules")+2])

rawDescription: Getting a specific parent folder with Python


code:
Script
import numpy as np

def main():
    # Generate some data...
    t = np.linspace(0, 10*np.pi, 30)
    x = np.sin(t)
    condition = np.where(x>0,1,0)

    onarray,offarray = on_off_times(condition)

    print "Condition: ",condition
    print "Ontimes:   ",onarray
    print "Offtimes:  ",offarray

def on_off_times(condition):

    changing=np.diff(condition)         #complete array, -1 when tunring off, +1 when turning on
    idx, = changing.nonzero()           #Indices of changepoints
    times=np.diff(idx)              #'Times' between changes
    times=np.r_[0,times]            # The first time can't be calculated ->is set to 0

    ontimes=np.where(changing[idx]<0,times,False)   #When turning off: Was Ontime (times-array with "False" instead of offtimes)
    offtimes=np.where(changing[idx]>0,times,False)  #When turning on:  Was Offtime

    onarray=np.r_[changing.copy(),0]            #copy the array with all the values and add 1(to have an "empty" array of the right size)
    offarray=np.r_[changing.copy(),0]

    np.put(onarray,idx,ontimes)         #Put the times into it (at the changepoints)
    np.put(offarray,idx,offtimes)

    return onarray,offarray

main()

rawDescription: numpy(.ma) array: Number of values since last value change?

description: Numpy(.ma) array: Number of values since last value change


code:
with open("banklist.csv", "rU") as infile:
    next(infile, None)  # skip the first line
    for line in infile:
        print line

rawDescription: Python - CSV read as one big line

description: Python - CSV read as one big line


code:
def nones(a, b, c, d):
    arguments = locals()
    print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None)

nones("Something", None, 'N', False)

rawDescription: How to iterate over function arguments

description: Iterate over function arguments


code:
for el in elems:
    try:
        print el.xpath("preceding::c[@attr1]")[-1].get("attr1")
    except IndexError:
        print "No preceding 'c' element."

rawDescription: lxml etree find closest element before

description: Lxml etree find closest element before


code:
# x and a are passed the same string because we want x == a to be True
x = Foo("a")
a, b = Foo("a"), Foo("b")
if x in (a, b):
  print "Hello World!"

rawDescription: Would it be better to use "if x in (y, z)" over "if x == y or x == z"?


code:
counter = {}
for word in words:
    counter[word] = counter.get(word, 0) + 1
print [key for key, count in counter.items() if count == 3]

rawDescription: Printing items in a list that occur a certain number of times?


code:
import calendar

def getLaborDay(year):
    month = 9
    mycal = calendar.Calendar(0)
    cal = mycal.monthdatescalendar(year, month)
    if cal[0][0].month == month:
        return cal[0][0]
    else:
        return cal[1][0]

print getLaborDay(2003)
print getLaborDay(2004)

rawDescription: Using Calendar.monthdatescalendar() & Labor Day


code:
class A(object):
    var = 0 #place holder

    def printTheVar(self):
        print self.var

class B(object):
    def __init__(self,cls):
        global A
        A = cls.A

    def buildAndCallA(self):
        a = A()
        a.printTheVar()

rawDescription: Access subclass variables from parent file


code:
import money

country_name = 'France'

for currency, data in money.CURRENCY.iteritems():
    if country_name.upper() in data.countries:
        print currency
        break

rawDescription: django countries currency code

description: Django countries currency code


code:
qp = xapian.QueryParser()
qp.set_stemmer(xapian.Stem("en"))
qp.set_stemming_strategy(qp.STEM_SOME)
query = qp.parse_query('question')
query = qp.parse_query('question and answer')
enquire = xapian.Enquire(db)
enquire.set_query(query)
for match in enquire.get_mset(0, 10):
    print match.document.get_data()

rawDescription: How to use xapian which returns a URL when indexing a web page

description: Use xapian which returns a URL when indexing a web page


code:
links = pq('#maincontent .linkoutlist a', response.content, parser="html")
for link in links:
    print link.attrib.get("title", "No title")

rawDescription: Using lxml to parse namepaced HTML?

description: Using lxml to parse namepaced HTML


code:
import numpy as np
import pandas

df = pandas.DataFrame({"a": np.random.random(100),
                       "b": np.random.random(100) + 10})

# Bin the data frame by "a" with 10 bins...
bins = np.linspace(df.a.min(), df.a.max(), 10)
groups = df.groupby(pandas.cut(df.a, bins))

# Get the mean of b, binned by the values in a
print groups.mean().b

rawDescription: binning a dataframe in pandas in Python

description: Binning a dataframe in pandas in Python


code:
for div in soup.find_all('div'):
    print len(filter(None , div.get('style').split(';')))

rawDescription: Python - How to get total no of style attributes of a specific div


rawDescription: Python 2.7, populating tables with arrays


code:
from subprocess import Popen, PIPE
from getpass import getpass

x = Popen('ssh root@host', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)

print x.stdout.readline()
_pass = getpass('Enter your superduper password:')
x.stdin.write(_pass)
print x.stdout.readline()

rawDescription: Python Fabric and password prompts

description: Python Fabric and password prompts


code:
f = open("bonnie.txt", "wb")
f.write("My Bonnie lies over the ocean.")
f.close()
f.open("bonnie.txt", "r+b")
mm = mmap(f.fileno(), 0)
print mm[3:9]

rawDescription: Python Random Access File

description: Python Random Access File


code:
from bs4 import BeautifulSoup as BS
for d in data:
    soup = BS(d)
    soupPTag = soup.p
    if soupPTag:
        soupList = [unicode(child) for child in soupPTag.children if child!=" "]
        print soupList
    else:
        soupBodyTag = soup.body
        soupList = [unicode(child) for child in soupBodyTag.children if child!=" "]
        print soupList

rawDescription: Python, extract tags and also get position of word


code:
from pyPdf import PdfFileReader
def _setup_page_id_to_num(pdf, pages=None, _result=None, _num_pages=None):
    if _result is None:
        _result = {}
    if pages is None:
        _num_pages = []
        pages = pdf.trailer["/Root"].getObject()["/Pages"].getObject()
    t = pages["/Type"]
    if t == "/Pages":
        for page in pages["/Kids"]:
            _result[page.idnum] = len(_num_pages)
            _setup_page_id_to_num(pdf, page.getObject(), _result, _num_pages)
    elif t == "/Page":
        _num_pages.append(1)
    return _result
# main
f = open('document.pdf','rb')
p = PdfFileReader(f)
# map page ids to page numbers
pg_id_num_map = _setup_page_id_to_num(p)
o = p.getOutlines()
pg_num = pg_id_num_map[o[0].page.idnum] + 1
print pg_num

rawDescription: How to get bookmark's page number

description: Get bookmark's page number


code:
tgt_list='ca bke clss'.split()
for word in ['car','bike','van','class']:
    wdist_exp=((w, levenshtein(w, word)) for w in tgt_list)
    closest, dist=min(wdist_exp, key=lambda t: t[1])
    print '{}=>{}   ld={}'.format(closest,word,dist)

rawDescription: python related word search and replace with list words

description: Python related word search and replace with list words


code:
class M(dict):

    def __getitem__(self, key):
        try:
            temp = int(key)
            return "I am a number"
        except ValueError:
            return self.get(key, None)

item = M({'one':'1', 'two':'2', '3':'three'})

print item['one']
print item[3]
print item[0]

rawDescription: python get by index for a dictionary

description: Python get by index for a dictionary


code:
class RecursiveRetrievalHelper(object):

    __items = None

    def __init__(self, first_item):
        self.__items = [first_item]

    def __getattr__(self, item):
        self.__items.append(item)
        return self

    # One possible way to break the iteration
    def __call__(self, *args, **kwargs):
        return self.__items

    # Another possible way to break the iteration
    def __iter__(self):
        return iter(self.__items)

    # This is mostly for debugging and console
    def __repr__(self):
        return repr(self.__items)

class MainClass(object):
    def __getattr__(self, item):
        return RecursiveRetrievalHelper(item)

if __name__ == '__main__':
    this_api = MainClass()
    print this_api.has.some.weird.complicated.path()     # Uses __call__()
    print list(this_api.has.some.weird.complicated.path) # Uses __iter__()
    for url_part in this_api.has.some.weird.complicated.path: # Uses __iter__() again
        print url_part,
    print

rawDescription: function that gets field as parameters

description: Function that gets field as parameters


code:
try:
    from file import varName
except ImportError:
    print 'var not found'

rawDescription: how to determine if a variable exists in another python file

description: Determine if a variable exists in another python file


code:
from ctypes import *
import sys
sys.path.insert(0,'..')

import pymunk

sendbody_lib = windll.LoadLibrary("sendbody.dll")

cpBody = pymunk._chipmunk.cpBody

mass_sum = sendbody_lib.mass_sum
mass_sum.restype = c_double
mass_sum.argtypes = [c_int, POINTER(POINTER(cpBody))]

b1 = pymunk.Body(1, 1)
b2 = pymunk.Body(10, 1)
bodies = [b1._body, b2._body, b1._body]
arr = (POINTER(cpBody) * len(bodies))(*bodies)

print mass_sum(len(arr), arr)

rawDescription: Cast an array of pointers to other objects?


code:
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)

counts = []
for bigram, count in sorted_bigrams:
    if bigram == ("interesting", "news"):
        print count
        counts.append(count)
print counts

rawDescription: how can i store the printing result, obtained by "for statement" variable?

description: Store the printing result, obtained by "for statement" variable


code:
def chunk_reading(filepath,y,z,x=0):
    # x : number of lines to skip before the periodical treatment
    # y : number of lines to periodically skip
    # z : number of lines to periodically print
    with open('poem.txt') as f:
        try:
            for sk in xrange(x):
                f.next()
            while True:
                try:
                    for i in xrange(y):
                        print 'i==',i
                        f.next()
                    for j in xrange(z):
                        print 'j==',j
                        print repr(f.next())
                except StopIteration:
                    break
        except StopIteration:
            print 'Not enough lines before the lines to print'

chunk_reading('poem.txt',7,3)

rawDescription: Using python to process a chunk of a file every x lines


code:
def userInput(ItemA, ItemB, *args):
    lst=[]
    lst.append(ItemA)
    lst.append(ItemB)
    for arg in args:
        lst.append(arg)

    print ' '.join(lst)

userInput('this','that','more1','more2','more3')

rawDescription: Iterate over *args?

description: Iterate over *args


code:
#simple case
data1= """
author='helloWorld'

def hello()
    print "hello world"
    """
# case with two ::
data2= """
__author__::'someone'

def hello()
    print "hello world"
    """
#case where we have numerical/alphabetic
data3= """
__author__='someone201119'

def hello()
    print "hello world"
    """
#Case where no author in code
data4= """
def hello()
    print "hello world"
    """

for data in [data1,data2,data3,data4]:
    m= re.match(r'.*author*.[^:=]*[:=]*(.[^\n]+)',data,re.DOTALL)
    if m:
        author= m.group(1)
    else:
        author='unkown'
    print "author is this case is:", author

rawDescription: Find author name in multiple files and folders in python


code:
def sliding_tristep(full_trace, future_step = 2, window_size = 3):
    for user_trace in full_trace:
        for current_input in window(user_trace):
            counter = 0
            trace = current_input[:] # make a copy of current_input
            accumulator = []
            while counter <= future_step:
                next_prediction = predict(trace)
                trace.append(next_prediction)
                accumulator.append(next_prediction)
                trace = trace[-window_size:]
                counter += 1
            print current_input, accumulator

rawDescription: Why does Python modify the list which is out of the loop?


code:
class _HandlerHelper:
   def fna(self):
       print 'a'

   def fnb(self):
       print 'b'

   # __call__ is a magic method which lets you treat the object as a function
   def __call__(self, fn):
       return getattr(self, 'fn' + fn)

get_handler_by_type = _HandlerHelper()

rawDescription: How to encapsulate handlers in an efficient manner in Python?

description: Encapsulate handlers in an efficient manner in Python


code:
frompos, topos = 0, len(str)
for i in range(1,100):  #never say forever with bisection...
    trypos = (frompos+topos+1)/2
    print "try:",frompos,trypos,topos
    if alphabet[trypos] != str[trypos]:
        topos = trypos
    else:
        frompos = trypos
    if topos-frompos==1:
        if alphabet[topos] != str[topos]:
            print alphabet[frompos]
        else:
            print alphabet[topos]
        break

rawDescription: python: finding a missing letter in the alphabet from a list - least lines of code

description: Python: finding a missing letter in the alphabet from a list - least lines of code


code:
from os.path import splitext

list1 = ['image1.png', 'image2.png', 'image3.png', 'image3.png', 'image4.png', 'image3.jpg']
list2 = ['image1.pdf', 'image2.eps', 'image3.ps', 'image5.doc']

# Create a lookup set of the document names sans extensions.
documents = set([splitext(filename)[0] for filename in list2])

# Compare each stripped filename in list1 to the list of stripped document filenames.
matches = [filename for filename in set(list1) if splitext(filename)[0] in documents]

print matches

rawDescription: compare two lists of files, ignoring file extension in one list

description: Compare two lists of files, ignoring file extension in one list


code:
for key in unique_key_dict:
  for date in unique_key_dict[key]:
    avg = sum(float(x) for x in unique_key_dict[key][date]) / len(unique_key_dict[key][date])
    print key, date, avg

rawDescription: How to change dictionary from one format into another?

description: Change dictionary from one format into another


code:
from nltk.tree import ParentedTree
ptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) \
        (VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))')

leaf_values = ptree.leaves()

if 'nice' in leaf_values:
    leaf_index = leaf_values.index('nice')
    tree_location = ptree.leaf_treeposition(leaf_index)
    print tree_location
    print ptree[tree_location]

rawDescription: NLTK tree data structure, finding a node, it's parent or children


code:
list_1=['taska1', 'taska2', 'taska3', 'taskb2', 'taska7']
print [l for l in list_1 if not l.startswith('taska')]

rawDescription: How to identify an odd item in a list of items using python

description: Identify an odd item in a list of items using python


code:
import random
with open('filename.txt', 'r') as fin:
    lines = list(fin)

random.shuffle(lines)
for line in lines:
    print line,  # the trailing comma suppresses the newline since the line already has that.

rawDescription: In Python how can I print the rows in my text file in a random order?


code:
unique_list = []
for el in int_list:
    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

rawDescription: Removing repeated characters from a list in python


code:
print u'\xe8'
print u'\x81'

rawDescription: Transform unicode string in python

description: Transform unicode string in python


code:
# addition.py

import original
original.original_list.append(4)

print original.original_list
#  [1, 2, 3, 4]

rawDescription: Extending a list in one module from another -- without any lines in the old module?


code:
class Bar(object):
    def x(self):
        return 0

bar = Bar()

setattr(bar.__class__, 'x', property(bar.__class__.x))

print Bar.x
# <property object at 0x04D306F0>
print bar.x
# 0

rawDescription: How do I assign a property to an instance in Python?

description: Assign a property to an instance in Python


code:
from timeit import Timer
timer = Timer('main()', 'from yourmodule import main')
print timer.timeit()

rawDescription: How to time how long a Python program takes to run?

description: Time how long a Python program takes to run


code:
from itertools import izip_longest
import xlrd

rb1 = xlrd.open_workbook('file1.xlsx')
rb2 = xlrd.open_workbook('file2.xlsx')

sheet1 = rb1.sheet_by_index(0)
sheet2 = rb2.sheet_by_index(0)

for rownum in range(max(sheet1.nrows, sheet2.nrows)):
    if rownum < sheet1.nrows:
        row_rb1 = sheet1.row_values(rownum)
        row_rb2 = sheet2.row_values(rownum)

        for colnum, (c1, c2) in enumerate(izip_longest(row_rb1, row_rb2)):
            if c1 != c2:
                print "Row {} Col {} - {} != {}".format(rownum+1, colnum+1, c1, c2)
    else:
        print "Row {} missing".format(rownum+1)

rawDescription: Compare 2 excel files using Python

description: Compare 2 excel files using Python


code:
from sqlalchemy import inspect
print inspect(A.bs).mapper.class_

rawDescription: Python+SQLAlchemy: Getting mapper class from InstrumentedList?


code:
import numpy
all_data = numpy.array([float(row[1]) for row in csvin])
print "differences: ", all_data[1:] - all_data[: -1]

rawDescription: How to operate with values in the same column in .csv files

description: Operate with values in the same column in .csv files


code:
s1="""List = ['android', 'ios', 'android', '', 'none', 'android']
OS_list = ['android', 'ios', 'windows']

[i for i in OS_list if i in List]"""

s2="""List = ['android', 'ios', 'android', '', 'none', 'android']
OS_list = ['android', 'ios', 'windows']
set(List).intersection(OS_list)"""

print timeit.timeit(stmt=s1,number=1000)
print timeit.timeit(stmt=s2,number=1000)

rawDescription: Python List: Pythonic way to get unique items in given List from a given Set


code:
import random
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
def gen():
    return ''.join([random.choice(chars) for x in range(32)])

test = [gen() for i in range(100000)]
print len(test), len(set(test)) # 100000 100000

rawDescription: random.choice not random

description: Random.choice not random


code:
import pygame
from pygame.locals import *

pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Gaben's Future Adventure")

player = pygame.image.load("images/player.png")
player_rect = player.get_rect()

white = (255, 255, 255)
black = (0, 0, 0)

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

move_map = {pygame.K_w: ( 0, -1),
            pygame.K_s: ( 0,  1),
            pygame.K_a: (-1,  0),
            pygame.K_d: ( 1,  0)}

def main():
    running = True

    while running:
        screen.fill(white)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                print "Exiting game."

        pressed = pygame.key.get_pressed()
        move = [move_map[key] for key in move_map if pressed[key]]
        final = map(sum, zip(*move))
        if final:
            player_rect.move_ip(*final)

        screen.blit(player, player_rect)
        pygame.display.flip()
        print player_rect.x
        print player_rect.y
main()

rawDescription: python pygame input controls

description: Python pygame input controls


code:
def lv1(d):
  locals().update(d)
  print zap

rawDescription: How can I pass my locals and access the variables directly from another function?

description: Pass my locals and access the variables directly from another function


rawDescription: Pandas Python: Merging every two rows in one dataframe


code:
cur = conn.cursor()
cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")
cur.execute("SELECT @@session.tx_isolation")
print cur.fetchall()[0]
cur.execute("SELECT * FROM bar")
print cur.fetchall()
cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ")
cur.execute("SELECT @@session.tx_isolation")
print cur.fetchall()[0]

# output
('READ-UNCOMMITTED',)
(('foo',), ('bar',))
('REPEATABLE-READ',)

rawDescription: How do you change the SQL isolation level from Python using MySQLdb?

description: Change the SQL isolation level from Python using MySQLdb


rawDescription: Pretty printing a list in a tabular format


code:
from lxml import etree as ET

def pp(e):
    print ET.tostring(e, pretty_print=True)
    print

root = ET.XML("""\
<project id="8dce5d94-4273-47ef-8d1b-0c7882f91caa" kpf_version="4">
<livefolder id="8744bc67-1b9e-443d-ba9f-96e1d0007ba8" idref="707cd68a-33b5-4051-9e40-8ba686c2fdb8">Mooo</livefolder>
<livefolder id="8744bc67-1b9e-443d-ba9f" idref="707cd68a-33b5-4051-9e40-8ba686c2fdb8" />
<preference-set idref="8dce5d94-4273-47ef-8d1b-0c7882f91caa">
  <boolean id="import_live">0</boolean>
</preference-set>
</project>
""")
pp(root)

xslt = ET.XML("""\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="*">
    <xsl:copy>
      <xsl:apply-templates select="*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
""")
tr = ET.XSLT(xslt)

doc2 = tr(root)
root2 = doc2.getroot()
pp(root2)

rawDescription: lxml (or lxml.html): print tree structure

description: Lxml (or lxml.html): print tree structure


code:
"Convert DICOM files to PNG format, remove blank areas."

import os
import sys # voor argv.
import subprocess
from multiprocessing import Pool, Lock

def checkfor(args):
    try:
        subprocess.check_output(args, stderr=subprocess.STDOUT)
    except CalledProcessError:
        print "Required program '{}' not found! exiting.".format(progname)
        sys.exit(1)

def processfile(fname):
    size = '1574x2048'
    args = ['convert', fname, '-units', 'PixelsPerInch', '-density', '300',
            '-crop', size+'+232+0', '-page', size+'+0+0', fname+'.png']
    rv = subprocess.call(args)
    globallock.acquire()
    if rv != 0:
        print "Error '{}' when processing file '{}'.".format(rv, fname)
    else:
        print "File '{}' processed.".format(fname)
    globallock.release()

## This is the main program ##
if __name__ == '__main__':
    if len(sys.argv) == 1:
        path, binary = os.path.split(sys.argv[0])
        print "Usage: {} [file ...]".format(binary)
        sys.exit(0)
    checkfor('convert')
    globallock = Lock()
    p = Pool()
    p.map(processfile, sys.argv[1:])
    p.close()

rawDescription: How do I Convert Python Dict to JSON in a Multi-Threaded Fashion


code:
import csv

with open("file.csv", "rb") as ins:
    for row in csv.reader(ins):
        print sum(map(int, row))

rawDescription: Import csv into python and sum the row of numbers


code:
print 'List Local Files'

VALUES_SEPARATOR = ","

with open('./local.csv','r') as localFile :
    lines = []
    for line in localFile:
        #use line[:-1] to remove the end line "\n" symbol.
        splitLine = line[:-1].split(VALUES_SEPARATOR)
        splitAgain = splitLine[2].replace('"', '')

        lines.append(splitAgain)#store the line in a out-of-the-loop variable.

    print(lines)

rawDescription: Cant print list out of python function

description: Cant print list out of python function


code:
import cv2

def show_image_and_wait_for_key( image, name="Image" ):
    print "showing",name,"(waiting for input)"
    cv2.imshow('norm',image)
    cv2.waitKey(0)

def draw_segments( image , segments, color=(255,0,0), line_width=1):
        '''draws segments on image'''
        for segment in segments:
            x,y,w,h= segment
            cv2.rectangle(image,(x,y),(x+w,y+h),color,line_width)

original= cv2.imread("ravens.jpg")
image=original
image= cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image= cv2.GaussianBlur(image,(3,3),0)
_, image= cv2.threshold( image, 140, 255, cv2.THRESH_BINARY )
contours,hierarchy = cv2.findContours(image.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
segments= [cv2.boundingRect(c) for c in contours]
draw_segments( original, segments )
show_image_and_wait_for_key( original )

rawDescription: Python Image Matching. Find mxm image from nxn image


rawDescription: How would I sort a hierarchical list into a tree/pyrimid model of dicts?


code:
for i in itertools.product(*l):
    print i

rawDescription: Obtaining the combination of elements in a dictionary


code:
import sys, re, optparse

first_re = re.compile(r'^\d{3}$')

parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()

if len(args) == 1:
    if first_re.match(args[0]):
        print "Primary argument is : ", args[0]
    else:
        raise ValueError("First argument should be ...")
elif len(args) > 1:
    raise ValueError("Too many command line arguments")

if options.debug:
    print 'debug flag'

if options.xls:
    print 'xls flag'

rawDescription: How can I process command line arguments in Python?

description: Process command line arguments in Python


code:
s = 'ABBBABBAAAAAABAAABAAAAAABAAABAABAAAAABAAAAABAABBBBBBBAAAAAAABABABAAA'
for i in range(len(s)):
  res = re.match(r'^(.)\1*', s[i:]).group(0)
  print i, res, len(res)

rawDescription: finding lenth of consecutive characters given an index

description: Finding lenth of consecutive characters given an index


code:
squaredDistances = np.sum((np.array(pheromones_positions.keys()) - (20, 20, 55))**2, axis=1)
idx = np.where(squaredDistances < 10**2)[0]
print pheromones_positions.values()[idx]

rawDescription: Organize 3d points and found them by distance from a position


code:
import pickle
infile = open('/tmp/pickle', 'rb')
buf = []
while True:
    line = infile.readline()
    if not line:
        break
    buf.append(line)
    if line.endswith('.\n'):
        print 'Decoding', buf
        print pickle.loads(''.join(buf))
        buf = []

rawDescription: Reading multiple Python pickled data at once, buffering and newlines?


code:
import re

remove_non_digits = re.compile(r'[^\d.]+')

inputList = ["a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'", '']

#remove empty strings
flag = True
while flag:
    try:
        inputList.remove('')
    except ValueError:
        flag=False

outputList = []

for varString in inputList:
    varStringList = varString.split()
    varDict = {}
    for aVar in varStringList:
        varList = aVar.split('=')
        varDict[varList[0]] = varList[1]
    outputList.append(varDict)

for aDict in outputList:
    for aKey in aDict:
        aDict[aKey] = float(remove_non_digits.sub('', aDict[aKey]))

print outputList

rawDescription: assign output of print to a variable in python

description: Assign output of print to a variable in python


code:
for element in elements.keys():
    print element
# output:
oxygen
hydrogen

rawDescription: Generating raw_inputs based on user input? [Python]


code: print args

rawDescription: python subprocess issue with Nmap

description: Python subprocess issue with Nmap


code:
import time

def userNoInput(msg):
    """ Get Number into from the user. """
    while 1:
        try:
            return int(raw_input(msg))
        except ValueError:
            print "Enter Only Number string."
            continue

def guessGame():
    """
        1. Get Lower and Upeer Value number from the User.
        2. time sleep to guess number for user in between range.
        3. While infinite loop.
        4. Get guess number from the Computer.
        5. User can check guess number and tell computer that guess number if correct ror not.
        6. If Correct then print msg and break While loop.
        7. If not Correct then
            Ask Computer will User that guess number is Greate or Lower then Actual number.
            7.1. If Greater then Set Max limit as guess number.
            7.2. If Not Greater then Set Min limit as guess number.
            7.3. Continue While loop
    """
    min_no = userNoInput("Please input the low number range:")
    max_no = userNoInput("Please input the high number range:")
    print "Guess any number between %d and %d."%(min_no, max_no)
    time.sleep(2)

    while True:
        mid = (min_no+max_no)/2
        print'Is you Secret Number'+str(mid)+'?'
        print"Enter 'h' to indicate the guess is too high.",
        print"Enter'l' to indicate the guess is too low",
        print"Enter'c'to indicate I guessed correctly"
        x=raw_input().lower()
        if(x=='c'):
            print'Game Over','Your Secret Number was'+str(mid)
            break
        elif(x=='h'):
            #- As guess number is higher then set max number to guess number.
            max_no=mid - 1
        elif(x=='l'):
            #- As guess number is lower then set min number to guess number.
            min_no = mid + 1
        else:
            print("Sorry, I did not understand your input.")

guessGame()

rawDescription: Basic Python code not Working

description: Basic Python code not Working


code:
from datetime import datetime
from elasticsearch import Elasticsearch

INDEX_NAME = "test_index"

ESCONN = Elasticsearch()

if ESCONN.indices.exists(INDEX_NAME):
    ESCONN.indices.delete(index = INDEX_NAME, ignore=[400, 404])

ESCONN.indices.create(index=INDEX_NAME, ignore=400)

obj_mapping = {
    'properties': {
        'timestamp': { 'type': 'date' },
    }
}

ESCONN.indices.put_mapping("doc", obj_mapping, [INDEX_NAME])

for i in range(0, 5):
    ESCONN.index(index=INDEX_NAME, doc_type="doc", body={
        'timestamp': datetime.utcnow(),
    })

    print "Stored %d" % i

rawDescription: Elasticsearch date range returns no hits


code:
class Dog(Animal, Weapon):
    def __init(self, numlegs):
        Animal.__init__(numlegs)
        self.weapon = Weapon()

    def bark(self):
        print "Arf!"

rawDescription: How to add same methods/properties to a set of subclasses derived from common class

description: Add same methods/properties to a set of subclasses derived from common class


code:
import collections
import itertools

genes_info = collections.defaultdict(list)

with open("testfile") as genes_file:
    for line in genes_file:
        fields = line.split()
        genes_info[fields[0]].append(fields[1:])  # Stores each row information

# Conversion of the row-first gene information into column-first information:
for gene_info in genes_info.itervalues():
    gene_info[:] = itertools.chain(*zip(*gene_info))

print genes_info

rawDescription: Python join elements with same index

description: Python join elements with same index


code:
# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1
print cnt

# Find the ten most common words in Hamlet
import re
words = re.findall('\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)

rawDescription: Python - Finding word frequencies of list of words in text file


code:
from threading import Thread, Lock
from Queue import Queue

class Logger:
     def __init__(self):
         self.iolock = Lock()

     def debug(self, str, *msg):
         with self.iolock:
             print str % msg

     error = debug

logger = Logger()

class TaskExecutor(object):
    def __init__(self):
        logger.debug("init taskExecutor")
        self.taskInfos = Queue()
        task_thread = Thread(target=self._run_worker_thread)
        task_thread.daemon = True
        task_thread.start()

    def is_running(self):
        return True

    def _run_worker_thread(self):
        logger.debug("start running taskExcecutor worker Thread")
        while self.is_running():
            try:
                logger.debug("try to get queued task from queue %s", self.taskInfos)
                msg, task = self.taskInfos.get()
                logger.debug("got task %s for msg: %s", str(task), str(msg))
                #task.execute(msg)
                self.taskInfos.task_done()
            except Exception, e:
                logger.error("Error: %s", e.message)
        logger.debug("shutting down TaskExecutor!")

    def schedule_task(self, msg, task):
        try:
            logger.debug("appending task '%s' for msg: %s", str(task), str(msg))
            self.taskInfos.put((msg, task))
            logger.debug("into queue: %s ", str(self.taskInfos))
        except Exception, e:
            logger.debug("queue is probably full: %s", str(e))

te = TaskExecutor()

def runit():
    for i in range(10):
        te.schedule_task("some task", i)

main = Thread(target=runit)
main.start()

rawDescription: deadlock because of blocking Queue.get() method

description: Deadlock because of blocking Queue.get() method


code:
test = TEST()
print test.x()

rawDescription: Understanding Python classes

description: Understanding Python classes


code:
def nfruits(dictionary, string):
    i = 0
    string = sorted(string)

    for idx, char in enumerate(string):
        # We should update other fruits on all steps except the
        # last one
        if idx < len(string) - 1:
            for key in dictionary:
                dictionary[key] += 1
            dictionary[char] -= 2
        else:
            # for the last step - only decrement the fruit
            # Python ate
            dictionary[char] -= 1
        print dictionary
    return dictionary[max(dictionary, key = dictionary.get)]

if __name__ == "__main__":
    dd = {'A': 1, 'B': 2, 'C': 3}
    print nfruits(dd, 'AC')

rawDescription: Change values in dictionary except for one key


code:
with open('cr_fixes.xml') as file: # get some data to process
    xmlfile = file.read()

def CRlistToTable(CRlist):
    cols = CRlist[0] # first item is header-row of col names on the first line

    CRstrings = ['
']
    # table header row
    CRstrings.append('
')
    for col in cols:
        CRstrings.append('    {}	'.format(col))
    CRstrings.append('
')

    # create a template for each table row
    TR_TEMPLATE = ['
']
    # 1st col of each row is CR and handled separately since it corresponds to a link
    TR_TEMPLATE.append(
        '    {{{}}}	'.format(*[cols[0]]*2))
    for col in cols[1:]:
        TR_TEMPLATE.append('    {{}}	'.format(col))
    TR_TEMPLATE.append('
')
    TR_TEMPLATE = '\n'.join(TR_TEMPLATE)

    # then apply the template to all the non-header rows of CRlist
    for items in CRlist[1:]:
        CRstrings.append(TR_TEMPLATE.format(CR=items[0], *items[1:]))
    CRstrings.append("
")

    return '\n'.join(CRstrings) + '\n'

FIXES_START_TAG, FIXES_END_TAG = '<Fixes>, </Fixes>'.replace(',', ' ').split()
CRsFixesStart = xmlfile.find(FIXES_START_TAG) + len(FIXES_START_TAG)
CRsFixesEnd = xmlfile.find(FIXES_END_TAG)
info = xmlfile[CRsFixesStart:CRsFixesEnd].strip().splitlines()

# first line of extracted info is a blank-separated list of column names
num_cols = len(info[0].split())

# split non-blank lines of info into list of columnar data
# assuming last col is the variable-length title, comprising reminder of line
CRlist = [line.split(None, num_cols-1) for line in info if line]

# convert list into html table
crInfo = CRlistToTable(CRlist)
print crInfo

rawDescription: How to create a dynamic table

description: Create a dynamic table


code:
import time, csv

def links():
    first = open('closed.csv')
    csv_file = csv.reader(first, delimiter="|")

    second = open('links.csv')
    csv_file2 = csv.reader(second, delimiter="|")

    list=[]
    for row in csv_file2:
        list.append(row)

    for row in csv_file:
        match=False
        for secrow in list:
            if row[0].replace(" ","") == secrow[0].replace(" ",""):
                print row[0] + "," + row[1] + "," + secrow[1]
                match=True
        if not match:
            print row[0] + "," + row[1] + ", blank no match"
        time.sleep(1)

rawDescription: Merge Two CSV files in Python

description: Merge Two CSV files in Python


code:
with open(fname, 'rb') as f:
    data = f.read()

header = "\xff\xd8"
tail = "\xff\xd9"

try:
    start = data.index(header)
    end = data.index(tail, start) + 2
except ValueError:
    print "Can't find JPEG data!"
    exit()

print 'Start: %d End: %d Size: %d' % (start, end, end - start)

with open(fname + "_tr.jpg", 'wb') as f:
    f.write(data[start:end])

rawDescription: python file I/O with binary data

description: Python file I/O with binary data


code:
print repr("""Hello!
this is a test string
yay.""")

rawDescription: List of lists chunked into sublists

description: List of lists chunked into sublists


code:
trks = lib.tracks[appscript.its.name.contains('test')]
print trks.name()

rawDescription: Searching for a track on iTunes

description: Searching for a track on iTunes


code: print '<img src="{0}">'.format(site)

rawDescription: Join string containg quotation marks

description: Join string containg quotation marks


code:
import threading
from time import sleep

N = 1000
value = 0
def fast(lock):
    global value
    count = 0
    while count<N:
        sleep(.02)
        count += 1
        with lock:
            value = count

def slow():
    while 1:
        sleep(5)  # sleep for a long time
        print value   # read current value
        if value == N:
            break

if __name__=="__main__":
    lock = threading.Lock()
    fast_thread = threading.Thread(target=fast, args=(lock,))
    fast_thread.start()
    slow()
    fast_thread.join()

rawDescription: An easily refreshable Queue for Python Threading


code:
while month <= 2:
    brownGrowth = growPOP(brownPOP, totalPOP, rt(ca, cb, month), carryK)
    print "Month ", month
    print "Grown brown fish: ", brownGrowth
    brownPOP = endbrownPOP
    goldPOP = endgoldPOP
    totalPOP = endtotalPOP
    carryK = newcarryK
    month = month + 1

rawDescription: Efficient coding for loops with names for variables


code:
import lxml.etree as et

s="""

<CustomerOrders>
  <Customers>
    <CustomerID>ALFKI</CustomerID>
    <Orders>
      <OrderID>10643</OrderID>
      <CustomerID>ALFKI</CustomerID>
      <OrderDate>1997-08-25</OrderDate>
    </Orders>
    <Orders>
      <OrderID>10692</OrderID>
      <CustomerID>ALFKI</CustomerID>
      <OrderDate>1997-10-03</OrderDate>
    </Orders>
    <CompanyName>Alfreds Futterkiste</CompanyName>
  </Customers>
  <Customers>
    <CustomerID>ANATR</CustomerID>
    <Orders>
      <OrderID>10308</OrderID>
  <CustomerID>ANATR</CustomerID>
  <OrderDate>1996-09-18</OrderDate>
    </Orders>
    <CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
  </Customers>
</CustomerOrders>

"""

tree = et.fromstring(s)

for txt in tree.xpath('//text()/parent::*[1]'):
   txt.text = "%s"%txt.text.lower()

print et.tostring(tree, pretty_print=True)

rawDescription: Iterate through all elements of XML file


code:
exampleDictionary = {'thing on ground': {'backpack': {'tea': 'Earl Grey'}}}

print exampleDictionary['thing on ground']
print exampleDictionary['thing on ground']['backpack']
print exampleDictionary['thing on ground']['backpack']['tea']

rawDescription: Python. Converting string into directory


code:
from package import *

print Class1
print Class2
print Class3

rawDescription: Importing Python classes from different files in a subdirectory


code:
from IPython.lib.kernel import find_connection_file
from IPython.zmq.blockingkernelmanager import BlockingKernelManager

# this is a helper method for turning a fraction of a connection-file name
# into a full path.  If you already know the full path, you can just use that
cf = find_connection_file('6759')

km = BlockingKernelManager(connection_file=cf)
# load connection info and init communication
km.load_connection_file()
km.start_channels()

def run_cell(km, code):
    # now we can run code.  This is done on the shell channel
    shell = km.shell_channel
    print
    print "running:"
    print code

    # execution is immediate and async, returning a UUID
    msg_id = shell.execute(code)
    # get_msg can block for a reply
    reply = shell.get_msg()

    status = reply['content']['status']
    if status == 'ok':
        print 'succeeded!'
    elif status == 'error':
        print 'failed!'
        for line in reply['content']['traceback']:
            print line

run_cell(km, 'a=5')
run_cell(km, 'b=0')
run_cell(km, 'c=a/b')

rawDescription: Connecting to a remote IPython instance

description: Connecting to a remote IPython instance


code:
elems = line.split('|', 3)
print '|'.join(elems[1:3])

rawDescription: How to Print a string to a specific character?

description: Print a string to a specific character


code:
def fibonacci(number):
    if number < 2:
        return number
    print "Number is currently %d, getting fibonacci(%d)" % (number, number - 1)
    minus_one = fibonacci(number-1)
    print "Number is currently %d, just got fibonacci(%d), now getting fibonacci(%d)" % (number, number - 1, number - 2)
    minus_two = fibonacci(number-2)
    print "Number is currently %d, returning %d + %d" % (number, minus_one, minus_two)
    return minus_one + minus_two

rawDescription: What is going on with the "return fibonacci... " in this program?


code:
import sqlite3

teams = [[23L, u'team1', 5713L, u'Gange', 144L],
 [22L, u'team3', 1406L, u'Gange', 126L],
 [15L, u'team2', 7319L, u'Bob Loblaw', 90L],
 [17L, u'team2', 7319L, u'Gange', 54L],
 [18L, u'team1', 5713L, u'Bob Loblaw', 69L],
 [16L, u'team3', 1406L, u'Bob Loblaw', 113L]]

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table t (id int, team_name text, team_number int, scout text, team_score int)");
cur.executemany("insert into t values(?, ?, ?, ?, ?)", teams)
con.commit()

res = cur.execute("""
  SELECT team_number, min(team_score), max(team_score), avg(team_score)
    FROM t
GROUP BY team_number""")

print "team_number, min, max, avg"
for row in res:
    print row

rawDescription: Grouping, calculating, and sorting scoring data


code:
from import_sample import class_sample

c = class_sample()
y = c.x
print " ".join(y)

rawDescription: How to run project files using Anaconda from any directory in Windows

description: Run project files using Anaconda from any directory in Windows


code:
print d['#Home']['Users']
50

rawDescription: Easy way to store multiple data in Python 3


code:
import re
p = re.compile(ur'(?:AZA:(\d+).*?)?ZZZ:(\d+)', re.DOTALL)
test_str = u"AZA:00zx---\nZZZ:32fd---\ntestxfiler\ngsdkfklsd\nfdsfsk\nAZA:06x---\nZZZ:50----\ngsdkfklsd\ngsdkfklsd\nfdsfsk\nfdsfsk\ngsdkfklsd\nfdsfsk\nZZZ:32zzz----\nfdsfsk\nfdsfsk\ngsdkfklsd\nfdsfsk\nAZA:46----\nZZZ:53---"

re.findall(p, test_str)

rawDescription: Regex optional matches pattern

description: Regex optional matches pattern


code:
def mask_code( python_code ):
    s="+".join(["chr("+str(ord(i))+")" for i in python_code])
    return "eval("+s+")"

bad_code='''__import__("os").getcwd()'''
masked= mask_code( bad_code )
print masked
print eval(bad_code)

rawDescription: Is there a way to secure strings for Python's eval?


code:
'àèìòù'
print 'àèìòù'.replace('\xa8', '')

rawDescription: Python str vs unicode types

description: Python str vs unicode types


rawDescription: Printing X-type pattern in Python 2.7

description: Printing X-type pattern in Python 2.7


code:
inp = {
   'property1': 'value1',
   'property2.property3': 'value2',
   'property2.property7': 'value4',
   'property4.property5.property6': 'value3',

}

output = transform(inp)

print output

{'property1': 'value1',
 'property2': {
    'property3': 'value2',
    'property7': 'value4'
}
,'property4': {
    'property5': {
        'property6': 'value3'
    }
}}

rawDescription: Convert one level dictionary to structure of nested dictionaries


code:
import json
print json.loads(r'{"date": "\/Date(1411084800000)\/"}')

rawDescription: How to have a single backslash in JSON response using jsonify and flask?

description: Have a single backslash in JSON response using jsonify and flask


code:
def getter(self): print 'Get!'

def setter(self, value): print 'Set to {!r}!'.format(value)

def deleter(self): print 'Delete!'

prop = property(getter)
prop.fget is getter
prop.fset is None
prop.fdel is None

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code:
def show_diff(seqm):
    output= []
    for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
        if opcode == 'equal':
            output.append(seqm.a[a0:a1])
        elif opcode == 'insert':
            output.append("" + seqm.b[b0:b1] + "")
        elif opcode == 'delete':
            output.append("" + seqm.a[a0:a1] + "")
        elif opcode == 'replace':
            output.append("" + seqm.a[a0:a1] + "" + "" + seqm.b[b0:b1] + "" )
        else:
            raise RuntimeError, "Unexpected opcode"
    return ''.join(output)

rawDescription: How to create a manual diff between two Json objects which can be sent to Reviewboard using python?

description: Create a manual diff between two Json objects which can be sent to Reviewboard using python


code:
with File('file.name') as f:
    print f.head(5)
    print f.tail(5)
    for row in f.backward():
        print row

rawDescription: python head, tail and backward read by lines of a text file

description: Python head, tail and backward read by lines of a text file


code:
from timeit import timeit

# All the same
print timeit('len(set([2, 2, 2, 2])) == 1')
# 0.843292317054

# Not the same
print timeit('len(set([2, 1, 2, 2])) == 1')
# 0.869108628247

## Without set ##

# AlL the same
print timeit('all(item == x[0] for item in x)', setup='x = [2,2,2,2]')
# 1.20339177387

# Not the same
print timeit('all(item == x[0] for item in x)', setup='x = [2, 1, 2, 2]')
# 1.42827283125

rawDescription: Is there any easy way to compare list items in python?


code:
words = []
wordset = set(())

file = open('List.txt')
for line in file:
    word = line.strip('\n')
    words.append(word)
    wordset.add(word)

for word in words:
    reversed = word[::-1]
    if reversed in wordset:
        print word + ' is the opposite of ' + reversed

rawDescription: Finding words that are the reverse of each other in a file


code: print "i is equal to {}".format(i)

rawDescription: how do you put a period right next to a variable in python?

description: Put a period right next to a variable in python


code:
def printHuffTree2(freqs, huffTree, prefix = ''):
   if len(huffTree) == 2:
      letter = huffTree[1]
      val = len(prefix)*freqs[letter]
      print '%s: %s\t%u * %f = %f' % \
          (huffTree[1], prefix, len(prefix), freqs[letter], val)
      return val
   else:
      lhs = printHuffTree2(freqs, huffTree[1], prefix + '0')
      rhs = printHuffTree2(freqs, huffTree[2], prefix + '1')
      return (lhs+rhs)

rawDescription: Python, SUM of multiply

description: Python, SUM of multiply


code:
def verify_permissions(request):
  user = request.user
  sid = request.POST.get('subscription_id')
  try:
    sub = Subscription.objects.get(id=sid)
  except ObjectDoesNotExist:
    raise PermissionError, 'Given subscription does not exist.'
  if sub.user != user:
    raise PermissionError, 'Invalid permission.'

def subscribe(request):
  try:
    verify_permissions(request)
    sub.save()
    return ajax_response(True)
  except PermissionError, why:
    return ajax_response(False, [('subscription', why)])

rawDescription: how should i refactor a piece of code that is present in many different functions, but has return statement in it

description: How should i refactor a piece of code that is present in many different functions, but has return statement in it


code:
'\xe2\x80\x94-test'.decode('utf8')
print '\xe2\x80\x94-test'.decode('utf8')
'\xe2\x80\x9cTest\xe2\x80\x9d'.decode('utf8')
print '\xe2\x80\x9cTest\xe2\x80\x9d'.decode('utf8')
import unicodedata
for u in u'\u2014\u201c\u201d':
    print u, unicodedata.name(u)

rawDescription: Python arguments are read as code

description: Python arguments are read as code


code:
# read field labels from first line in file
header = reader.next()
# prepare static output
templates = [('  <Placemark>\n   <name>{}</name>\n', 'name'),
         ('   <description>\n    <![CDATA[\n     \n', 'image'),
         ('     {}\n', 'address'),
         ('     {}\n', 'postcode'),
         ('     {}\n', 'country'),
         ('     Tel: {}\n', 'telephone'),
         ('     Mail: {}\n', 'Email'),
         ('   </description>\n   <Point>\n    <coordinates>{},', 'lat'),
         ('{}</coordinates>\n   </Point>\n  </Placemark>\n', 'lng')]
# lookup function for field values. leading and trailing whitespace will be removed
value = lambda field, array: array[header.index(field)].lstrip().rstrip()

# start output
print '''<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>'''
# insert values into xml
for row in reader:
    for t, f in templates:
        print t.format(value(f, row)),

print ' </Document>\n</kml>'

rawDescription: Create KML file for Google Maps from CSV


code:
from itertools import islice, izip

#prints out samenodes
f = open('newerfile.txt')
mylist = list(f)

zippedLists = itertools.izip(mylist, islice(mylist, 12), islice(mylist, 2), islice(mylist, 13))
slicedList = itertools.islice(zippedLists, 0, None, 12)

for elt1, elt13, elt2, elt14 in slicedList:
    if elt1 == elt13 and elt2 == elt14:
        print elt1

rawDescription: Loop to Match Parts of List

description: Loop to Match Parts of List