code:
import ctypes
from random import randrange, seed

seed(42)

SPAMSUM_LENGTH = 64
FUZZY_MAX_RESULT = SPAMSUM_LENGTH + SPAMSUM_LENGTH // 2 + 20
SIZE = 0x50000

fuzzy = ctypes.CDLL('fuzzy.dll')

fuzzy_hash_buf = fuzzy.fuzzy_hash_buf
fuzzy_hash_buf.restype = ctypes.c_int
fuzzy_hash_buf.argtypes = [
    ctypes.c_char_p, #buf
    ctypes.c_uint32, #buf_len
    ctypes.c_char_p, #result
]
fuzzy_compare = fuzzy.fuzzy_compare
fuzzy_compare.restype = ctypes.c_int
fuzzy_compare.argtypes = [
    ctypes.c_char_p, #sig1
    ctypes.c_char_p, #sig2
]

out1 = ctypes.create_string_buffer('\x00' * FUZZY_MAX_RESULT)
out2 = ctypes.create_string_buffer('\x00' * FUZZY_MAX_RESULT)

in1 = ''.join(chr(randrange(256)) for x in xrange(SIZE))
in2 = ''.join(c if (i < 0x100 or i >= 0x110) else '\x25'
              for i, c in enumerate(in1))

print fuzzy_hash_buf(in1, len(in1), out1)
print fuzzy_hash_buf(in2, len(in2), out2)
print out1.value
print out2.value
print fuzzy_compare(out1, out2)

rawDescription: ssdeep's fuzzy_compare always returns 0 loaded from ctypes python

description: Ssdeep's fuzzy_compare always returns 0 loaded from ctypes python


code:
import numpy as np

def func1():   #No map -- And pretty speedy :-).
    a=np.zeros((3000,300),dtype=np.float32)
    with open('junk.txt') as f:
        for i,line in enumerate(f):
            a[i,:]=line.split()

def func2():
    a=np.zeros((3000,300),dtype=np.float32)
    with open('junk.txt') as f:
        for i,line in enumerate(f):
            a[i,:]=map(np.float32,line.split())

def func3():
    a=np.zeros((3000,300),dtype=np.float32)
    with open('junk.txt') as f:
        for i,line in enumerate(f):
            a[i,:]=map(float,line.split())

import timeit

print timeit.timeit('func1()',setup='from __main__ import func1',number=3)  #1.36s
print timeit.timeit('func2()',setup='from __main__ import func2',number=3)  #11.53s
print timeit.timeit('func3()',setup='from __main__ import func3',number=3)  #1.72s

rawDescription: Convert a string list to float32 efficiently


code: print re.sub('(?<=#)(\w+)(?=#)', lambda m:m.group(1).title(), text)

rawDescription: Replacing words tagged by #word# within a string


code:
class Foo(object):
   @staticmethod
   def foo():
      print 'foo'
   def bar(self):
      print 'bar'

rawDescription: Are there any benefits from using a @staticmethod?


code:
def instrument_operator_hooks(cls):
    def add_hook(name):
        operator_func = getattr(operator, name.strip('_'), None)
        existing = getattr(cls, name, None)

        def op_hook(self, *args, **kw):
            print "Hooking into {}".format(name)
            self._function = operator_func
            self._params = (args, kw)
            if existing is not None:
                return existing(self, *args, **kw)
            raise AttributeError(name)

        try:
            setattr(cls, name, op_hook)
        except (AttributeError, TypeError):
            pass  # skip __name__ and __doc__ and the like

    for hook_name in operator_hooks:
        add_hook(hook_name)
    return cls

rawDescription: How to catch any method called on an object in python?

description: Catch any method called on an object in python


code:
import re
import itertools as it

text = "<h> This is a string. </H><p> This is another part. </P>"

cnt = it.count()
print re.sub(r"</?\w+>", lambda x: '{{{}}}'.format(next(cnt)), text)

rawDescription: replace pattern with a sequential number string in python

description: Replace pattern with a sequential number string in python


code:
def func():
    pass

new_func = func
print func.__name__
print new_func.__name__

rawDescription: Get function name as a string in python

description: Get function name as a string in python


code:
import re
vdd_level_re = re.compile(r'(\d+)\:\s*(\d+)')

vdd_levels = {}
with open('/sys/devices/system/cpu/cpuX/cpufreq/vdd_levels') as vdd_level_file:
    for vdd_level in vdd_level_file:
        level = vdd_level_re.match(vdd_level)
        if level:
            k,v = level.group(1,2)
            vdd_levels[k] = v
        else:
            print "line did not match expected format"
            print vdd_level

rawDescription: How do I clean data from a file and get it in a dictionary?

description: Clean data from a file and get it in a dictionary


code:
src = """

OPEN
80002

ACCY

2001

10
Intro Financial Accounting
3.00
 Ray, K
MON 113
MW
12:45PM - 02:00PM
08/25/14 - 12/06/14

"""

from lxml import html

tree = html.fromstring(src)
tds = tree.xpath("//td/descendant-or-self::*/text()[normalize-space()]")

print ", ".join([td.strip() for td in tds])

rawDescription: Extract html cell data XPath

description: Extract html cell data XPath


code: print sigma, k

rawDescription: Approximate an infinite sum within some epsilon


code:
import yaml
with open("data.yml", "r") as f:
    data = yaml.load(f)
exec data['list']

rawDescription: Execute Python code embedded in YAML file


code:
import os
import multiprocessing as mp
import sys

def foo(stdin):
    print 'Foo: ',
    status = stdin.readline()
    # You could use raw_input instead of stdin.readline, but
    # using raw_input will cause an error if you call it in more
    # than one subprocess, while `stdin.readline` does not
    # cause an error.
    print('Received: {}'.format(status))

status = raw_input('Host? (Y/N) ')
print(status)
newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
try:
    proc1 = mp.Process(target = foo, args = (newstdin, ))
    proc1.start()
    proc1.join()
finally:
    newstdin.close()

rawDescription: raw input and multiprocessing in python

description: Raw input and multiprocessing in python


code:
import re
a = "-hlocalhost-uuser-ppassword"
b = re.split("(-h)|(-u)|(-p)", a)[1:]
a = [x for x in b if x is not None]
b = dict(zip(a[0::2], a[1::2]))
print b

rawDescription: get text via re in python

description: Get text via re in python


code:
import re
text = '''<select name="sel">
   <option value="a">a</option>
   <option value="b">b</option>
   <option value="c">c</option>
   <option value="d">d</option>
</select>'''
pattern = re.compile(r'<option value="(?P<val>.*?)">(?P=val)</option>')
handy_list = pattern.findall(text)
print handy_list

rawDescription: html select option into a list

description: Html select option into a list


rawDescription: how to change the inner element tuple into list?

description: Change the inner element tuple into list


code:
import csv
import StringIO

s = '''"thing1,blah","thing2,blah","thing3,blah"
"thing4,blah","thing5,blah","thing6,blah"'''
source = StringIO.StringIO(s)
dest = StringIO.StringIO()
rdr = csv.reader(source)
wtr = csv.writer(dest)
for row in rdr:
    wtr.writerow([item.replace('\\,',',').replace(',','\\,') for item in row])
print dest.getvalue()

rawDescription: Python RegEx nested search and replace

description: Python RegEx nested search and replace


code:
import serial, time

try:
    station1 = serial.Serial('/dev/ttyUSB0', 9600,timeout=0)
    print 'station one Is Ready!! Please Show your Card'
except serial.SerialException:
        print 'Station 1 is Down'

while True:
    card_dataa = station1.read(12)
    if len(card_dataa) > 0: print card_dataa

rawDescription: Jumbled out put of RFID Tags

description: Jumbled out put of RFID Tags


code:
def do_something( self ):
    print 'I have done something'

rawDescription: referring to self from within self in python

description: Referring to self from within self in python


code:
class Person:
    name="Person"
    def speak(self):
        print "Hi! Im %s"%slf.name

class Dad(Person):
     name = "Dad"

class Mom(Person):
     name = "Mom"

class Child(Person):
     name = "a Child"
     age  = 5
     def speak(self):
        print "Hewwo, I am a %d year old child!"%self.age

d = Dad()
m = Mom()
c = Child()

c.speak()
m.speak()
d.speak()

rawDescription: Child classes and parent classes in Python


code:
import re

data = """group Head:
  data1: abc         data2: def
  2word data3: ghi   data4: jkl
  data3: mno         three word data4: pqr stu"""

for l in data.split('\n'):
    print [ x.split(':') for x in re.split('\s\s+', l) if x ]

rawDescription: How to improve a python regex data file parsing efficiency?

description: Improve a python regex data file parsing efficiency


code:
user = "Username"
prefix = user + ":\t\t"
expanded_indent = textwrap.fill(prefix+'$', replace_whitespace=False)[:-1]
subsequent_indent = ' ' * len(expanded_indent)
wrapper = textwrap.TextWrapper(initial_indent=prefix,
                               subsequent_indent=subsequent_indent)
message = "LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT " * 3
print wrapper.fill(message)

rawDescription: Printing with indentation in python

description: Printing with indentation in python


code:
print "r1"   # before first return
print "r2"   # at the end of the function, before second, implicit return

rawDescription: Tower of Hanoi Call Trace

description: Tower of Hanoi Call Trace


code:
a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"
position = 0
previous_position = 0
final_array = []
temp_array = []
for character in a:
    if character == ',':
        temp_array = []
        temp_array.append(int(a[previous_position:position]))
        previous_position = position
    elif character == ' ':
        temp_array.append(int(a[previous_position+1:position]))
        previous_position = position+1
        final_array.append(temp_array)
    elif position == len(a) - 1:
        temp_array.append(int(a[previous_position+1:]))
        final_array.append(temp_array)

    position += 1

print final_array

rawDescription: Convert series of numbers to array in Python


rawDescription: Subiterate over a tuple

description: Subiterate over a tuple


code: print root.attrib['a']

rawDescription: Get root's attributes - elementtree

description: Get root's attributes - elementtree


code:
class MyDualArrayStruct(C.Structure):
    _fields_ = [("c_x", C.POINTER(C.c_double)),
                ("c_y", C.POINTER(C.c_int))]

    def __init__(self,*args,**kwargs):
        super(MyDualArrayStruct,self).__init__(*args,**kwargs)
        self.np_x = np.array([1,2,3,4,5],dtype="float64")
        self.c_x = np.ctypeslib.as_ctypes(self.np_x)
        self.np_y = np.array([5,4,3,2,1],dtype="int32")
        self.c_y = np.ctypeslib.as_ctypes(self.np_y)

test = MyDualArrayStruct()

print test.np_x
print test.c_x[:5]

# Note that here c_x and np_x both contain the same data. Thus modifying one of them
# (inplace) modifies the other. You can use this to do easy inplace modification of
# numpy arrays in C functions.
# This implies that test.np_x.sum() is also the sum of test.c_x
test.np_x[:] = 1

print test.np_x
print test.c_x[:5]

rawDescription: Access np.array in ctypes struct

description: Access np.array in ctypes struct


code:
coefficients = np.polyfit(soDF['log_total_rep'] , soDF['log_users'], 2)

print "Coefficients: ", coefficients

rawDescription: using pandas and numpy to parametrize stack overflow's number of users and reputation

description: Using pandas and numpy to parametrize stack overflow's number of users and reputation


code:
import itertools
for comb in itertools.product(range(4), repeat=3):
    print comb

rawDescription: Python: Recursion to count up an array of size n


code:
print dict( sorted(d.items(), key=lambda item:item[0][1]))
from collections import OrderedDict
print OrderedDict( sorted(d.items(), key=lambda item:item[0][1]))

rawDescription: How to sort a dictionary by value where the key is a tuple

description: Sort a dictionary by value where the key is a tuple


code:
import socket, ssl, pprint

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# require a certificate from the server
ssl_sock = ssl.wrap_socket(s,
                           # http://curl.haxx.se/ca/cacert.pem
                           ca_certs="cacert.pem",
                           cert_reqs=ssl.CERT_REQUIRED)

ssl_sock.connect(('www.verisign.com', 443))

print repr(ssl_sock.getpeername())
print ssl_sock.cipher()
print pprint.pformat(ssl_sock.getpeercert())

# Set a simple HTTP request -- use httplib in actual code.
ssl_sock.write("""GET / HTTP/1.0\r
Host: www.verisign.com\r\n\r\n""")

# Read a chunk of data.  Will not necessarily
# read all the data returned by the server.
data = ssl_sock.read()
print repr(data)[:79]

# note that closing the SSLSocket will also close the underlying socket
ssl_sock.close()

rawDescription: Getting a raw, unparsed response to a HTTPS GET request


code:
names = g.vs["name"]
for edge in g.es:
    print names[edge.tuple[0]], names[edge.tuple[1]], edge["weight"]

rawDescription: Using igraph for read 'ncol' format while preserving labels


code:
cfdist = ConditionalFreqDist()

for word in word_tokenize(text):
    condition = len(word)
    cfdist[condition][word] += 1

for condition in cfdist:
    for word in cfdist[condition]:
        print "Cond. frequency of", word, cfdist[condition].freq(word), "[condition is word-length=", condition, "]"

rawDescription: New to nltk, having trouble with conditional frequency


rawDescription: Pairwise Elements Using Python - Calculating Average of individual elements of array


code:
import itertools

def generate_pairs(*args):
    # assuming function is commutative
    for i, l in enumerate(args, 1):
        for x, y in itertools.product(l, itertools.chain(*args[i:])):
            yield (x, y)

# you can use lists instead of strings as well
for x, y in generate_pairs("ab", "cd", "ef"):
    print (x, y)

# e.g., apply your comparison logic
print any(x == y for x, y in generate_pairs("ab", "cd", "ef"))
print all(x != y for x, y in generate_pairs("ab", "cd", "ef"))

rawDescription: Generate combinations of elements from multiple lists


code:
myvariable = 5
def func():
    global myvariable
    myvariable = 6   #changes `myvariable` at the global scope
    print myvariable #prints 6

func()
print myvariable  #prints 6 now because we were able
                  #to modify the reference in the function

rawDescription: In Python what is a global statement?

description: In Python what is a global statement


code:
def find_repeats(L, required_number, num_repeats, stop_after_match=False):
    idx = 0
    while idx < len(L):
        if [required_number]*num_repeats == L[idx:idx+num_repeats]:
            L[idx:idx+num_repeats] = [True]*num_repeats
            idx += num_repeats
            if stop_after_match:
                break
        else:
            idx += 1
    return L

L=[1,1,1,4,6]
print find_repeats(L, 1, 2)
L=[1,1,1,4,6]
print find_repeats(L, 1, 3)
L=[1,1,1,4,4,4,6]
print find_repeats(L, 1, 3)
L=[1,1,1,4,4,4,6]
print find_repeats(L, 4, 3)

rawDescription: Python finding n consecutive numbers in a list


code:
comment = fields.Char(compute='_compute_comment')

def _compute_comment(self):
    for record in self:
        record.comment = partner_id.comment
        print record.comment

rawDescription: How to use related fields (fields.related) in odoo-8?

description: Use related fields (fields.related) in odoo-8


code:
def reverse(ip):
        if len(ip) <= 1:
                return ip
        l = ip.split('.')
        return '.'.join(l[::-1])

ip = '10.1.2.3'
print reverse(ip)

rawDescription: performing IP reversing in string

description: Performing IP reversing in string


code:
r = Reader()
for path in ['file1.txt', 'file2.txt']:
    r.add(open(path, 'rb'))

for event, elem in etree.iterparse(r):
    print event, elem.tag

rawDescription: Parse large split XML file(s) with Python


code:
first_names  = map(lambda el: el.text, browser.find_elements_by_xpath('//tr/td[1]'))
second_names = map(lambda el: el.text, browser.find_elements_by_xpath('//tr/td[2]'))
headers      = map(lambda el: el.text, browser.find_elements_by_xpath('//th/div'))

print [{headers[0]: first_names[i], headers[1]: second_names[i]} for i in range(len(first_names))]

rawDescription: Assign table headers as keys in Python dict


code:
def f(x):
    return x + 1

print f(3)

rawDescription: Return Statements in Recursion

description: Return Statements in Recursion


code:
def sort_by_type():
    maininput = iter("acdre2345ty")

    for char in maininput:
        if char.isalpha():
            print char
        elif char.isdigit():
            number = char
            while True:
                # try/except could take care of the StopIteration exception
                # when a digit is last in the string
                #
                # try:
                #    char = maininput.next()
                # except StopIteration:
                #    char = ""
                #
                # however using next(iterator, default) is much better:
                #
                char = next(maininput, "")

                if char.isdigit():
                    number += char
                else:
                    break
            print number
            print char

rawDescription: Python iterator behaviour

description: Python iterator behaviour


code:
import sympy
from sympy.core.function import Function
from sympy.core import S
from sympy import sympify
from sympy.functions import im
from scipy.special import wofz

class Wofz(Function):
    is_real = True
    @classmethod
    def _should_evalf(csl,arg):
        return True
    def as_base_exp(cls):
        return cls,S.One

    def _eval_evalf(cls, prec):
        return sympy.numbers.Number(im(wofz(float(cls.args[0]))))

print sympify("Wofz(2)",{'Wofz':Wofz}).evalf()

rawDescription: Python: Using sympy.sympify to perform a safe eval() on mathematical functions


code:
import urllib2
from BeautifulSoup import BeautifulSoup

q = urllib2.urlopen('http://stackoverflow.com/questions/3884419/')
soup = BeautifulSoup(q.read())

for link in soup.findAll('a'):
    if link.has_key('href'):
        print str(link.string) + " -> " + link['href']
    elif link.has_key('id'):
        print "ID: " + link['id']
    else:
        print "???"

rawDescription: How do I use regular expressions to parse HTML tags?

description: Use regular expressions to parse HTML tags


code:
#like the built-in function `max`,
#but returns the index of the largest element
#instead of the largest element itself.
def index_of_max(seq, key=lambda item:item):
    return max(range(len(seq)), key=lambda idx: key(seq[idx]))

lists = [
    [2, 3, 2, 4, 5],
    [1, 3, 2, 3, 2],
    [1, 1, 2, 2, 2],
    [3, 2, 2, 4, 5]
]

idx = index_of_max(lists, key=lambda item: (sum(item), item[0]))
#add one to this result because Python lists are zero indexed,
#but the original numbering scheme started at one.
print "List # {} is largest.".format(idx+1)

rawDescription: Isolating lists based on value in python3


code:
json_functions={}
def make_available_to_json(f):
 json_functions[f.__name__]=f
 return f
@make_available_to_json
def sayhello():
 print "Hello World!"
json_functions.get("sayhello")()
json_functions["sayhello"]()
json_functions.get("prove_riemann_hypothesis", sayhello)()

rawDescription: Python: How do you call a method when you only have the string name of the method?


code:
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup('''\

        text1:
        text_1.1

        text2
        text_2.1
        text_2.2

        text4
        text_4.1
        text_4.2
        text_4.3
        text_4.4

        text5
         text5.1

        text6
        text6.1
        text6.2
        text6.3

        text7
        text7.1
        text7.2

        text8
        2

''')
results = OrderedDict()
for li in soup.find_all('li'):
    bold = li.b
    if bold is None:
        continue
    results[bold.get_text(strip=True)] = [
        link.get_text(strip=True) for link in li.find_all('a')
    ]

results
for key, elems in results.items():
    print '{}: {}'.format(key, ', '.join(elems))

rawDescription: How to get print the content of tags in order in beautifulsoup?

description: Get print the content of tags in order in beautifulsoup


code:
maxNum, current, result = 12, 1, []

while maxNum > current:
    result.append(current)
    maxNum -= current
    current += 1
result.append(maxNum)
print result

rawDescription: How to generate this list from user entered number using python?

description: Generate this list from user entered number using python


code:
df['diff'] = df[1].diff()
df['diff_modulo'] = df['diff'].mod(100)

print df

rawDescription: Sum of precipitation per Timeframe in pandas DataFrame


code:
def primes3():
    p = 2
    yield p
    sifter = gensifter(p) # <-- changed!
    s = next(sifter)
    for p in count(p+1):
        #print '(testing p = %d\ts = %d)' % (p, s)
        if p==s: # this p is sieved out
            print 's:', s
            s = next(sifter)
        else:
            yield p # this is prime
            print 'p:', p
            sifter = (k for k, g in groupby(merge(sifter,gensifter(p)))) # <-- changed!

rawDescription: Merged iterators produce obscure results


code:
def user_authenticate():
    login = request.form.get('login')
    password = request.form.get('password')
    print login, password

rawDescription: Sending a POST request with Angularjs and get parameters in a Flask backend


code:
import numpy

with open("myfile.fa","rt") as infile:
    matrix =  numpy.matrix([list(line.strip()) for line in infile.readlines()])
    print matrix

rawDescription: How to open a text file as a character matrix in python?

description: Open a text file as a character matrix in python


code:
set_of_strings = {'abc', 'def', 'xyz'}
dict_of_dicts = {}
for key in set_of_strings:
    dict_of_dicts[key] = {'pr':0, 'wt':0}

print dict_of_dicts

rawDescription: GIven a set of strings, create a dictionary of dictionaries using them as keys to entries with default values


code:
import os

rootPath = "D:\\desktop"
counter = 0
for file in os.listdir(rootPath):
    if file.endswith('.pdf'):
        os.startfile("%s/%s" %(rootPath, file))
        counter = counter + 1
print counter

rawDescription: Open pdf files format with python

description: Open pdf files format with python


code:
from itertools import product
A = [('a', 'b'), ('c', 'd'), ('e', 'f')]
for perm in product(*((l, l[::-1]) for l in A)):
    print perm

rawDescription: generating list with permuted tuples in a list

description: Generating list with permuted tuples in a list


code:
settings
helper
Helper in lib.settings
someobject
Helper in lib.foo.someobject

# ./import_submodule.py
import fnmatch, os
from lib.settings import Values
from lib import Helper

print
for root, dirs, files in os.walk('.'):
    for f in fnmatch.filter(files, '*.py'):
        print "# %s/%s" % (os.path.basename(root), f)
        print open(os.path.join(root, f)).read()
        print

# lib/helper.py
print 'helper'
class Helper(object):
    def __init__(self, module_name):
        print "Helper in", module_name

# lib/settings.py
print "settings"
import helper

class Values(object):
    pass

helper.Helper(__name__)

# lib/__init__.py
#from __future__ import absolute_import
import settings, foo.someobject, helper

Helper = helper.Helper

# foo/someobject.py
print "someobject"
from .. import helper

helper.Helper(__name__)

# foo/__init__.py
import someobject

rawDescription: How to import classes defined in __init__.py

description: Import classes defined in __init__.py


code:
class Table(frozenset):
    def __new__(cls, names, rows):
        return frozenset.__new__(cls, rows)

    def __init__(self, names, rows):
        frozenset.__init__(self, rows)
        self.names = names

def add_column(rows, func):
    return [row + (func(row, idx),) for (idx, row) in enumerate(rows)]

def table_process(t, (name, func)):
    return Table(
        t.names + (name,),
        add_column(t, lambda row, idx: func(row))
        )

def table_filter(t, (name, func)):
    names = t.names
    idx = names.index(name)
    return Table(
        names,
        [row for row in t if func(row[idx])]
        )

def table_rank(t, name):
    names = t.names
    idx = names.index(name)
    rows = sorted(t, key = lambda row: row[idx])
    return Table(
        names + ('rank',),
        add_column(rows, lambda row, idx: idx)
        )

def table_print(t):
    format_row = lambda r: ' '.join('%15s' % c for c in r)
    print format_row(t.names)
    print '\n'.join(format_row(row) for row in t)

if __name__ == '__main__':
    from random import randint
    cols = ('c1', 'c2', 'c3')
    T = Table(
        cols,
        [tuple(randint(0, 9) for x in cols) for x in range(10)]
        )
    table_print(T)

    # Columns to add to the table, this is a perfect fit for a
    # reduce. I'd honestly use a boring for loop instead, but reduce
    # is a perfect example for how in FP data and code "becomes one."
    # In fact, this whole program could have been written as just one
    # big reduce.
    actions = [
        ('max', max),
        ('min', min),
        ('sum', sum),
        ('avg', lambda r: sum(r) / float(len(r)))
        ]
    T = reduce(table_process, actions, T)
    table_print(T)

    # Ranking is different because it requires an ordering, which a
    # table does not have.
    T2 = table_rank(T, 'sum')
    table_print(T2)

    # Simple where filter: select * from T2 where c2 < 5.
    T3 = table_filter(T2, ('c2', lambda c: c < 5))
    table_print(T3)

rawDescription: Converting an imperative algorithm that "grows" a table into pure functions


code:
for word in words.right:
    za = word
print za

rawDescription: My search terms are only printing our the last term in a list instead of the term found [Python 2.7.6]


code:
a, b = 0, 1
counter = input("Please enter the term you wish to end at: ")
for _ in xrange(counter): #xrange is more efficient than range, the number is not used so _ is used to show that
    a, b = b, a+b
    print a
    print

rawDescription: Checking efficiency of a Python Fibonacci Sequence Generator?


code:
import numpy as np

A = np.random.randint(0, 10, (3, 4))

print A
print A.cumsum(axis=0).cumsum(axis=1)

rawDescription: Efficient summed Area Table Calculation with Numpy


code:
execfile('./vars.py')
print git_branch

rawDescription: Getting variables from another python file WITHOUT importing


code:
from decimal import Decimal
from repr import Repr

class CustomRepr(Repr):
    def repr_Decimal(self, obj, level):
        return "{0:.2f}".format(obj)

cr = CustomRepr()

data = {"money": [Decimal("42")]}

print cr.repr(data)

rawDescription: Python: Making Dollars make Sense

description: Python: Making Dollars make Sense


code:
from cStringIO import StringIO

# csvFile = 'Facility No\tTesting No\tName\tAge\n\n252\t2351\tJackrabbit, Jazz\t15\n345\t257\tAardvark, Ethel\t41\n'
reader = csv.DictReader(StringIO(csvFile), delimiter='\t', quoting=csv.QUOTE_NONE)
print reader.fieldnames

rawDescription: DictReader, No quotes, tabbed file

description: DictReader, No quotes, tabbed file


code:
def onSessionOpen(self):
    global ses_var

    ses_var[self.session_id] = self
    print "connection from ", self.peer.host, self.peer.port

rawDescription: How to obtain the client IP address in Autobahn Wamp Protocol?

description: Obtain the client IP address in Autobahn Wamp Protocol


code:
import pandas as pd

df1 = pd.DataFrame({
    'ID': ['a', 'b', 'c'],
    'Value': [45, 3, 10]
})

df2 = pd.DataFrame({
    'ID': ['a', 'b', 'c', 'd', 'e'],
    'ID_n': [3, 35, 0, 7, 1],
})

df1.set_index(['ID'], drop=False, inplace=True)
df2.set_index(['ID'], drop=False, inplace=True)

print pd.merge(df1, df2, on="ID", how='left')

rawDescription: How can I check the ID of a pandas data frame in another data frame in Python?

description: Check the ID of a pandas data frame in another data frame in Python


code:
from itertools import product
nested = product(product(Colour, Type), repeat=2)

# flatten it by unpacking each element
print [(a,b,c,d) for ((a,b),(c,d)) in nested]

# alternative way to flatten the product
from itertools import chain
print [tuple(chain.from_iterable(x)) for x in nested]

rawDescription: Listing out binary combinations and mapping to data


code:
var = "String"
fileName = var + ".xml"
print fileName

rawDescription: Using variable content as part of file name of my output file


code:
for a, b in [(1, 'x'), (2, 'y')]:
    print a, "and b is", b

rawDescription: SQLAlchemy: How is it that a comma determines if a query returns a String or a Tuple?


rawDescription: Retrive data from jquery-json to python

description: Retrive data from jquery-json to python


code:
import broken
from broken import dependency

def brokenfunc():
    print "patched"

    dependency()

broken.brokenfunc = brokenfunc

rawDescription: Monkey patching a module function depending on another function inside the module


code:
from BeautifulSoup import BeautifulSoup
doc = '
yep

somelink
another'
soup = BeautifulSoup(doc)
print soup.prettify()

rawDescription: Find specific link w/ beautifulsoup

description: Find specific link w/ beautifulsoup


code:
from itertools import combinations
def myStrings(s):
    return ["".join(item) for i in range(1,len(s)) for item in combinations(s,i)]

print myStrings('ab')
print myStrings('abc')
print myStrings('abcd')

rawDescription: Subsets for a string

description: Subsets for a string


code:
import zmq

context = zmq.Context()
sender = context.socket(zmq.PUB)
sender.connect("tcp://localhost:5555")

sender.send("Sending to nobody", zmq.NOBLOCK)

print "Msg sent"

rawDescription: issue when implementing a non-blocking publishing mechanism with zeromq

description: Issue when implementing a non-blocking publishing mechanism with zeromq


code:
fdfg = connections.groupby('friendName')
for k, v in fdfg:
    if len(v) > 1:
        print k
        print v.name

rawDescription: Common item selection - Pandas Dataframe


code:
reg = '.*?/[\d\s]*(.*)'
print re.match(reg, '27P/Crommelin').group(1)
print re.match(reg, 'C/1991 L3 Levy').group(1)

rawDescription: read a table according to a certain number of characters

description: Read a table according to a certain number of characters


code:
import csv
import json

filename = 'qdata.csv'
fieldnames = ('district', 'Zone', 'geography',
    'Dev Region', 'casualties', 'injured')

geo_keys = ('Zone', 'geography', 'Dev Region')

all_data = {}
with open(filename, 'rb') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    # skip header
    next(reader)
    current_district = None
    for row in reader:
        district = row['district']
        if district != current_district:
            current_district = district
            data = all_data[district] = {}
            casualties = data['Casualties'] = {}
            data['geoInfo'] = dict((k, row[k]) for k in geo_keys)
        casualties[row['casualties']] = row['injured']

print json.dumps(all_data, indent=4, sort_keys=True)

rawDescription: Convert CSV to restructured JSON in Python


code:
while True:
    try:
        #check for a message, this will not block
        message = socket.recv(flags=zmq.NOBLOCK)

        #a message has been received
        print "Message received:", message

    except zmq.Again as e:
        print "No message received yet"

    # perform other important stuff
    time.sleep(10)

rawDescription: zero-mq: socket.recv() call is blocking

description: Zero-mq: socket.recv() call is blocking


code:
from collections import defaultdict
with open("abc") as f:
    dic=defaultdict(list)
    i=1
    for line in f:
          line=line.strip()
          if line:
             dic[i].append(line)
             i+=1
          else:
             i=1

for i in range(1,10,2):   #get the 1,3,5,7,9 line
   print "This is row {0}: {1}".format(i," ".join(dic[i]))

print

for i in [1,4,8]:        #get the 1,4,8 line
   print "This is row {0}: {1}".format(i," ".join(dic[i]))

rawDescription: Python- get specific lines from a file and iterate


code:
import random
z = 0
while(z < 0.5625):
    z = square_of_average(random.random(), random.random(), random.random())
print z

rawDescription: Random function with break command in Python


code:
#partition list a into k partitions
def partition_list(a, k):
    #check degenerate conditions
    if k <= 1: return [a]
    if k >= len(a): return [[x] for x in a]
    #create a list of indexes to partition between, using the index on the
    #left of the partition to indicate where to partition
    #to start, roughly partition the array into equal groups of len(a)/k (note
    #that the last group may be a different size)
    partition_between = []
    for i in range(k-1):
        partition_between.append((i+1)*len(a)/k)
    #the ideal size for all partitions is the total height of the list divided
    #by the number of paritions
    average_height = float(sum(a))/k
    best_score = None
    best_partitions = None
    count = 0
    no_improvements_count = 0
    #loop over possible partitionings
    while True:
        #partition the list
        partitions = []
        index = 0
        for div in partition_between:
            #create partitions based on partition_between
            partitions.append(a[index:div])
            index = div
        #append the last partition, which runs from the last partition divider
        #to the end of the list
        partitions.append(a[index:])
        #evaluate the partitioning
        worst_height_diff = 0
        worst_partition_index = -1
        for p in partitions:
            #compare the partition height to the ideal partition height
            height_diff = average_height - sum(p)
            #if it's the worst partition we've seen, update the variables that
            #track that
            if abs(height_diff) > abs(worst_height_diff):
                worst_height_diff = height_diff
                worst_partition_index = partitions.index(p)
        #if the worst partition from this run is still better than anything
        #we saw in previous iterations, update our best-ever variables
        if best_score is None or abs(worst_height_diff) < best_score:
            best_score = abs(worst_height_diff)
            best_partitions = partitions
            no_improvements_count = 0
        else:
            no_improvements_count += 1
        #decide if we're done: if all our partition heights are ideal, or if
        #we haven't seen improvement in >5 iterations, or we've tried 100
        #different partitionings
        #the criteria to exit are important for getting a good result with
        #complex data, and changing them is a good way to experiment with getting
        #improved results
        if worst_height_diff == 0 or no_improvements_count > 5 or count > 100:
            return best_partitions
        count += 1
        #adjust the partitioning of the worst partition to move it closer to the
        #ideal size. the overall goal is to take the worst partition and adjust
        #its size to try and make its height closer to the ideal. generally, if
        #the worst partition is too big, we want to shrink the worst partition
        #by moving one of its ends into the smaller of the two neighboring
        #partitions. if the worst partition is too small, we want to grow the
        #partition by expanding the partition towards the larger of the two
        #neighboring partitions
        if worst_partition_index == 0:   #the worst partition is the first one
            if worst_height_diff < 0: partition_between[0] -= 1   #partition too big, so make it smaller
            else: partition_between[0] += 1   #partition too small, so make it bigger
        elif worst_partition_index == len(partitions)-1: #the worst partition is the last one
            if worst_height_diff < 0: partition_between[-1] += 1   #partition too small, so make it bigger
            else: partition_between[-1] -= 1   #partition too big, so make it smaller
        else:   #the worst partition is in the middle somewhere
            left_bound = worst_partition_index - 1   #the divider before the partition
            right_bound = worst_partition_index   #the divider after the partition
            if worst_height_diff < 0:   #partition too big, so make it smaller
                if sum(partitions[worst_partition_index-1]) > sum(partitions[worst_partition_index+1]):   #the partition on the left is bigger than the one on the right, so make the one on the right bigger
                    partition_between[right_bound] -= 1
                else:   #the partition on the left is smaller than the one on the right, so make the one on the left bigger
                    partition_between[left_bound] += 1
            else:   #partition too small, make it bigger
                if sum(partitions[worst_partition_index-1]) > sum(partitions[worst_partition_index+1]): #the partition on the left is bigger than the one on the right, so make the one on the left smaller
                    partition_between[left_bound] -= 1
                else:   #the partition on the left is smaller than the one on the right, so make the one on the right smaller
                    partition_between[right_bound] += 1

def print_best_partition(a, k):
    #simple function to partition a list and print info
    print '    Partitioning {0} into {1} partitions'.format(a, k)
    p = partition_list(a, k)
    print '    The best partitioning is {0}\n    With heights {1}\n'.format(p, map(sum, p))

#tests
a = [1, 6, 2, 3, 4, 1, 7, 6, 4]
print_best_partition(a, 1)
print_best_partition(a, 2)
print_best_partition(a, 3)
print_best_partition(a, 4)
print_best_partition(a, 5)

b = [1, 10, 10, 1]
print_best_partition(b, 2)

import random
c = [random.randint(0,20) for x in range(100)]
print_best_partition(c, 10)

d = [95, 15, 75, 25, 85, 5]
print_best_partition(d, 3)

rawDescription: Split a list of numbers into n chunks such that the chunks have (close to) equal sums and keep the original order


code:
for item in items:
    result = item.xpath('following-sibling::text()[normalize-space()][preceding-sibling::b[1] = $b]', b=item)
    print [r.strip() for r in result]

rawDescription: HTML parsing with lxml, python, .tail being broken up by <br> tags


code:
filepathsUmlauts = []
filepathsUmlauts.append(1)
filepathsUmlauts
x = filepathsUmlauts.append(2)
x
print x
filepathsUmlauts

rawDescription: Python 2.7 - Adding unicode strings to list


code:
j = json.loads(json_source)
print "table name:", j['table']
for col in j['columns']:
    print "column name:", col['name']
    print "source type:", col['source_type']
    print "source col:",  col['source_col']

rawDescription: Using an xml "map" to import data to MySQL via python?


code:
print mnb.feature_count_
print mnb.coef_[0]

rawDescription: How to get most informative features for scikit-learn classifier for different class?

description: Get most informative features for scikit-learn classifier for different class


code:
class Foo(object):
  def bar(self):
    print self.baz
f=Foo()
f.baz = 'quux'
f.bar()
Foo.bar(f)

rawDescription: Types and functions with same name in Python 3.X?


code:
print 'a', 'b', 'c'
print 'a',
print 'b',
print 'c'
print 'a'
print 'b'
print 'c'

rawDescription: Why use a comma after a print?

description: Why use a comma after a print


code:
iterable = 'the quick brown fox jumps over the lazy dog'
chunk_size = [1, 2, 3, 4, 5, 6]
for item in uneven_chunker(iterable, chunk_size):
    print ''.join(item)

rawDescription: Uneven chunking in python

description: Uneven chunking in python


code:
import pandas as pd
data = pd.DataFrame({'T': ['A', 'B', 'C', 'D', 'E']})
res = pd.get_dummies(data)
res.to_csv('output.csv')
print res

rawDescription: Converting categorical values to binary using pandas


code:
source
from collections import defaultdict
import pandas as pd

df = pd.DataFrame(["2014-01-01","2013-01-01","2014-02-02", "2012-08-09"])
# df = df.values.flatten().tolist()

dindex = defaultdict(list)
for index,dateval in enumerate(df.values):
    year = dateval[0].split('-')[0]
    dindex[year].append(index)

assert dindex == {'2014': [0, 2], '2013': [1], '2012': [3]}
print dindex

rawDescription: Defining lists based on indices of pandas dataframe


code:
text = """
Now I will a rhyme construct
By chosen words the young instruct
Cunningly ensured endeavour
Con it and remember ever
Widths of circle here you see
Stretched out in strange obscurity
"""
pattern = ("falafel", "ensured", "pizza", "strange")

text1=text.split()
pattern1=list(pattern)

print text1
for q in range(0,len(text1)):
    for r in range(0,len(pattern1)):
        if text1[q]==pattern1[r]:
            print q

rawDescription: How to return just the index of element in one list while comparing two lists in python

description: Return just the index of element in one list while comparing two lists in python


code:
def print_template(a,b):
    c="the c"
    template="{a} {b} {c}"
    print template.format(**vars())

rawDescription: what is most concise way to transfer variables to python string.format?

description: What is most concise way to transfer variables to python string.format


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
from matplotlib.patches import Rectangle

# Generate dummy data.
a = np.random.random(75)
b = np.random.random(75) - 0.6
c = np.random.random(75) + 0.75

# Collate into a DataFrame
df = pd.DataFrame({'a': a, 'b': b, 'c': c})
df.columns = [list(['WT', 'MUT', 'WTxMUT']), list(['Parent', 'Parent', 'Offspring'])]
df.columns.names = ['Genotype', 'Status']
df_melt = pd.melt(df)

ax = sb.swarmplot(data = df_melt, x = "Status", y = "value", hue = "Genotype")

def getdatalim(coll):
    x,y = np.array(coll.get_offsets()).T
    try:
        print 'xmin={}, xmax={}, ymin={}, ymax={}'.format(
                x.min(), x.max(), y.min(), y.max())
        rect = Rectangle((x.min(),y.min()),x.ptp(),y.ptp(),edgecolor='k',facecolor='None',lw=3)
        ax.add_patch(rect)
    except ValueError:
        pass

getdatalim(ax.collections[0]) # "Parent"
getdatalim(ax.collections[1]) # "Offspring"

plt.show()

rawDescription: Obtaining span of plotted points from seaborn swarmplot


code:
keyword = 'gcse'
message = 'python'
n, m = len(keyword), len(message)
print ''.join( [ keyword[ i % n ]  for i in range(m) ] )

rawDescription: How can I get an alphabetic input to match another alphabetic input in length?

description: Get an alphabetic input to match another alphabetic input in length


code:
import zipfile

zf = zipfile.ZipFile('test.zip')

uncompress_size = sum((file.file_size for file in zf.infolist()))

extracted_size = 0

for file in zf.infolist():
    extracted_size += file.file_size
    print "%s %%" % (extracted_size * 100/uncompress_size)
    zf.extract(file)

rawDescription: Monitor ZIP File Extraction Python

description: Monitor ZIP File Extraction Python


code:
import sleekxmpp
from ConfigParser import ConfigParser

class StatusWatcher(sleekxmpp.ClientXMPP):
    def __init__(self, jid_to_watch):
        self._jid_to_watch = jid_to_watch
        config = ConfigParser()
        config.read("config.ini")
        jid = config.get("general", "jid")
        resource = config.get("general", "resource")
        password = config.get("general", "password")
        sleekxmpp.ClientXMPP.__init__(self, jid + "/" + resource, password)

        self.add_event_handler("session_start", self.handle_XMPP_connected)
        self.add_event_handler("changed_status", self.handle_changed_status)

    def handle_XMPP_connected(self, event):
        print "connected"
        self.sendPresence(pstatus="I'm just a Bot.")
        self.get_roster()

    def handle_changed_status(self, pres):
        if pres['from'].bare == self._jid_to_watch:
            print pres['status']

xmpp = StatusWatcher("login@gmail.com") # The account to monitor
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
if xmpp.connect():
    xmpp.process(threaded=False)

rawDescription: How do I monitor the change of my gtalk status message?

description: Monitor the change of my gtalk status message


code:
for line in f.read().split('\0'):
    print line

rawDescription: Python - how to read file with NUL delimited lines?


code:
import wx
from wx.lib.scrolledpanel import ScrolledPanel

rev1 = {"A": "a", "B": "b", "C": "c"}
rev2 = {"A": "d", "B": "e", "C": "f"}
rev3 = {"A": "g", "B": "h", "C": "i"}

RevHist = {"1":rev1, "2":rev2, "3":rev3}

class TestGui(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Hey, a GUI!", size=(400,400))
        self.panel = ScrolledPanel(parent=self, id=-1)

        self.revsList = sorted(RevHist.keys())
        self.CRDict = rev3

        self.CreateGui()
        self.revDrop.SetValue("3")

    def CreateGui(self):
        crrev = wx.StaticText(self.panel, -1, "Revision:")
        self.revDrop = wx.ComboBox(self.panel, choices=self.revsList, style = wx.CB_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.OnRevDrop, self.revDrop)

        hboxRev = wx.BoxSizer(wx.HORIZONTAL)
        hboxRev.Add((20,20), 1)
        hboxRev.Add(crrev)
        hboxRev.Add((0,0), 1)
        hboxRev.Add(self.revDrop)
        hboxRev.Add((20,20), 1)

        sbox1 = wx.StaticBox(self.panel, wx.ID_ANY, u"Here's where the information goes")
        sbox1.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.staticbox1 = wx.StaticBoxSizer(sbox1, wx.VERTICAL)

        self.infoA = wx.StaticText(self.panel, -1, "A: {0}".format(self.CRDict["A"]))
        self.infoB = wx.StaticText(self.panel, -1, "B: {0}".format(self.CRDict["B"]))
        self.infoC = wx.StaticText(self.panel, -1, "C: {0}".format(self.CRDict["C"]))

        self.staticbox1.Add(self.infoA, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=10)
        self.staticbox1.Add(self.infoB, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=10)
        self.staticbox1.Add(self.infoC, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=10)

        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(hboxRev, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=10)
        self.vbox.Add(self.staticbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=10)
        self.panel.SetSizer(self.vbox)
        self.panel.Layout()
    def UpdateValues(self,valueDict):
        for k,v in valueDict.items():
             if hasattr(self,"info{0}".format(k)):
                  getattr(self,"info{0}".format(k)).SetLabel(v)
    def OnRevDrop(self, event):
        event.Skip()
        rev = self.revDrop.GetValue()
        print rev
        self.CRDict = RevHist[rev]

        self.UpdateValues(self.CRDict )

app = wx.PySimpleApp()
gui = TestGui()
gui.Show()
app.MainLoop()

rawDescription: WxPython Panel Refresh

description: WxPython Panel Refresh


code:
# In each row 1st element is the event, the rest are gage values
l = [[1, 1.1, 2.2, 3.3, 4.4],
     [2, 5.4, 3.2, 4.2, 1.1],
     [3, 1.0, 2.0, 3.0]]

for line in l:
    print line[0],  max(line[1::])

rawDescription: max value in Python

description: Max value in Python


code:
numbers = []

def loop_function(numbers):
    x = 6
    i = 0
    while i < x:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d\n" % i

    return numbers

loop_function(numbers)
print "The numbers: "

for num in numbers:
    print num

rawDescription: Placing a While-loop Inside a Function

description: Placing a While-loop Inside a Function


code:
response = urllib.urlopen(URL + "?%s" % parameter)
print response.read()

rawDescription: send xml file to http using python

description: Send xml file to http using python


code:
from bs4 import BeautifulSoup
import requests
r = requests.get('http://en.wikipedia.org/wiki/Animal_House_(U.D.O._album)')
soup = BeautifulSoup(r.content)
covers = soup.select('table.infobox a.image img[src]')
for cover in covers:
    print cover['src']

rawDescription: Getting a particular image from Wikipedia with BeautifulSoup


code:
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
               'localhost'))

# Create normal 'Hello World' type channel.
channel = connection.channel()
channel.confirm_delivery()
channel.queue_declare(queue='hello', durable=True)

# We need to bind this channel to an exchange, that will be used to transfer
# messages from our delay queue.
channel.queue_bind(exchange='amq.direct',
                   queue='hello')

# Create our delay channel.
delay_channel = connection.channel()
delay_channel.confirm_delivery()

# This is where we declare the delay, and routing for our delay channel.
delay_channel.queue_declare(queue='hello_delay', durable=True,  arguments={
  'x-message-ttl' : 5000, # Delay until the message is transferred in milliseconds.
  'x-dead-letter-exchange' : 'amq.direct', # Exchange used to transfer the message from A to B.
  'x-dead-letter-routing-key' : 'hello' # Name of the queue we want the message transferred to.
})

delay_channel.basic_publish(exchange='',
                      routing_key='hello_delay',
                      body="test",
                      properties=pika.BasicProperties(delivery_mode=2))

print " [x] Sent"

rawDescription: How to create a delayed queue in RabbitMQ?

description: Create a delayed queue in RabbitMQ


code:
import sys
import ConfigParser

if __name__ == '__main__':
    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])
    print config['settings']['host']
    print config['settings']['port']

rawDescription: python script command line arguments from file

description: Python script command line arguments from file


code:
import threading
import time

class DecoratorClass(object):
    def __init__(self):
        self.thread = None

    def __call__(self, func, *args, **kwargs):
        def wrapped_func(*args, **kwargs):
            curr_thread = threading.currentThread().getName()
            self.thread = curr_thread
            print '\nthread name before running func:', self.thread
            ret_val = func()
            print '\nthread name after running func:', self.thread
            return ret_val

        return wrapped_func

@DecoratorClass()
def decorated_with_class():
    print 'running decorated w class'
    time.sleep(1)
    return

threads = []
for i in range(5):
    t = threading.Thread(target=decorated_with_class)
    threads.append(t)
    t.start()

rawDescription: creating a thread safe decorator class

description: Creating a thread safe decorator class


code: print "\t".join(two_word_sets)

rawDescription: Python - print tab delimited two-word set


code:
# wait 30 seconds for the thread to finish its work
t.join(30)
if t.is_alive():
    print "thread is not done, setting event to kill thread."
    e.set()
    # The thread can still be running at this point. For example, if the
    # thread's call to isSet() returns right before this call to set(), then
    # the thread will still perform the full 1 second sleep and the rest of
    # the loop before finally stopping.
else:
    print "thread has already finished."

# Thread can still be alive at this point. Do another join without a timeout
# to verify thread shutdown.
t.join()

rawDescription: Most Pythonic way to kill a thread after some period of time


code:
from itertools import combinations

def check_reversed(x, y):
    number = str(x * y)
    return number == number[::-1]

x, y = max((c for c in combinations(range(100, 1000), r=2) if check_reversed(*c)),
           key=lambda c: c[0] * c[1])
print x, y, x * y

rawDescription: Loop ends with no reason

description: Loop ends with no reason


code:
with open('data.txt') as inf:
    yline = []
    for line in inf:
        line = line.split()
        x = int(line[0])
        yline = '+'.join(yline + [(line[1])])
        print x, yline
        yline = [yline]

rawDescription: the sum of values of a second column of a file

description: The sum of values of a second column of a file


code:
sshChild.sendline(cmdrun + '\r')
child.expect(pexpect.EOF, timeout=20)
print child.before, child.after

rawDescription: pexpect: Retrieve log from command run over ssh tunnel

description: Pexpect: Retrieve log from command run over ssh tunnel


code:
words = None
with open('data.txt') as f:
    words = f.read().split()
total_words = len(words)
print 'Total words:', total_words

in_para = False
para_count = 0
para_type = None
paragraph = list()
for word in words:
  if ('P1' in word or
      'P2' in word or
      'P3' in word ):
      if in_para == False:
         in_para = True
         para_type = word
      else:
         print 'Words in paragraph', para_type, ':', para_count
         print ' '.join(paragraph)
         para_count = 0
         del paragraph[:]
         para_type = word
  else:
    paragraph.append(word)
    para_count += 1
else:
  if in_para == True:
    print 'Words in last paragraph', para_type, ':', para_count
    print ' '.join(paragraph)
  else:
    print 'No words'

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

rawDescription: Convert a python 'type' object to a string


code:
import re
import sys

samp='''S
=NP
==(DT +def) the
== (N +ani) man
=VP
==V walks'''.splitlines()

relinelev = re.compile(r'(=*)(.*)')
reclean = re.compile(r'\s*\((\S+)[^)]*\)')

def clean(line):
  return reclean.sub(r'\1', line)

def reparse(tree=samp):
  stack = [-1]
  for line in tree:
    equals, rest = relinelev.match(line).groups()
    linelev = len(equals)
    while linelev < stack[-1]:
      sys.stdout.softspace = False
      print ')',
      curlev = stack.pop()
    if linelev == stack[-1]:
      sys.stdout.softspace = False
      print ')',
    else:
      stack.append(linelev)
    print '(%s' % clean(rest),
  while stack[-1] >= 0:
    sys.stdout.softspace = False
    print ')',
    stack.pop()
  print

reparse()

rawDescription: converting a treebank of vertical trees to s-expressions

description: Converting a treebank of vertical trees to s-expressions


code:
def sumColumn(arr3d, index):
    sum = 0
    for arr in arr3d:
        for arr2 in arr:
            sum+=float(arr2[index])
    return sum

#now print the sum of the first column using the initial data file.
print sumColumn(ret, 0)    # the columns are 0 indexed, so 0 is the first column

rawDescription: reading data file into multidimensional array in python

description: Reading data file into multidimensional array in python


code:
from collections import Counter
with open('file.txt', 'r') as fd:
    lines = fd.read().split()
    counter = Counter(lines)
    # sorts items
    items = sorted(counter.items(), key=lambda x: int(x[0]))
    # prints desired output
    for k, repetitions in items:
        print k,'\t', repetitions

rawDescription: How to count the frequency of numbers given in a text file

description: Count the frequency of numbers given in a text file


code:
from ctypes import CDLL, POINTER, c_int, c_float
import numpy as np
import time

fortran = CDLL('./elementwise.so')
fortran.elementwise.argtypes = [ POINTER(c_float),
                                 POINTER(c_float),
                                 POINTER(c_float),
                                 POINTER(c_int),
                                 POINTER(c_int) ]

# Setup
M=10
N=5000000

a = np.empty((M,N), dtype=c_float)
b = np.empty((M,N), dtype=c_float)
c = np.empty((M,N), dtype=c_float)

a[:] = np.random.rand(M,N)
b[:] = np.random.rand(M,N)

# Fortran call
start = time.time()
fortran.elementwise( a.ctypes.data_as(POINTER(c_float)),
                     b.ctypes.data_as(POINTER(c_float)),
                     c.ctypes.data_as(POINTER(c_float)),
                     c_int(M), c_int(N) )
stop = time.time()
print 'Fortran took ',stop - start,'seconds'

# Numpy
start = time.time()
c = np.multiply(a,b)
stop = time.time()
print 'Numpy took ',stop - start,'seconds'

rawDescription: Speeding up element-wise array multiplication in python


code:
import pulp

dist = {("A", "B"): 1.0,
        ("B", "C"): 1.0,
        ("D", "E"): 3.0}
trains = [("A", "B", 1.0, 2.0),
          ("B", "C", 2.0, 3.0),
          ("C", "B", 3.5, 4.5),
          ("B", "A", 4.5, 5.5),
          ("D", "E", 1.0, 5.5)]
sources = set(list([t[0] for t in trains]))

x = pulp.LpVariable.dicts("x", trains, lowBound=0, upBound=1, cat=pulp.LpInteger)
y = pulp.LpVariable.dicts("y", dist.keys(), lowBound=0, upBound=1, cat=pulp.LpInteger)
s = pulp.LpVariable.dicts("s", sources, lowBound=0, upBound=1, cat=pulp.LpInteger)
mod = pulp.LpProblem("Train Optimization", pulp.LpMaximize)

# Objective
mod += sum([dist[k] * y[k] for k in dist])

# Feasibility
for t in trains:
    mod += x[t] <= s[t[0]] + sum([x[k] for k in trains if k[1] == t[0] and k[3] <= t[2]]) - sum([x[k] for k in trains if k != t and k[0] == t[0] and k[2] <= t[2]])
mod += sum([s[k] for k in sources]) == 1

# Valid y variables
for k in dist:
    mod += y[k] <= sum([x[t] for t in trains if (t[0] == k[0] and t[1] == k[1]) or (t[1] == k[0] and t[0] == k[1])])

# Solve
mod.solve()
for t in trains:
    print "Trip", t, "used:", x[t].value()

rawDescription: Graph with distance and travelling times: find most km's in 24 hours (with constraints)


rawDescription: Variable always gets rounded to 2 decimal places - Python


code:
from whoosh.qparser import QueryParser, FuzzyTermPlugin, PhrasePlugin, SequencePlugin

with ix.searcher() as searcher:
    parser = QueryParser(u"content", ix.schema)
    parser.add_plugin(FuzzyTermPlugin())
    parser.remove_plugin_class(PhrasePlugin)
    parser.add_plugin(SequencePlugin())
    query = parser.parse(u"\"letter~2 stamp~2 mail~2\"~10")
    results = searcher.search(query)
    print "nb of results =", len(results)
    for r in results:
        print r

rawDescription: python fuzzy text search

description: Python fuzzy text search


code:
for i in [0,2,4]:
    if i%2==0:
        print i
        break
else:
    print "There are no EVEN #s"

rawDescription: Python For If Else

description: Python For If Else


code:
def countpos(lsts):
     count = 0
     for lst in lsts:
         for val in lst:
             if val > 0:
                 count += 1
     return count

print countpos([[0, 0, 0, 0], [1, 0, 6, 0]])  # 2

rawDescription: how to count a list within a function

description: Count a list within a function


code:
print logIt('example text')
print logIt('example "quoted" text')

rawDescription: Escaping JavaScript Strings in Python

description: Escaping JavaScript Strings in Python


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
import os

server = SimpleXMLRPCServer(('localhost', 9000))

def list_contents(dir_name):
    return os.listdir(dir_name)
for name, val in os.__dict__.items():
    if callable(val):
        print "Registering " +  name
        server.register_function(val, name)

try:
    print 'Use Control-C to exit'
    server.serve_forever()
except KeyboardInterrupt:
    print 'Exiting'

rawDescription: xmlrpcserver implementation in python capable of registering an entire module?

description: Xmlrpcserver implementation in python capable of registering an entire module


rawDescription: For loop troubleshooting

description: For loop troubleshooting


code:
import re

a="The_Birds_1963_HDTV_XvidHD_720p-NPW.avi"
b="Seven_Pounds_(BDrip_1080p_ENG-ITA-GER)_Multisub_x264_bluray_.mkv"
c="1892.XVID.AC3.HD.120_min.avi"

def cleanit(str):
    result = []
    l = re.split('[_.]',str)
    flag = 0
    if re.match('^[a-zA-z]+',l[0]):
        flag = 1
    elif re.match('^[0-9]+',l[0]):
        flag = 2

    if flag == 1:
        for x in l:
            if not re.match('^[a-zA-Z]+',x):
                break;
            result.append(x)
        return " ".join(result)

    if flag == 2:
        for x in l:
            if not re.match('^[0-9]+',x):
                break;
            result.append(x)
        return " ".join(result)

if __name__ == '__main__':
    print cleanit(a)
    print cleanit(b)
    print cleanit(c)

rawDescription: Python String Cleaning

description: Python String Cleaning


code:
import xml.etree.ElementTree as ET

data = """<parameters>
<parameter>
 <name>ec_num</name>
 <value>none</value>
 <units/>
 <url/>
 <id>2455</id>
 <m_date>2008-11-29 13:15:14</m_date>
 <user_id>24</user_id>
 <user_name>registry</user_name>
</parameter>
<parameter>
 <name>swisspro</name>
 <value>Q8H6N2</value>
 <units/>
</parameter>
</parameters>"""

tree = ET.fromstring(data)

for parameter in tree.iter(tag='parameter'):
    name = parameter.find('name')
    if name is not None and name.text == 'swisspro':
        print parameter.find('value').text
        break

rawDescription: Parsing XML with ElementTree in Python

description: Parsing XML with ElementTree in Python


code:
import json
decoder = json.JSONDecoder()
json_example = '{"item_one" : "Spam", "item_two" : "Eggs"}'
template = 'Item 1: {item_one}\nItem 2: {item_two}'
print template.format(**decoder.decode(json_example))

rawDescription: Convert JSON to .ics (Python)

description: Convert JSON to .ics (Python)


code:
letters = [chr(i) for i in range(97,97+26)]
print letters
max = 300

def searchWord(orig,word, curindex,counter):
    if counter>max: return

    if counter==0:
        s = letters[0] + word[1:]
        searchWord(orig,s,0,counter+1)
    else:
        c = word[curindex]

        print 'checking ',word,curindex
        s = word
        i = letters.index(c)

        if i==len(letters)-1 and curindex==len(orig)-1:
            print 'done'
            return

        if i==len(letters)-1:
            print 'end of letters reached'
            print 'curindex',curindex
            s = list(word)
            s[curindex] = list(orig)[curindex]
            s[curindex+1] = letters[0]
            s[1] = letters[0]
            s = ''.join(s)
            searchWord(orig,s,curindex+1,counter+1)

        else:
            s = list(word)
            try:
                s[curindex] = letters[i+1]
            except:
                print '?? ',s,curindex,letters[i]

            s = ''.join(s)
            searchWord(orig,s ,curindex,counter+1)

searchWord("weke","weke",0,0)

rawDescription: Trie Backtracking in Recursion

description: Trie Backtracking in Recursion


code:
import re

mystring = """
DEALER: 'S up, Bubbless?
BUBBLES: Hey.
DEALER: Well, there you go.
JUNKIE: Well, what you got?
DEALER: I got some starters. """

p = re.compile('([A-Z]*):')
s = set(p.findall(mystring))

print s

rawDescription: Get specific words in a string

description: Get specific words in a string


code:
import os.path
while True:
    username = raw_input('What would you like your username to be?  ')
    if os.path.exists("%s.p" % username):
        print 'The username "%s" is not available. Please try a different one.' % (username,)
        continue
    username2 = raw_input('Please enter the same username again: ')
    if username == username2:
        break
    else:
        print "The usernames don't match.  Try again."

while True:
    pword = raw_input('What would you like your password to be?  ')
    pword2 = raw_input('Please enter the same password again: ')
    if pword == pword2:
        break
    else:
        print 'The passwords do not match. Try again.'

money_left = 0
isguest = False
print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)

rawDescription: Why is it continuing to repeat the while True even though I have broken it?


code:
result = lineExpr.parseString(test)
print result.keyword
print result.data

rawDescription: pyparsing: Nested countedArray?

description: Pyparsing: Nested countedArray


code:
for frame in quantize(25, 10):
    print frame

rawDescription: bash evenly choose 10 numbers

description: Bash evenly choose 10 numbers


code:
@my_other_decorator # another decorator following the same pattern
@my_decorator
def foo(args):
    print args

foo.decorated(args) # calls the function with the inner decorated function (my_decorator)
foo.decorated.decorated(args) # original function

rawDescription: Is it possible to use reflection to examine a function's decorators in Python 2.5?


code:
import pandas as pd

result = { 'meta': {'some': 'meta info'} }

df = pd.DataFrame([[1,2,3], [.1,.2,.3]], columns=('a','b','c'))

#result['extra_data'] = df.to_dict() # as dictonary

result['extra_data'] = df

print pd.json.dumps( result )

rawDescription: Combine DataFrame as JSON with additional data


code: print my_dictionary['url1']

rawDescription: How to capture iterated output variable into list for analysis

description: Capture iterated output variable into list for analysis


code:
from collections import defaultdict
from operator import itemgetter

# dictionaries for keeping track of the counts
pos_dict = defaultdict(int)
neg_dict = defaultdict(int)

for r in trainingTexts:
  rating = r.rating
  freq = r.freq_dist

  # choose the appropriate counts dict
  if rating > 0:
    partition = pos_dict
  elif rating < 0:
    partition = neg_dict
  else:
    continue

  # add the information to the correct counts dict
  for word,count in freq.iteritems():
    partition[word] += count

# Turn the counts dictionaries into lists of descending-frequency words
def only_list(counts, filtered):
  return sorted(filter(lambda (w,c): w not in filtered, counts.items()), \
                key=itemgetter(1), \
                reverse=True)

only_positive_words = only_list(pos_dict, neg_dict)
only_negative_words = only_list(neg_dict, pos_dict)

rawDescription: Separating nltk.FreqDist words into two lists?


code:
row = [1, "a", "the big bad, string"]
print ','.join('"%s"'%i for i in row)

rawDescription: How to escape comma in string Python 2.7 in a .csv file

description: Escape comma in string Python 2.7 in a .csv file


code:
import urllib

params = {title:"foo",text:"baz and spam and eggs"}

print """
POST /add HTTP/1.1
Content-type:application/x-http-form-urlencoded

""",urlencode(params)

rawDescription: Run python script with telnet

description: Run python script with telnet


code:
s = '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'
us = s.decode('utf-8')
print us

rawDescription: Working with unicode in python

description: Working with unicode in python


code:
for line in inputfile:
  line = line.strip() #remove whitespace before and after
  if line[0:6] == 'DeltaE':
    #then we have a line like: DeltaE =    13.5423 | TDMI^2 = 0.6670E-01, Intensity =  6553.
    deltae = float(line.split('|')[0].strip().split('=')[1].strip())
    intensity = float(line.split('|')[1].strip().split(',')[1].strip().split('=')[1].strip())

    print deltae, ',', intensity

rawDescription: How to read specific line in python and print data to text file or console window?

description: Read specific line in python and print data to text file or console window


rawDescription: How to print the sign + of a digit for positive numbers in Python

description: Print the sign + of a digit for positive numbers in Python


code:
di = DecimalIndexing(31415927)
for i in xrange(len(di)):
    if di[i:i+4] == [9,5,1,4]:
        print "found"

rawDescription: Find sequences of digits in long integers efficiently


code:
from bottle import template
t = """

%for key, value in wordList.iteritems():

        {{key}}
        {{value}}

%end

"""
print template(t, wordList={'hello': 1, 'hi': 2, 'go': 3})

rawDescription: How do I return a Python bottle template that prints out key-value pairs from a dictionary?

description: Return a Python bottle template that prints out key-value pairs from a dictionary


code:
test = """
...... A
B .......
B .......
...... A
B .......
B ......."""

from pyparsing import Literal, Word, printables, Group, OneOrMore

A = Literal("A")
B = Literal("B")

notAorB = Word(printables, excludeChars="AB")

parser = OneOrMore(Group(A + Group(OneOrMore(B))))
parser.ignore(notAorB)

print parser.parseString(test).asList()

rawDescription: python pyparsing string: A,b,b,b,A,b,b,b*

description: Python pyparsing string: A,b,b,b,A,b,b,b*


code:
import json
import urllib2

def get_geonames(lat, lng, types):
    url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
            '?latlng={},{}&sensor=false'.format(lat, lng)
    jsondata = json.load(urllib2.urlopen(url))
    address_comps = jsondata['results'][0]['address_components']
    filter_method = lambda x: len(set(x['types']).intersection(types))
    return filter(filter_method, address_comps)

lat, lng = 59.3, 18.1
types = ['locality', 'administrative_area_level_1']

# Display all geographical names along with their types
for geoname in get_geonames(lat, lng, types):
    common_types = set(geoname['types']).intersection(set(types))
    print '{} ({})'.format(geoname['long_name'], ', '.join(common_types))

rawDescription: How to reverse geocode serverside with python, json and google maps?

description: Reverse geocode serverside with python, json and google maps


rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code:
import re

pattern = re.compile(r'^(?:[^"/\\]|\"(?:[^\"\\]|\\.)*\"|/(?:[^/"\\]|\\.)|/\"(?:[^\"\\]|\\.)*\"|\\.)*//(.*)$')

tests = [
    (r'// hello world', True),
    (r'     // hello world', True),
    (r'hello world', False),
    (r'System.out.println("Hello, World!\n"); // prints hello world', True),
    (r'String url = "http://www.example.com"', False),
    (r'// hello world', True),
    (r'//\\', True),
    (r'// "some comment"', True),
    (r'new URI("http://www.google.com")', False),
    (r'System.out.println("Escaped quote\""); // Comment', True)
]

tests_passed = 0

for test in tests:
    match = pattern.match(test[0])
    has_comment = match != None
    if has_comment == test[1]:
        tests_passed += 1

print "Passed {0}/{1} tests".format(tests_passed, len(tests))

rawDescription: Regular Expression for single line comments


code:
import csv

with open(r"c:\testing.csv", "rb") as infh:
    reader = csv.reader(infh)
    next(reader, None)   # skip first row
    row = next(reader)
    if row[1] == 'A1' and row[2] == 'CLIENT':
        print "yes"

rawDescription: Reading Cell from CSV, trying to truncate the code


code:
a = {'a':24, 'e':30, 't':12, 'n':10}
x = 11

def big_keys(dictionary, value):
  big_keys_list = []
  for k, v in dictionary.iteritems(): #iterating the dict items
    if v > value: # checking the condition
      big_keys_list.append(k) #append to list if meets the rule
  return big_keys_list

print big_keys(a, x) # ['a', 'e', 't']

rawDescription: hints and stepping stone on how to tackle this

description: Hints and stepping stone on how to tackle this


code:
import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument("--file", required=True, help="Video file to upload")
argparser.add_argument("--title", help="Video title", default="Test Title")
argparser.add_argument("--description", help="Video description",
    default="Test Description")
argparser.add_argument("--category", default="22",
    help="Numeric video category. " +
        "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
argparser.add_argument("--keywords", help="Video keywords, comma separated",
    default="")
VALID_PRIVACY_STATUSES = ("private","public")
argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
    default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")

#pass in any positional or required variables.. as strings in a list
#which corresponds to sys.argv[1:].  Not a string => arcane errors.
args = argparser.parse_args(["--file", "myfile.avi"])

#you can populate other optional parameters, not just positionals/required
#args = argparser.parse_args(["--file", "myfile.avi", "--title", "my title"])

print vars(args)

#modify them as you see fit, but no more validation is taking place
#so best to use parse_args.
args.privacyStatus = "some status not in choices - already parsed"
args.category = 42

print vars(args)

#proceed as before, the system doesn't care if it came from the command line or not
# youtube = get_authenticated_service(args)

rawDescription: python argparse - pass values WITHOUT command line

description: Python argparse - pass values WITHOUT command line


code:
import tempfile
import subprocess

w = tempfile.NamedTemporaryFile()
p = subprocess.Popen('third_party.exe', shell=True, stdout=w,
                        stderr=subprocess.STDOUT, bufsize=0)

with open(w.name, 'r') as r:
    for line in r:
        print line
w.close()

rawDescription: Python subprocess output on windows?

description: Python subprocess output on windows


code:
for item in itertools.product([0, 1], repeat=14):
    print item

rawDescription: All combinations fourteen item array

description: All combinations fourteen item array


code:
def getRank(item_url):
    href = item_url[:37]+"page=weekend&" + item_url[37:]
    response = requests.get(href)
    print response.status_code, "for", href
    soup = BeautifulSoup(response.content)  # or BeautifulSoup(response.content, "html5lib")

    rows = soup.select('.chart-wide tr')

    header_skipped = False
    for row in rows:
        if not header_skipped:
            header_skipped = True
            continue

        headers = "Date Rank WeekendGross Change Theaters Change/Avg GrossToDate Week".split()

        for header, child in zip(headers, row.children):
            print header, ":", child.text

rawDescription: Python BeautifulSoup webcrawling: Getting text that doesn't have links or class tags


code:
nums=[]
words=[]
for e in tgt.split():
    try:
        nums.append(float(e))
    except ValueError:
        words.append(e)

print words,nums

rawDescription: How do you split a string into quoted sentence and numbers using python

description: Split a string into quoted sentence and numbers using python


code:
import sys
from inspect import getframeinfo

def multiply(X, Y):
    print getframeinfo(sys._getframe(1))

def trace(Z):
    pass

def multiply_then_trace(X, Y):
    Z = multiply(X, Y)
    return trace(Z)

if __name__ == '__main__':
    A = [[1, 1], [1, 1]]
    B = [[2, 2], [2, 2]]
    multiply_then_trace(A, B)

rawDescription: Cleanest way to compute less in a function by implicitly knowing what the callback / caller function is in Python?


code:
a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

rawDescription: Python string to unicode

description: Python string to unicode


code:
import numpy as np

class DynamicRecArray(object):
    def __init__(self, dtype):
        self.dtype = np.dtype(dtype)
        self.length = 0
        self.size = 10
        self._data = np.empty(self.size, dtype=self.dtype)

    def __len__(self):
        return self.length

    def append(self, rec):
        if self.length == self.size:
            self.size = int(1.5*self.size)
            self._data = np.resize(self._data, self.size)
        self._data[self.length] = rec
        self.length += 1

    def extend(self, recs):
        for rec in recs:
            self.append(rec)

    @property
    def data(self):
        return self._data[:self.length]

y = DynamicRecArray(('a4,int32,float64'))
y.extend([("xyz", 12, 3.2), ("abc", 100, 0.2)])
y.append(("123", 1000, 0))
print y.data
for i in xrange(100):
    y.append((str(i), i, i+0.1))

rawDescription: Adding records to a numpy record array

description: Adding records to a numpy record array


code:
import numpy as np
import scipy.ndimage

x = np.arange(9).reshape(3,3)

print 'Original array:'
print x

print 'Resampled by a factor of 2 with nearest interpolation:'
print scipy.ndimage.zoom(x, 2, order=0)

print 'Resampled by a factor of 2 with bilinear interpolation:'
print scipy.ndimage.zoom(x, 2, order=1)

print 'Resampled by a factor of 2 with cubic interpolation:'
print scipy.ndimage.zoom(x, 2, order=3)

rawDescription: Resampling a numpy array representing an image


rawDescription: understanding python variable assignment

description: Understanding python variable assignment


code:
import pyximport
pyximport.install()
import test_mod

a = test_mod.func()
print type(a) # <type 'numpy.float32'>

rawDescription: Can I create a PyObject* (numpy.float32)

description: Create a PyObject* (numpy.float32)


code:
base_url =  'https://hacker-news.firebaseio.com/v0/item/{}.json?print=pretty'
top_story_ids = json.loads(html)
for story in top_story_ids:
    response = urllib2.urlopen(base_url.format(story))
    print response.read()

rawDescription: How to use Hacker News API in Python?

description: Use Hacker News API in Python


rawDescription: numpy: how to fill multiple fields in a structured array at once

description: Numpy: how to fill multiple fields in a structured array at once


code: print set(a) & set(b)

rawDescription: Finding a substring within a string using an array?


code:
from lxml import objectify, etree
embossed = objectify.Element('embossed')
embossed.append(objectify.Element('line'))
embossed.line[-1] = 'Test Line'
embossed.append(objectify.Element('line'))
embossed.line[-1] = 'Test Line 2'
print etree.tostring(embossed, pretty_print=True)

rawDescription: How to create the same XML element 3 times with Python LXML Objectify

description: Create the same XML element 3 times with Python LXML Objectify


code:
def pattern_writer(pattern_size):
    first_x = 0
    last_x = pattern_size - 1
    while first_x < pattern_size and last_x > -1:
        for t in range(pattern_size):
            if t == first_x or t == last_x:
                print "x",
            else:
                print ".",
        print "\n"
        first_x += 1
        last_x -= 1

rawDescription: X pattern in python 3.2

description: X pattern in python 3.2


code:
# coherence
cxy, fcoh = cohere(s1, s2, nfft, 1./dt)

# calculate 95% confidence level
edof = (len(s1)/(nfft/2)) * cxy.mean() # equivalent degrees of freedom: (length(timeseries)/windowhalfwidth)*mean_coherence
gamma95 = 1.-(0.05)**(1./(edof-1.))
conf95 = np.where(cxy>gamma95)
print 'gamma95',gamma95, 'edof',edof

# Plot twin plot
fig, ax1 = plt.subplots()
# plot on ax1 the coherence
ax1.plot(fcoh, cxy, 'b-')
ax1.set_xlabel('Frequency (hr-1)')
ax1.set_ylim([0,1])
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('Coherence', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

# plot on ax2 the phase
ax2 = ax1.twinx()
ax2.plot(fcoh[conf95], phase[conf95], 'r.')
ax2.set_ylabel('Phase (degrees)', color='r')
ax2.set_ylim([-200,200])
ax2.set_yticklabels([-180,-135,-90,-45,0,45,90,135,180])

for tl in ax2.get_yticklabels():
    tl.set_color('r')

ax1.grid(True)
#ax2.grid(True)
fig.suptitle('Coherence and phase (>95%) between signal 1 and 2', fontsize='12')
plt.show()

rawDescription: How to use the cross-spectral density to calculate the phase shift of two related signals

description: Use the cross-spectral density to calculate the phase shift of two related signals


code:
final = '''\
>M. tuberculosis H37Rv|Rv1617|pykA
VTRRGKIVCTLGPATQRDDLVRALVEAGMDVARMNFSHGDYDDHKVAYERVRVASDATGR
AVGVLADLQGPKIRLGRFASGATHWAEGETVRITVGACEGSHDRVSTTYKRLAQDAVAGD
RVLVDDGKVALVVDAVEGDDVVCTVVEGGPVSDNKGISLPGMNVTAPALSEKDIEDLTFA
LNLGVDMVALSFVRSPADVELVHEVMDRIGRRVPVIAKLEKPEAIDNLEAIVLAFDAVMV
ARGDLGVELPLEEVPLVQKRAIQMARENAKPVIVATQMLDSMIENSRPTRAEASDVANAV
LDGADALMLSGETSVGKYPLAAVRTMSRIICAVEENSTAAPPLTHIPRTKRGVISYAARD
IGERLDAKALVAFTQSGDTVRRLARLHTPLPLLAFTAWPEVRSQLAMTWGTETFIVPKMQ
STDGMIRQVDKSLLELARYKRGDLVVIVAGAPPGTVGSTNLIHVHRIGEDDV
'''
final_lines = final.splitlines()
print final_lines[0] + '\n' + ''.join(final_lines[1:])

rawDescription: How to remove the unwanted character like white spaces and newline from a string

description: Remove the unwanted character like white spaces and newline from a string


code:
#!/usr/bin/python3
pidfile = '/var/run/MyApplication.pid'

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if pid < 0:
        return False
    try:
        os.kill(pid, 0)
    except OSError, e:
        return e.errno == errno.EPERM
    else:
        return True

if isfile(pidfile):
    with open(pidfile) as fh:
        thepid = fh.read()

    pidnr = int(thepid)
    if pid_exists(pidnr):
        exit(1) # The previous instance is still running
    else:
        remove(pidfile) # Prev instance is dead, remove pidfile

# Create a pid-file with the active PID written in it
with open(pidfile, 'w') as fh:
    fh.write(str(getpid()))

## Your code goes here...

remove(pidfile)

rawDescription: running python script as startup service ubuntu 12.04

description: Running python script as startup service ubuntu 12.04


rawDescription: Explain the function

description: Explain the function


code:
from urllib2 import urlopen
citylinkpage = urlopen("http://www.city-data.com/city/Texas.html")
from bs4 import BeautifulSoup as BS
soup = BS(citylinkpage)
allImportantLinks = soup.select('table.cityTAB td.ph a')
print allImportantLinks[:10]
allCityUrls = ["http://www.city-data.com/city/"+a.get('href') for a in allImportantLinks if not a.get('href').startswith('javascript:')]
allCityUrls

rawDescription: Scraping data from multiple links on a webpage


code:
import wx
from wx.lib.scrolledpanel import ScrolledPanel

class Tester(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Window")
        self.panel = ScrolledPanel(parent=self, id=-1)
        self.panel.SetupScrolling()
        self.sizerItems = []

        Btn1 = wx.Button(self.panel, -1, "I'm a Button!")
        Btn2 = wx.Button(self.panel, -1, "Me Too!")
        Btn3 = wx.Button(self.panel, -1, "Hey! Quiet up there!")
        Btn4 = wx.Button(self.panel, -1, "Jeez Frank, relax")

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        hbox1.Add(Btn1, flag=wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        hbox1.Add(Btn2, flag=wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        hbox2.Add(Btn3, flag=wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        hbox2.Add(Btn4, flag=wx.LEFT|wx.RIGHT|wx.TOP, border=10)

        vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=25)
        vbox.Add(hbox2, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP|wx.BOTTOM, border=25)

        self.panel.SetSizer(vbox)
        self.panel.Layout()

        self.GetAllChildren(self.panel.GetSizer())
        print self.sizerItems

    def GetAllChildren(self, item):
        for sizerItem in item.GetChildren():
            widget = sizerItem.GetWindow()
            if not widget:
                # then it's probably a sizer
                sizer = sizerItem.GetSizer()
                if isinstance(sizer, wx.Sizer):
                    self.GetAllChildren(sizer)
            else:
                self.sizerItems.append(widget)

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    Tester().Show()
    app.MainLoop()

rawDescription: Generate List of All sizerItems Nested in wxPython Sizers


code:
module_name = "filename_{0}".format(getpass.getuser())
exec_string = "import {0}".format(module_name)
exec exec_string

rawDescription: is it possible to import file if the file name is in variable?

description: Is it possible to import file if the file name is in variable


code:
tmp_iter = iter(tmp)
prev = tmp_iter.next()

for x in tmp_iter:
   print 'seq: ', x[1], 'prev seq:', prev[1], 'variance: ', x[1]-prev[1]
   prev = x

rawDescription: Optimal way to access a value from the last iteration in a loop


rawDescription: predict the outcome numbers using a list

description: Predict the outcome numbers using a list


code: print r'this is \n a test'

rawDescription: What does the "r" in pythons re.compile(r' pattern flags') mean?


code:
#!/usr/bin/env python

import re, sys
from collections import Counter

file_count = dict()
filenames = [ name.strip() for name in open(sys.argv[1]) ]

for name in filenames:
    for line in open(name):
        cat_count = Counter()
        for cat in re.sub('[^a-zA-Z ]+', '', line.rstrip()).split():
            cat_count[cat] += 1
        file_count[name] = cat_count

print file_count

rawDescription: Dictionary python trouble

description: Dictionary python trouble


code:
import urllib2
import json

locu_api = '****'

def loc_search(request):
    query = request.GET.get('query')
    api_key = locu_api
    url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
    locality = query.replace(' ', '%20')
    final_url = url + "&locality=" + locality + "&category=restaurant"
    json_obj = urllib2.urlopen(final_url)
    data = json.load(json_obj)

    for item in data['objects']:
        print item['name']
        print item['phone']

rawDescription: Json query on button press python / django


code:
from Tkinter import *

SubnetM = 0

def beenclicked():
    radioValue = relStatus.get()
    return

def changeLabel(*args): # require *args for trace
    print "changeLabel", args
    if relStatus.get() == 'HOSTS':
        if custname.get() == "6":
            label4Text.set("255.255.255.248")
            return
    if relStatus.get() == 'NETWORKS':
        if custname.get() == "6":
            label4Text.set("224.0.0.0")
            return

app = Tk()
app.title("SUBNET MASK CALCULATOR")
app.geometry('400x450+200+200')

labelText = StringVar()
labelText.set("WELCOME!")
label1 = Label(app,textvariable=labelText, height=4)
label1.pack()

relStatus = StringVar()
relStatus.set(None)
radioValue = relStatus.get()
radio1 = Radiobutton(app, text="HOSTS", value="HOSTS", variable=relStatus, command=changeLabel)
radio1.pack()
radio1 = Radiobutton(app, text="NETWORKS", value="NETWORKS", variable=relStatus, command=changeLabel)
radio1.pack()

label2Text = StringVar()
label2Text.set("~Quantity~")
label2 = Label(app, textvariable=label2Text, height=4)
label2.pack()

custname = StringVar()
custname.set("0")
Quantity = Entry(app, textvariable=custname,)
Quantity.pack()
custname.trace("w", changeLabel)

label3Text = StringVar()
label3Text.set("Your Subnet Mask is...")
label3 = Label(app, textvariable=label3Text, height=4)
label3.pack()

label4Text = StringVar()
label4Text.set(SubnetM)
label4 = Label(app, textvariable=label4Text, height=4)
label4.pack()

button1 = Button(app, text="GO!", width=20, command=changeLabel)
button1.pack(padx=15, pady=15)

app.mainloop()

rawDescription: need assistance with Entry Tkinter in Python 2.5

description: Need assistance with Entry Tkinter in Python 2.5


code:
old_list = [
        (1, 'AAA', None, 1),
        (2, 'AAA', 'x', 0),
        (5, 'AAB', 'z', 1),
        (6, 'ABB', 'x', 1),
        (9, 'ABB', 'x', 1)]
from itertools import groupby
from operator import itemgetter
print [sorted(list(group), key=itemgetter(0))[-1]
       for key, group in groupby(old_list, key=itemgetter(1))]

rawDescription: python unique list based on item

description: Python unique list based on item


code:
def chkbox_checked():
   opt=[chkbox.v.get() for chkbox in cb]
   print opt

rawDescription: How to get the list of text values of multiple Checkbuttons in Tkinter in Python?

description: Get the list of text values of multiple Checkbuttons in Tkinter in Python


code:
for found in re.finditer('(.*?)', txt, re.DOTALL):
    print found.groups()

rawDescription: regular expressions : (.*), (.*?) and .*

description: Regular expressions : (.*), (.*?) and .*


code:
for roll, count in result.most_common():
    print '{}: {}'.format(roll, count)

rawDescription: Organize Counter () display in python?

description: Organize Counter () display in python


code:
import time

import wx
from wx.lib.newevent import NewCommandEvent

TimerChangeEvent, EVT_TIMER_CHANGE = NewCommandEvent()

class SettingsFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, size=(100, 200))
        self.CenterOnParent()
        self.SetBackgroundColour('#e4e4e4')

        self.radio1 = wx.RadioButton(self, label="1 sec", pos=(40, 45))
        self.radio1.Bind(wx.EVT_RADIOBUTTON, self.SetLab1)

        self.radio2 = wx.RadioButton(self, label="5 sec", pos=(40, 65))
        self.radio2.Bind(wx.EVT_RADIOBUTTON, self.SetLab2)

        self.radio3 = wx.RadioButton(self, label="10 sec", pos=(40, 85))
        self.radio3.Bind(wx.EVT_RADIOBUTTON, self.SetLab3)

        extBtn = wx.Button(self, label="Exit", pos=(20, 110))
        extBtn.Bind(wx.EVT_BUTTON, self.extFrame)

    def SetLab1(self, event):
        self.post_timer_change_event(1000)

    def SetLab2(self, event):
        self.post_timer_change_event(5000)

    def SetLab3(self, event):
        self.post_timer_change_event(10000)

    def post_timer_change_event(self, value):
        evt = TimerChangeEvent(self.Id, value=value)
        wx.PostEvent(self, evt)

    def extFrame(self, event):
        self.Close()

class MainPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        self.frame = parent
        self.CenterOnParent()

        setBtn = wx.Button(self, label="Set", pos=(45, 10))
        setBtn.Bind(wx.EVT_BUTTON, self.setFrame)

        self.redraw_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
        self.redraw_timer.Start(milliseconds=1000)

    def setFrame(self, event):
        settings_frame = SettingsFrame()
        settings_frame.Show()
        settings_frame.Bind(EVT_TIMER_CHANGE, self.on_change_timer)

    def on_redraw_timer(self, event):
        print "Test: " + time.ctime()

    def on_change_timer(self, event):
        value = event.value
        print 'Changing timer to:', value
        self.redraw_timer.Start(value)

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, size=(200, 200))
        panel = MainPanel(self)
        self.CenterOnParent()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

rawDescription: wx.lib.pubsub: How to change the value in a timer

description: Wx.lib.pubsub: How to change the value in a timer


code:
from inspect import getdoc
print getdoc(pos_tag)

rawDescription: Probing a python function

description: Probing a python function


code:
class Node:

    def __init__(self,parent = None):
        self.parent = parent
        self.children = []
        self.child_index = None

    def AddNode(self):
        new_child = Node(self)
        self.children.append(new_child)
        new_child.child_index = self.children.index(new_child)
        return new_child

    def getIndex(self):
        return self.child_index

a = Node()
b = a.AddNode()
c = a.AddNode()
d = a.AddNode()

print d.getIndex()
print c.getIndex()
print b.getIndex()

rawDescription: find self index for nested Python object

description: Find self index for nested Python object


rawDescription: Invert the order of a string, while preserving the original contents of the string


code: print ws.cell(column=12).value

rawDescription: read two columns in Excel using python

description: Read two columns in Excel using python


code:
import difflib as dl
x   = dl.SequenceMatcher(lambda x : x == ' ', "omg", "omgggg")
y   = dl.SequenceMatcher(lambda x : x == ' ', "omgggg","omg")
avg = (x.ratio()+y.ratio())/2.0
if avg>= 0.6:
    print 'Match!'
else:
    print 'Sorry!'

rawDescription: Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc


code:
for desc, items in differences:
    print desc
    print
    for item in items:
        print '\t' + item
    print

rawDescription: How to compare clusters?

description: Compare clusters


rawDescription: Error in the results of a list comprehension


code:
import datetime
date_list = [
        datetime.datetime(2012,1,1,0,0,0),
        datetime.datetime(2012,1,2,0,0,0),
        datetime.datetime(2012,1,4,0,0,0),
        datetime.datetime(2012,1,7,0,0,0),
        datetime.datetime(2012,1,8,0,0,0),
        ]
import itertools
[list(g) for k, g in itertools.groupby(enumerate(date_list), key=lambda (i, x): i-x.day)]

rawDescription: Python splitting a datetime list based on missing days


code:
phrase = raw_input("Please enter a sentence of 3 or 4 words: ")
output = ''.join([x[0] for x in phrase.split()])
print output

rawDescription: using find in python

description: Using find in python


code:
paths=['Brad/files/pdf/abc.pdf','Brad/files/pdf/abc2.pdf','Brad/files/pdf/abc3.pdf','Brad/files/pdf/abc4.pdf','mybucket/files/pdf/new/','mybucket/files/pdf/new/abc.pdf','mybucket/files/pdf/2011/']
def foo(m):
   return [p for p in paths if p.startswith(m+'/')]

print foo('Brad')

rawDescription: How can I get a list of all file names having same prefix on Amazon S3?

description: Get a list of all file names having same prefix on Amazon S3


code:
import pandas as pd

# Make DataFrame
df = pd.DataFrame(
    pd.date_range('1998-02-28', periods=12, freq='6M'),
    columns=['Date']
)
print 'Original DataFrame:'
print df
print

# Replace feb 29 with feb 28
df['Date'] = df['Date'].apply(
    lambda x:
        x if x.month != 2 and x.date != 29
        else pd.datetime(x.year, x.month, 28)
)

print 'Processed DataFrame:'
print df
print

rawDescription: Dealing with leap years and substituting a new date


code:
import nltk
pattern = [(r'(March)$','MAR')]
tagger = nltk.RegexpTagger(pattern)
print tagger.tag(nltk.word_tokenize('He was born in March 1991'))

rawDescription: How do I use Regexp Tagger in nltk?

description: Use Regexp Tagger in nltk


code:
def largest():
    f = pickAFile()
    sound = makeSound(f)
    value = []
    for i in range(1, getLength(sound)):
      value.append(getSampleValueAt(sound, i))
    print max(value)

rawDescription: Max() function using python from loop

description: Max() function using python from loop


code:
mylist = list("aabbccddeeffgghhii")
for x, v  in enumerate(mylist):
    if v in "bdfh":
        del mylist[x]
print mylist

rawDescription: python - recursively deleting dict keys?

description: Python - recursively deleting dict keys


code:
from bs4 import BeautifulSoup
import requests

html = requests.get('https://archive.org/stream/warandpeace030164mbp/warandpeace030164mbp_djvu.txt')
soup = BeautifulSoup(html.text, "lxml")
war_and_peace = soup.pre.get_text()

paragraphs = war_and_peace.split('\n\n')
paragraphs[:] = [p for p in paragraphs if len(p)]       # Remove empty entries

print paragraphs[671]

rawDescription: How to split a txt file into multiple files excluding lines with certain content

description: Split a txt file into multiple files excluding lines with certain content


code:
if (int(one[1]) == solution) or (int(two[1]) == solution):
    print "Hello, world"

rawDescription: Quick question regarding format of if-elif statements


code:
import ipaddr
b = ipaddr.Bytes('\x20\x01\x06\x58\x02\x2a\xca\xfe' '\x02\x00\x00\x00\x00\x00\x00\x01')
print ipaddr.IPAddress(b)

rawDescription: Create ipaddr-py IPv6Address from byte string


code:
print map_rows
#{'Apple': 0, 'Microsoft': 1}
print map_cols
#{'Banana': 0, 'Google': 1, 'Orange': 2}
print result.toarray()
#array([[ 5.,  1.,  0.],
#       [ 0.,  0.,  2.]])

rawDescription: What's the most pythonic way to load a matrix in ijv/coo/triplet format?


code:
result = []
for word in someList:
    if 'p' not in word:
        result.append(word)
print result

rawDescription: negating with re.search (find strings that don't contain a specific character)

description: Negating with re.search (find strings that don't contain a specific character)


code:
import csv
import sys #used for passing in the argument
file_name = sys.argv[1] #filename is argument 1
with open(file_name, 'rU') as f:  #opens PW file
    reader = csv.reader(f)
    # Print every value of every row.
    for row in reader:
        for value in row:
            print value

rawDescription: Building list of lists from CSV file

description: Building list of lists from CSV file


code:
#My python script called mypy.py
import sys

if len(sys.argv) != 2:
  sys.exit("Not enough args")
ca_one = str(sys.argv[1])
ca_two = str(sys.argv[2])

print "My command line args are " + ca_one + " and " + ca_two

rawDescription: Run a python script with arguments

description: Run a python script with arguments


code:
from ConfigParser import RawConfigParser

parser= RawConfigParser()
parser.read('demo.ini')

print
#To retrieve all the sections
print parser.sections()

print
#to retrieve options of a section
print parser.options('headers')

#To get value of each option in a section
for i in parser.options('headers'):
     print parser.get('headers',i)

rawDescription: How could I extract the lengthy config from my controller/main code


code:
from sklearn.utils import shuffle
from sklearn.cross_validation import StratifiedKFold, cross_val_score
for i in range(10):
   X, y = shuffle(X_orig, y_orig, random_state=i)
   skf = StratifiedKFold(y, 10)
   print cross_val_score(clf, X, y, cv=skf)

rawDescription: 10*10 fold cross validation in scikit-learn?


code:
from datetime import timedelta
print timedelta(minutes=6*60)

rawDescription: Python datetime add

description: Python datetime add


code:
key = 'b'
val = 'a'
print d
d.setdefault(key, []).append(val)
print d
d.setdefault(key, []).append('zee')
print d

rawDescription: Efficient way to either create a list, or append to it if one already exists?


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

data = pd.read_csv('Workbook2.csv', header=None)
print data

rawDescription: Fixed y axis in Python plotting times in 12 hr format


code:
print split_it('Test1.0,0.csv')
print split_it('Test2.wma')
print split_it('Test3.1100,456.jpg')
print split_it('T.E.S.T.4.5,6.png')
print split_it('Test5,7,8.sss')
print split_it('Test6.2,3,4.png')
print split_it('Test7.5,6.7,8.test')

rawDescription: Python/Regex - Match .#,#. in String

description: Python/Regex - Match .#,#. in String


code:
import itertools

for grpname,grpteams in df.groupby('group')['team']:
    # No need to use grpteams.tolist() to convert from pandas Series to Python list
    print list(itertools.combinations(grpteams, 2))

[('Canada', 'Netherlands'), ('Canada', 'China'), ('Canada', 'New Zealand'), ('Netherlands', 'China'), ('Netherlands', 'New Zealand'), ('China', 'New Zealand')]
[('Germany', 'Norway'), ('Germany', 'Thailand'), ('Germany', 'Ivory Coast'), ('Norway', 'Thailand'), ('Norway', 'Ivory Coast'), ('Thailand', 'Ivory Coast')]
[('Japan', 'Switzerland'), ('Japan', 'Ecuador'), ('Japan', 'Cameroon'), ('Switzerland', 'Ecuador'), ('Switzerland', 'Cameroon'), ('Ecuador', 'Cameroon')]
[('USA', 'Sweden'), ('USA', 'Australia'), ('USA', 'Nigeria'), ('Sweden', 'Australia'), ('Sweden', 'Nigeria'), ('Australia', 'Nigeria')]
[('Brazil', 'Spain'), ('Brazil', 'South Korea'), ('Brazil', 'Costa Rica'), ('Spain', 'South Korea'), ('Spain', 'Costa Rica'), ('South Korea', 'Costa Rica')]
[('France', 'England'), ('France', 'Mexico'), ('France', 'Colombia'), ('England', 'Mexico'), ('England', 'Colombia'), ('Mexico', 'Colombia')]

rawDescription: Generate pairings within World Cup tournament groups


code:
import mechanize

br = mechanize.Browser()
br.open(URL)
br.select_form(nr=0)
for i in range(0, len(br.find_control(type="checkbox").items)):
    br.find_control(type="checkbox").items[i].selected =True
reponse = br.submit()
print reponse.read()

rawDescription: Python mechanize checkboxes

description: Python mechanize checkboxes