code:
import time
import sqlite3

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,  create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

Base = declarative_base()
DBSession = scoped_session(sessionmaker())

class Customer(Base):
    __tablename__ = "customer"
    id = Column(Integer, primary_key=True)
    name = Column(String(255))

def init_sqlalchemy(dbname = 'sqlite:///sqlalchemy.db'):
    global engine
    engine = create_engine(dbname, echo=False)
    DBSession.remove()
    DBSession.configure(bind=engine, autoflush=False, expire_on_commit=False)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)

def test_sqlalchemy_orm(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    for i in range(n):
        customer = Customer()
        customer.name = 'NAME ' + str(i)
        DBSession.add(customer)
        if i % 1000 == 0:
            DBSession.flush()
    DBSession.commit()
    print "SqlAlchemy ORM: Total time for " + str(n) + " records " + str(time.time() - t0) + " secs"

def test_sqlalchemy_orm_pk_given(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    for i in range(n):
        customer = Customer(id=i+1, name="NAME " + str(i))
        DBSession.add(customer)
        if i % 1000 == 0:
            DBSession.flush()
    DBSession.commit()
    print "SqlAlchemy ORM pk given: Total time for " + str(n) + " records " + str(time.time() - t0) + " secs"

def test_sqlalchemy_core(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    engine.execute(
        Customer.__table__.insert(),
        [{"name":'NAME ' + str(i)} for i in range(n)]
    )
    print "SqlAlchemy Core: Total time for " + str(n) + " records " + str(time.time() - t0) + " secs"

def init_sqlite3(dbname):
    conn = sqlite3.connect(dbname)
    c = conn.cursor()
    c.execute("DROP TABLE IF EXISTS customer")
    c.execute("CREATE TABLE customer (id INTEGER NOT NULL, name VARCHAR(255), PRIMARY KEY(id))")
    conn.commit()
    return conn

def test_sqlite3(n=100000, dbname = 'sqlite3.db'):
    conn = init_sqlite3(dbname)
    c = conn.cursor()
    t0 = time.time()
    for i in range(n):
        row = ('NAME ' + str(i),)
        c.execute("INSERT INTO customer (name) VALUES (?)", row)
    conn.commit()
    print "sqlite3: Total time for " + str(n) + " records " + str(time.time() - t0) + " sec"

if __name__ == '__main__':
    test_sqlalchemy_orm(100000)
    test_sqlalchemy_orm_pk_given(100000)
    test_sqlalchemy_core(100000)
    test_sqlite3(100000)

rawDescription: Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly?


code:
input = """"<person>John</person>went to<location>London</london>"""
soup = BeautifulSoup(input)
print soup.findAll("person")[0].renderContents()
print soup.findAll("location")[0].renderContents()

rawDescription: Regex to find words between two tags

description: Regex to find words between two tags


code:
myDict = {'X':'X+YF','Y':'FX-Y'}
myXVal = myDict['X']
myYVal = myDict['Y']
print myXVal, myYVal

rawDescription: Working with python dictionary notation

description: Working with python dictionary notation


code:
df_result = pd.merge(month_perf, year_perf, left_on='Year', right_on='Year')
print df_result.tail()

rawDescription: Index or group by attributes of a DateTimeIndex in Pandas


code:
def dowork(observer=None):
  worker = WorkerClass()
  u = worker.updater()
  total = u.next()
  if observer:
    observer.progress_total(total)
  for i in u:
    if i == 'end': break
    if observer:
      observer.progress(i)
  print 'done!'

rawDescription: Sending progress from thread to gui

description: Sending progress from thread to gui


code:
with open("Input.txt") as inputFile:
    lines = [line for line in inputFile]
    month, mydate, time_start, time_stop = [lines[0].strip()] + lines[1].strip().split()
    print month, mydate, time_start, time_stop

rawDescription: Parse text file in Python

description: Parse text file in Python


code:
# bonus: save image using only the N most common colours
c = ar.copy()
for i, code in enumerate(codes):
    c[scipy.r_[scipy.where(vecs==i)],:] = code
scipy.misc.imsave('clusters.png', c.reshape(*shape))
print 'saved clustered image'

rawDescription: Python - Find dominant/most common color in an image


rawDescription: Manipulating two lists

description: Manipulating two lists


code:
from geopy.geocoders import GoogleV3
def get_lat_lng(zip_code):
    geocoder = GoogleV3()
    location = geocoder.geocode(query=str(zip_code),components={"country": "PK","locality":"lahore"})
    if location:
        print location._address
        lat, lng = location.latitude, location.longitude
    return lat, lng

print(get_lat_lng(54000))

rawDescription: geopy does not show correct output

description: Geopy does not show correct output


code:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

rawDescription: python glob.glob - how to find a specific file (or a list of files) without knowing how deep it in in subdirs?

description: Python glob.glob - how to find a specific file (or a list of files) without knowing how deep it in in subdirs


code:
from collections import Counter
master_wordlist = ['dog', 'cat', 'hat', 'bat', 'big']
article_a = ['dog', 'cat', 'dog','big']
article_b = ['dog', 'hat', 'big', 'big', 'big']

c_a = Counter(article_a)
c_b = Counter(article_b)

print [c_a[x] for x in master_wordlist]
print [c_b[x] for x in master_wordlist]

rawDescription: Python - cleaning data to run apriori algorithm


code:
from myproject.myapp.middleware.globalrequestmiddleware import GlobalRequestMiddleware

# Get the current request object for this thread
request = GlobalRequestMiddleware.get_current_request()

# Access some of its attributes
print 'The current value of session variable "foo" is "%s"' % request.SESSION['foo']
print 'The current user is "%s"' % request.user.username

# Add something to it, which we can use later on
request.some_new_attr = 'some_new_value'

rawDescription: Is there a way to access the context from everywhere in Django?


code:
for i in ftp.listdir():
    lstatout=str(ftp.lstat(i)).split()[0]
    if 'd' not in lstatout: print i, 'is a file'

rawDescription: How to list all the folders and files in the directory after connecting through sftp in python

description: List all the folders and files in the directory after connecting through sftp in python


code:
def f1(a):
    return repr(a)

def f2(a):
    return a.__repr__()

def f3(a):
    return `a`

rawDescription: What do backticks mean to the python interpreter: `num`


code:
import itertools
from datetime import datetime, timedelta

names = ["P1", "P2", "P3"]
extns = {'P1': 'xxxx', 'P2': 'xxxy', 'P3': 'xxyy'}

for (day,name) in itertools.izip((day for day in (datetime.today()+timedelta(n) for n in itertools.count()) if day.weekday() not in (5,6)), (itertools.cycle(names))):
    print "| %s | %s | %s |" % (day.strftime("%d-%m-%y"), name, extns[name])

rawDescription: Incrementing date whilst ignoring weekends


code: print match.group(1)

rawDescription: Extract only the portion of a string between two regex patterns


code:
#!/usr/bin/env python
import bcrypt
import random

password = str(random.getrandbits(8000))
print bcrypt.hashpw(password,bcrypt.gensalt())

rawDescription: bcrypt in python

description: Bcrypt in python


code:
import logging
import sys

log = logging.getLogger()
log.setLevel(logging.DEBUG)
stream = logging.StreamHandler(sys.stdout)
stream.setLevel(logging.DEBUG)
log.addHandler(stream)

# for calling from outside
def main__(args):
    print("main__()") # can see output
    print type(args)
    print len(args)
    for eachArg in args:
        logging.info(eachArg)

rawDescription: How to see logging output in embedded python interpreter?

description: See logging output in embedded python interpreter


code:
import urllib2
from lxml import html

tree = html.parse(urllib2.urlopen('http://www.opensiteexplorer.org/links?site=www.google.com'))

spans = tree.xpath('//span[@class="metrics-authority"]')
data = [item.text.strip() for item in spans]
print "Domain Authority: {0}, Page Authority: {1}".format(*data)

div = tree.xpath('//div[@id="metrics-page-link-metrics"]//div[@class="has-tooltip"]')[1]
print "Root Domains: {0}".format(div.text.strip())

rawDescription: How can I get certain text from a website with Python?

description: Get certain text from a website with Python


code:
def gen_data(n):
    l = []
    for k in xrange(n):
        l.append(collections.namedtuple('normal', ('x', 'y', 'z'))(random.random(), random.random(), random.random()))
    return l

if __name__ == '__main__':
    times = 1000
    print 'format:'
    print timeit.Timer('for i in xrange(len(normal_array)):\n    str = "vn {0:.15f} {1:.15f} {2:.15f}\\n".format(normal_array[i].x, normal_array[i].y, normal_array[i].z)\n',
            'from __main__ import gen_data; normal_array = gen_data(1000)').timeit(times)
    print '%s:'
    print timeit.Timer('for i in xrange(len(normal_array)):\n    str = "vn %.15f %.15f %.15f\\n".format(normal_array[i].x, normal_array[i].y, normal_array[i].z)\n',
            'from __main__ import gen_data; normal_array = gen_data(1000)').timeit(times)
    print '%s+iteration:'
    print timeit.Timer('for o in normal_array:\n    str = "vn %.15f %.15f %.15f\\n".format(o.x, o.y, o.z)\n',
            'from __main__ import gen_data; normal_array = gen_data(1000)').timeit(times)

rawDescription: faster way to do .format()

description: Faster way to do .format()


code:
indices = [(x, y) for y in range(5) for x in range(5)]
sub_list = [(1, 2), (2, 3), (3, 4)]

d = {}

for (x, y) in indices:
    d[x, y] = (x ** 2 + y ** 2) ** 0.5

values = [d[ind] for ind in sub_list] # <-- no problem

print reduce(lambda x, y: x + y, values)

rawDescription: Retrieve properties of a class instance stored in a dictonary


code:
from bs4 import BeautifulSoup
import urllib2
url="https://www.seedrs.com/tanorganic"
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read(), "html.parser")
target = soup.find("dl", class_="investment_sought")
print target.text
figure = target.find("dd").text
print figure

rawDescription: 'NoneType' object has no attribute 'text'


code:
from random import randint
num = randint(5,10)
print "This should be reprinted only {} times\n".format(num)*num

rawDescription: Limiting loop repetition in python

description: Limiting loop repetition in python


code:
instances = [read_instance(filename) for filename in 'abcd']

print len(instances)  # Prints 4
print instance[0]  # Prints the first
print instance[1]  # Prints the second, etc

rawDescription: How to programmatically add instances in Python?

description: Programmatically add instances in Python


rawDescription: How to get current date and time from DB using SQLAlchemy

description: Get current date and time from DB using SQLAlchemy


code: print base64.b64encode(buf.getvalue())

rawDescription: HTML set an image's content to content generated by a server-side script


code:
from collections import defaultdict

def topological_sort(dependency_pairs):
    'Sort values subject to dependency constraints'
    num_heads = defaultdict(int)   # num arrows pointing in
    tails = defaultdict(list)      # list of arrows going out
    for h, t in dependency_pairs:
        num_heads[t] += 1
        tails[h].append(t)

    ordered = [h for h in tails if h not in num_heads]
    for h in ordered:
        for t in tails[h]:
            num_heads[t] -= 1
            if not num_heads[t]:
                ordered.append(t)
    cyclic = [n for n, heads in num_heads.iteritems() if heads]
    return ordered, cyclic

if __name__ == '__main__':
    connections = [(3, 7), (6, 5), (4, 6), (5, 3), (7, 8), (1, 2), (2, 1)]
    print topological_sort(connections)

rawDescription: How can I order a list of connections

description: Order a list of connections


rawDescription: Convert data in String format to List - python


code:
class MyPlugin(Plugin):
    def register_signals(self):
        print "Class created and registering signals"

    def other_plugin_stuff(self):
        print "I can do other plugin stuff"

rawDescription: Plugin architecture - Plugin Manager vs inspecting from plugins import *


code:
x = ['a', '1', ['c', 'd', ['e', ['f', '123']]]]

def recurse(y):
    left,right = [],None

    # Here we loop over the elements and whenever we encounter
    # another list, we recurse.
    for elem in y:
        if isinstance(elem,list):
            right = recurse(elem)
        else:
            left.append(elem)

    # If there is no further nested list, return only the
    # concatenated values, else return the concatenated values
    # and the next list in the nest.
    if right is None:
        return ["".join(left)]
    else:
        return ["".join(left),right]

print recurse(x)

rawDescription: Concatenate Items within nested list python


code:
myl = ['A','B','C','D','E','F']
[''.join(myl[i:i+2]) for i in range(0, len(myl), 2)]
print '\n'.join(''.join(myl[i:i+2]) for i in range(0, len(myl), 2))

rawDescription: List Slicing python

description: List Slicing python


code:
import textwrap
import scipy.optimize as optimize

def make_model(*fixed):
    template = textwrap.dedent("""
        def func(variable, {fixed}):
            {variable} = variable
            return 4*(b-a)**2 + 5*(c-d)**2
        """)
    variable = set(('a', 'b', 'c', 'd')).difference(fixed)
    ns = dict()
    funcstr = template.format(variable=', '.join(variable), fixed=', '.join(fixed))
    print(funcstr)  # comment out if you don't want to see the function
    exec funcstr in ns
    return ns['func']

def solve(initial_guess, **givens):
    fixed = tuple(givens.keys())
    vals = tuple(givens.values())
    sol = optimize.minimize(make_model(*fixed), initial_guess, args=vals)
    return sol

print(solve(initial_guess=1, a=1, c=1.1, d=-1.2))

rawDescription: Dynamically choose argument for which to minimize a function in python using scipy.optimize


code:
# collect, the constants to a dictionary,
# with the proper key names
d = dict(a=1, b=2, c=3)

# create functions, where you want to use the constants
# and use the same key-names as in dictionary, and also
# add '**kwargs' at the end of the attribute list
def func1(a, b, d=4, **kwargs):
    print a, b, d

def func2(c, f=5, **kwargs):
    print c, f

# now any time, you use the original dictionary
# as an argument for one of these functions, this
# will let the function select only those keywords
# that are used later
func1(**d)
# 1 2 4
func2(**d)
# 3 5

rawDescription: Organizing code for Testing with Constants from a Configuration File


code:
# Open an existing file or create if it doesn't exist
with touchopen("./tool.run", "r+") as doing_fd:

    # Acquire a non-blocking exclusive lock
    fcntl.lockf(doing_fd, fcntl.LOCK_EX)

    # Read a previous value if present
    previous_value = doing_fd.read()
    print previous_value

    # Write the new value and truncate
    doing_fd.seek(0)
    doing_fd.write("new value")
    doing_fd.truncate()

rawDescription: How to open (read-write) or create a file with truncation possible?

description: Open (read-write) or create a file with truncation possible


code:
in_para = False
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, ':', len(paragraph)
         print ' '.join(paragraph)
         del paragraph[:]
         para_type = word
  else:
    paragraph.append(word)
else:
  if in_para == True:
    print 'Words in last paragraph', para_type, ':', len(paragraph)
    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:
import csv

inf = csv.reader(open('ACslist.csv', 'r'))
out1 = csv.writer(open('ACs1.csv', 'wb'))
out2 = csv.writer(open('ACs2.csv', 'wb'))
out3 = csv.writer(open('ACs3.csv', 'wb'))

firstrow = inf.next()
out1.writerow(firstrow)
out2.writerow(firstrow)
out3.writerow(firstrow)

sum1 = 0
sum2 = 0
sum3 = 0

count1 = 0
count2 = 0
count3 = 0

for row in inf:
    row[1] = int(row[1])
    if sum1 == 0:
        out1.writerow(row)
        count1 += 1
        sum1 += row[1]
    elif sum2 == 0:
        out2.writerow(row)
        count2 += 1
        sum2 += row[1]
    elif sum1 < sum2 and sum1 < sum3 and count1 < 90:
        out1.writerow(row)
        count1 += 1
        sum1 += row[1]
    elif sum2 < sum1 and sum2 < sum3 and count2 < 90:
        out2.writerow(row)
        count2 += 1
        sum2 += row[1]
    elif sum3 < sum2 and sum3 < sum1 and count3 < 90:
        out3.writerow(row)
        count3 += 1
        sum3 += row[1]
    elif count1 < 90:
        out1.writerow(row)
        count1 += 1
        sum1 += row[1]
    elif count2 < 90:
        out2.writerow(row)
        count2 += 1
        sum2 += row[1]

print sum1
print sum2
print sum3

rawDescription: First, Last, Next ordering in exporting CSV, Python


code:
class Person:
    def __init__(self, name):    # Constructor
        self.name = name

    def sayHello(self):          # Class method (requires `self` parameter)
        print 'Hello, {0}'.format(self.name)

    @staticmethod
    def makePerson(name):        # Static Method (note, no `self` parameter)
        p = Person(name)
        return p

    @classmethod
    def makePerson2(cls, name):  # Class method. First parameter is class
        p = cls(name)            #    Call constructor for that class
        return p

def main():
    p2 = Person.makePerson('Joe')  # Call static "factory" method
    p2.sayHello()

rawDescription: calling function of one class from other class in python

description: Calling function of one class from other class in python


code:
for whatever in range(len(a)):
   print whatever, a[whatever]

rawDescription: Range function Python

description: Range function Python


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

try:
    # dont use ; !
    infilename = sys.argv[1]
    outfilename = sys.argv[2]
except:
    print "Usage is <script> inFile outFile"

# you could use `with` here if you have a Python 2.7
ifile = open(infilename,'r')
ofile = open(outfilename, 'w')

# no need to count yourself, enumerate does that
# plus when you iterate over a file you get lines too
for i, line in enumerate(ifile, start=1):
    # dont shadow builtins like `list`
    parts = line.split()
    parts[0] = i
    # join is the inverse function to split
    new_line = ' '.join("%d" % int(val) for val in parts)
    ofile.write(new_line + '\n')

ifile.close()
ofile.close()

rawDescription: change the numbers in the 1st column

description: Change the numbers in the 1st column


code:
def is_sublist_of_any_list(cand, lists):
    # Compare candidate to a single list
    def is_sublist_of_list(cand, target):
        try:
            i = 0
            try:
                start = target.index(cand[0])
            except:
                return False

            while start < (len(target) + len(cand)) - start:
                if cand == target[start:len(cand)]:
                    return True
                else:
                    start = target.index(cand[0], start + 1)
        except ValueError:
            return False

    # See if candidate matches any other list
    return any(is_sublist_of_list(cand, target) for target in lists if len(cand) <= len(target))

# Compare candidates to all other lists
def super_lists(lists):
    a = [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])]
    return a

lists = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
expect = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69],  [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]]

def test():
    out = super_lists(list(lists))

    print "In  : ", lists
    print "Out : ", out

    assert (out == expect)

rawDescription: Python list filtering: remove subsets from list of lists


code:
#!/usr/bin/env python

from Tkinter import *

class App():

    def __init__(self, master):
        self.master = master

        self.all_entries = {} # empty dictionary
        self.all_entries_vars = {} # empty dictionary

        self.all_optionmenus = {} # empty dictionary
        self.all_optionmenus_vars = {} # empty dictionary

        fixtures = ["One", "Two", "Tree", "Other"]

        # create 5 options menu
        for i in range(5):
            self.all_optionmenus_vars[i] = StringVar()
            self.all_optionmenus_vars[i].set("One")

            self.all_optionmenus[i] = OptionMenu(self.master, self.all_optionmenus_vars[i], *fixtures, command=lambda selection, col=i:self.addEntry(selection, col))
            self.all_optionmenus[i].grid(row=1, column=i)

        Button(master, text="Print OptionMenus Vars", command=self.printOptionMenus).grid(row=2, column=0, columnspan=5)
        Button(master, text="Print Entries Vars", command=self.printEntries).grid(row=3, column=0, columnspan=5)

    def run(self):
        self.master.mainloop()

    def addEntry(self, selection, col):

        if selection == "Other":

            # if Entry was created before
            if col in self.all_entries:
                # show existing Entry
                self.all_entries[col].grid(row=0, column=col)
            else:
                # create new Entry
                self.all_entries_vars[col] = StringVar()
                self.all_entries[col] = Entry(self.master, textvariable=self.all_entries_vars[col])
                self.all_entries[col].grid(row=0, column=col)

        # if Entry was created before
        elif col in self.all_entries:
            # hide Entry
            self.all_entries[col].grid_forget()

    def printEntries(self):
        print "-"*30
        for key in self.all_entries_vars:
            print "Entry #%d: %s" % ( key, self.all_entries_vars[key].get() )

    def printOptionMenus(self):
        print "-"*30
        for key in self.all_optionmenus_vars:
            print "OptionMenu #%d: %s" % ( key, self.all_optionmenus_vars[key].get() )

#----------------------------------------------------------------------

if __name__ == '__main__':
    App(Tk()).run()

rawDescription: What's the difference between these two functions in Tkinter?


code:
import subprocess
import sys

# only to wait some time...
import time

def f(name):
    "Function that could run in background for a long time (30')"
    time.sleep(5)
    print 'hello', name

if __name__ == '__main__':
    if (len(sys.argv) > 1) and (sys.argv[1] == 'SUB'):
        # Should be an internal execution: start the lengthy function
        f('bar')
    else:
        # normal execution: start a subprocess with same script to launch the function
        p = subprocess.Popen("%s %s SUB" % (sys.executable, sys.argv[0]))
        # other processing...
        print 'END of normal process'

rawDescription: Running function as a thread in background python and exit before its application


code:
import re

words = ('apple', 'plepe', 'leoran', 'lemon')
s = 'bananaappleorangestrawberryapplepear'

x = set()

for w in words:
    for m in re.finditer(w, s):
        i = m.start()
        for j in range(i, i+len(w)):
            x.add(j)

result = ''.join(('x' if i in x else s[i]) for i in range(len(s)))
print result

rawDescription: String coverage optimization in Python

description: String coverage optimization in Python


code:
def lol():
    print "first!"
    return
    print "unreachable"

rawDescription: Exit in a function using Python

description: Exit in a function using Python


code:
for x, y in numpy.argwhere(H == H.max()):
    # center is between x and x+1
    print numpy.average(xedges[x:x + 2]), numpy.average(yedges[y:y + 2])

rawDescription: Find peak of 2d histogram

description: Find peak of 2d histogram


rawDescription: How do I use integer arithmetic to convert fractions into floating point numbers in python?

description: Use integer arithmetic to convert fractions into floating point numbers in python


code:
import csv

with open("file.txt", "r") as f_input:
    csv_input = csv.reader(f_input, delimiter="\t")

    for cols in csv_input:
        print " ".join(cols)

rawDescription: parse list in python with \t

description: Parse list in python with \t


code:
import string
import numpy as np

x = np.array([[0, 2, 3], [2, 0, 4], [0, 4, 0]], np.int64)
mapping = {letter:idx for (idx, letter) in enumerate(string.ascii_uppercase)}

def coords(letter1, letter2):
    """ assuming that the letters are always uppercase """
    return mapping[letter1], mapping[letter2]

# now to get what you wanted:
result  = x[coords('A', 'B')]
# or really short method:
result = x[string.ascii_uppercase.index('A'), string.ascii_uppercase.index('B')]

print result

rawDescription: Look up value from row and column headers


code:
list_name = raw_input('wallet or numbers? ')
try:
    print getattr(myDict, list_name)
except AttributeError:
    print "Sorry, no such list"

rawDescription: Print variable from other file with raw_input


code:
# example with a default plane
uv_dict  = uv_centroids('pPlane1')
ordered = uv_dict.keys()
ordered.sort()
for k in ordered:
    print k, uv_dict[k]

# prints out the keys and faces ordered 0,10,20... 1, 11, 21.... etc

rawDescription: re-ordering polygon face index in maya

description: Re-ordering polygon face index in maya


code: print unicode("éáóý");

rawDescription: Is it possible to represent non-ASCII characters?


code:
settings = {}
settings['name'] = 'carl'

key2 = "foo $global.name bar"

import re
print re.sub(r'\$(\w+)\.(\w+)', lambda m: settings[m.group(2)], key2)

rawDescription: How to extract all substrings between certain characters by using regular expression in Python?

description: Extract all substrings between certain characters by using regular expression in Python


code:
print 'Created: '+RootOutput+"\\Full_Extent.shp"
f = open(RootOutput+'\\Success_LOG.txt', 'a')
f.write(str(list)+"\n\n Merged to: "+RootOutput+"\\Full_Extent.shp")
f.close()

rawDescription: Python: Current directory in an os.walk

description: Python: Current directory in an os.walk


rawDescription: Generating recurring dates using python?

description: Generating recurring dates using python


code:
import urllib2,StringIO
from lxml import etree

seite = urllib2.urlopen("http://www.samsungapps.com/topApps/topAppsDetail.as?productId=G00000467050&listYN=Y")
html = seite.read()
seite.close()
parser = etree.HTMLParser()
tree = etree.parse(StringIO.StringIO(html), parser)
xpath = "//div[contains(@class,'detail-view')]/h4/text()"
name = tree.xpath(xpath)
xpath = "//div[contains(@class,'detail-view')]/table/tbody/tr[2]/td/text()"
cat = tree.xpath(xpath)
xpath = "//div[contains(@class,'detail-view')]/table/tbody/tr[3]/td/text()"
typ = tree.xpath(xpath)
xpath = "//div[contains(@class,'detail-view')]/table/tbody/tr[4]/td/text()"
version = tree.xpath(xpath)

print name[0].strip().encode("utf-8")
print cat[0].strip().encode("utf-8")
print typ[0].strip().encode("utf-8")
print version[0].strip().encode("utf-8")

rawDescription: Whitespace problem with python and lxml

description: Whitespace problem with python and lxml


code:
for item in data['clubs']:
    if 'id' in item:
        print item['id']

rawDescription: Can't encode content of keys from json

description: Can't encode content of keys from json


code:
def send_one_file(file_dir, host_pair, files):

    src, dst = host_pair  # a tuple of Mininet node objects

    # choose a random file from files
    rand_fname = random.sample(files, 1)[0]
    rand_path = os.path.join(file_dir, rand_fname)

    port = random.randint(1024, 65535)

    # Start listening at the destination host
    dst_cmd = 'nc -l %d > /home/mininet/sent/%s.out' % (port, rand_fname)
    print os.path.getsize(rand_path)
    dst.popen( dst_cmd, shell=True )

    # Send file from the source host
    src_cmd = 'nc %s %s < %s' % (dst.IP(), port, rand_path)
    src.popen( src_cmd, shell=True )

rawDescription: Sending "random" traffic through Mininet network


code:
tgt='''\
section aaa:
   some values
   value 5
section bbb
   more values
value 6
section ccc:
   some values
   value 5
section ddd:
   more values
   value 6'''

pat=re.compile(r'^section (\w+).*?^\s*value (\d+)',flags=re.MULTILINE|re.DOTALL)

print [(m.group(1),m.start(),m.end())
          for m in pat.finditer(tgt)
          if m.group(2)=='6']

rawDescription: Regex: Matching the closest value backwards


code:
filex.py
import argparse
def f():
    p = argparse.ArgumentParser()
    p.add_argument("-c", dest="configfile",help="Input configuration file")
    args = p.parse_args()
    configfile = args.configfile
    print configfile

rawDescription: python: use command line argument from file A in file B

description: Python: use command line argument from file A in file B


code:
import requests

URL = "https://query.yahooapis.com/v1/public/yql"

query = 'select * from yahoo.finance.quotes where symbol in ("GOOG")'

params = {
    "q": query,
    "format": "json",
    "env": "store://datatables.org/alltableswithkeys"
}

data = requests.get(URL, params=params).json()

print data['query']['results']['quote']['PreviousClose']
print data['query']['results']['quote']['Open']

rawDescription: Scraping for text between nondescript tags


code:
import re

f = open ("parse.txt", "rb")
fileRead = f.read()

Description = re.findall("Description[^:]*(.*)", fileRead)
amount = re.findall("amount[^:]*(.*)", fileRead)
requirements = re.findall("requirements[^:]*(.*)", fileRead)
ID1 = re.findall("ID1[^:]*(.*)", fileRead)

print Description[0]
print amount[0]
print requirements[0]
print ID1[0]

f.close()

rawDescription: Parse text between multiple lines - Python 2.7 and re Module


code:
from functools import wraps

class A(object):
     @abc.abstractmethod
     def method1(self):
         raise Exception("Unimplemented method")

     def method2(self):
         print "method1 finished"

     def __getattribute__(self, name):
         obj = super(A, self).__getattribute__(name)
         if name == 'method1':
             @wraps(obj)
             def wrapper(*args, **kw):
                 res = obj()
                 self.method2()
                 return res
             return wrapper
         return obj

rawDescription: Specifying an exit function for an abstract function


rawDescription: how could I pass a collection of the arguments that a function needed?

description: How could I pass a collection of the arguments that a function needed


code:
def iter_starting_at(start_pos, string):
    for i in range(start_pos, len(string)):
        yield string[i]

for character in iter_starting_at(start_pos, my_string):
    print character

rawDescription: Iterate through python string starting at index


code:
class patricia():
    def __init__(self):
        self._data = {}

    def addWord(self, word):
        data = self._data
        i = 0
        while 1:
            try:
                node = data[word[i:i+1]]
            except KeyError:
                if data:
                    data[word[i:i+1]] = [word[i+1:],{}]
                else:
                    if word[i:i+1] == '':
                        return
                    else:
                        if i != 0:
                            data[''] = ['',{}]
                        data[word[i:i+1]] = [word[i+1:],{}]
                return

            i += 1
            if word.startswith(node[0],i):
                if len(word[i:]) == len(node[0]):
                    if node[1]:
                        try:
                            node[1]['']
                        except KeyError:
                            data = node[1]
                            data[''] = ['',{}]
                    return
                else:
                    i += len(node[0])
                    data = node[1]
            else:
                ii = i
                j = 0
                while ii != len(word) and j != len(node[0]) and \
                      word[ii:ii+1] == node[0][j:j+1]:
                    ii += 1
                    j += 1
                tmpdata = {}
                tmpdata[node[0][j:j+1]] = [node[0][j+1:],node[1]]
                tmpdata[word[ii:ii+1]] = [word[ii+1:],{}]
                data[word[i-1:i]] = [node[0][:j],tmpdata]
                return

    def isWord(self,word):
        data = self._data
        i = 0
        while 1:
            try:
                node = data[word[i:i+1]]
            except KeyError:
                return False
            i += 1
            if word.startswith(node[0],i):
                if len(word[i:]) == len(node[0]):
                    if node[1]:
                        try:
                            node[1]['']
                        except KeyError:
                            return False
                    return True
                else:
                    i += len(node[0])
                    data = node[1]
            else:
                return False

    def isPrefix(self,word):
        data = self._data
        i = 0
        wordlen = len(word)
        while 1:
            try:
                node = data[word[i:i+1]]
            except KeyError:
                return False
            i += 1
            if word.startswith(node[0][:wordlen-i],i):
                if wordlen - i > len(node[0]):
                    i += len(node[0])
                    data = node[1]
                else:
                    return True
            else:
                return False

    def removeWord(self,word):
        data = self._data
        i = 0
        while 1:
            try:
                node = data[word[i:i+1]]
            except KeyError:
                print "Word is not in trie."
                return
            i += 1
            if word.startswith(node[0],i):
                if len(word[i:]) == len(node[0]):
                    if node[1]:
                        try:
                            node[1]['']
                            node[1].pop('')
                        except KeyError:
                            print "Word is not in trie."
                        return
                    data.pop(word[i-1:i])
                    return
                else:
                    i += len(node[0])
                    data = node[1]
            else:
                print "Word is not in trie."
                return

    __getitem__ = isWord

rawDescription: Implementing a Patricia Trie for use as a dictionary


code:
from types import MethodType

def func(*x):
    print('func:', x)

class ABC:
    def __init__(self, f):
        self.f1 = MethodType(f, self, self.__class__)

    def f2(*x):
        print('f2:', x)

if __name__ == '__main__':
    a = ABC(func)
    print a.f1(10)
    print a.f2(10)
    a.f3 = MethodType(func, a, ABC)
    print a.f3(10)

rawDescription: Python: calling a function as a method of a class


code:
foo = Foo({'X':1, 'Y':2, 'Z':3})
for elem in foo:
    print elem

rawDescription: Iterate over unknown object attributes in Python


code:
class toy(object):
    pass

a = toy()
a.key1 = "hello world"
print a.key10

rawDescription: An approach to address html contents in a python class


code:
im = np.arange(81).reshape(9,9)
print np.swapaxes(im.reshape(3,3,3,-1),1,2)

rawDescription: Find a 3x3 sliding window over an image

description: Find a 3x3 sliding window over an image


code:
from argparse import ArgumentParser

parser = ArgumentParser(description="Tool to keep archiving tar files")
sub = parser.add_subparsers(dest='action')
sp1 = sub.add_parser('start')
sp2 = sub.add_parser('stop')
sp3 = sub.add_parser('list')
#parser.add_argument("-a", "--action", dest="action", choices=("start", "stop", "list"), help="start/stop/list the directories to be monitored", default="list", required=True)
for sp in [sp1,sp2]:
    sp.add_argument("-t", "--type", dest="type", choices=("a", "b"), help="Type of spooler job", default=None)
    sp.add_argument("-p", "--path", dest="path", help="Absolute path of the directory to be monitored", default=None)
    sp.add_argument("-c", "--codeline", dest="codeline", choices=("x","y","z"), default=None, required=True)
    sp.add_argument("-r", "--release", dest="release", help="Directory path gets assigned automatically based on the release", default=None)

for astr in [
    'list',
    'start -t a -p /tmp -c x',
    'start -t b -r rr -c y',
    'start']:
    print parser.parse_args(astr.split())

rawDescription: How to group command-line arguments in python?

description: Group command-line arguments in python


code:
some_dictionary = {'FIRST' : ['a', '1', 'b', '2'],
                   'SECOND' : ['c', 'd', '3', 'e'],
                   'THIRD' : ['4', '5', 'f', 'g6']}

amount_of_numbers = []

for value in some_dictionary.values():
    amount_of_numbers += [string for string in value if all(char.isdigit() for char in string)]

print amount_of_numbers
['3', '4', '5', '1', '2']

rawDescription: How to count the numbers in values in a dictionary

description: Count the numbers in values in a dictionary


code:
def print_dict_rec( indict ):
    for majorkey, subdict in indict.iteritems():
         if type(subdict) == dict:
            print majorkey
            print_dict_rec(subdict)
         else:
            print majorkey, subdict

print_dict_rec(ourResult)

rawDescription: Write a loop that parses json dictionaries using python


code: print nodes[0]

rawDescription: using python in maya do for-loop through selected nodes

description: Using python in maya do for-loop through selected nodes


code:
import os
import your_module

# Get directory of your module
print os.path.dirname(your_module.__file__)

rawDescription: get the path of a module in python

description: Get the path of a module in python


code:
@app.task
def test(x):
    import time
    time.sleep(1)
    print x
    if x == 5:
        return x
    else:
        return test.delay(x+1)

rawDescription: celery issuing tasks from subtasks

description: Celery issuing tasks from subtasks


code:
from random import sample
print sample(s, 3)
# ['E', 'C', 'A']

rawDescription: Statistical counting in Python

description: Statistical counting in Python


code:
import numpy as np
import math
import timeit

def v(x):
    return math.exp(x)

def makeS1(N, x_range):
    vec = np.full(N, 2 * v(x_range[1]))
    vec[0] *= 0.5
    S = np.diag(vec)
    vec = np.full(N - 1, v(x_range[0]))
    S += np.diag(vec, 1)
    for m in xrange(1, N):
        vec = np.full(N - m, 2 * v(x_range[m + 1]))
        vec[0] *= 0.5
        S += np.diag(vec, -m)
    return S

def makeS2(N, x_range):
    values = np.array([v(x) for x in x_range])
    values_doubled = 2 * values

    def value_at_position(ai, aj):
        result = np.zeros((N, N))
        for i, j in zip(ai.flatten(), aj.flatten()):
            if j > i + 1:
                continue
            elif j == i + 1:
                result[i, j] = values[0]
            elif j == 0:
                result[i, j] = values[i + 1]
            else:
                result[i, j] = values_doubled[i - j + 1]
        return result

    return np.fromfunction(value_at_position, (N, N))

def makeS3(N, x_range):
    values = np.array([v(x) for x in x_range])
    values_doubled = 2 * values
    result = np.zeros((N, N))
    for i in xrange(N):
        for j in xrange(min(i + 2, N)):
            if j == i + 1:
                result[i, j] = values[0]
            elif j == 0:
                result[i, j] = values[i + 1]
            else:
                result[i, j] = values_doubled[i - j + 1]
    return result

def makeS4(N, x_range):
    values = np.array([v(x) for x in x_range])
    values_doubled = 2 * values
    result = np.eye(N, k=1) * values[0]
    result[:, 0] = values[1:]
    for i in xrange(N - 1):
        result[i + 1, 1:i + 2] = values_doubled[1:i + 2][::-1]
    return result

def main():
    N = 2000
    x_range = np.random.randn(N + 1)

    start = timeit.default_timer()
    s1 = makeS1(N, x_range)
    print 'makeS1', timeit.default_timer() - start
    start = timeit.default_timer()
    s2 = makeS2(N, x_range)
    print 'makeS2', timeit.default_timer() - start
    start = timeit.default_timer()
    s3 = makeS3(N, x_range)
    print 'makeS3', timeit.default_timer() - start
    start = timeit.default_timer()
    s4 = makeS4(N, x_range)
    print 'makeS4', timeit.default_timer() - start
    if N < 10:
        print s1
        print s2
        print s2
        print s4
    assert np.allclose(s1, s2)
    assert np.allclose(s2, s3)
    assert np.allclose(s3, s4)

main()

rawDescription: Efficient way to create a dense matrix from diagonal vectors in Python?


code:
import urllib2
import io
import gzip

open_url = urllib2.urlopen("http://www.elegantthemes.com/gallery/")
site_html = open_url.read()
bi = io.BytesIO(site_html)
gf = gzip.GzipFile(fileobj=bi, mode="rb")
s = gf.read()
print s[50:]

rawDescription: Strange Output from Python urllib2

description: Strange Output from Python urllib2


code:
import re
import mechanize

bs = mechanize.Browser()
server = raw_input("IP to retry: ")

response = bs.open("http://" + server + "/avicapture.html")
assert bs.viewing_html()
bs.select_form(name="avistatus_form")

matches = re.findall(
    r'(?s)<!--\$FREETEXT\|AVI_STATUS_END_TIME([0-9]+).*?<td>\s*([0-9/]+ [0-9:]+)\s*\n',
    response.read())
latest_id, latest_time = max(matches, key=lambda m: m[1])
form = bs.form
bs.find_control("AVI_STATUS_ACTION").items[1].selected = True
bs.find_control("avistatuscheck" + latest_id).items[0].selected = True

print "Sending retry signal."
bs.submit()
print server+" Retried!"

rawDescription: Determining which line in an html table to manipulate with mechanize


code:
import calendar
import datetime
now = datetime.datetime.now()
print calendar.monthrange(now.year, now.month)[1]

rawDescription: How to find number of days in the current month

description: Find number of days in the current month


code: print tester is hand  #should return `True`

rawDescription: Unsure why dictionary is mutating

description: Unsure why dictionary is mutating


code:
def collide_top(a, b):
    return a.top <= b.bottom <= a.bottom and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_bottom(a, b):
    return a.bottom >= b.top >= a.top and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_left(a, b):
    return a.left <= b.right <= a.right and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)
def collide_right(a, b):
    return a.right >= b.left >= a.left and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

center = Rect((100, 100, 100, 100))
player = Rect((10, 0, 75, 75))

move = {K_UP:    ( 0, -1),
        K_DOWN:  ( 0,  1),
        K_LEFT:  (-1,  0),
        K_RIGHT: ( 1,  0)}

while True:
    screen.fill((0, 0 ,0))
    pressed = pygame.key.get_pressed()
    for d in [m for (k, m) in move.items() if pressed[k]]:
      player.move_ip(*d)
    pygame.draw.rect(screen, (120, 0, 120), center, 3)
    pygame.draw.rect(screen, (0, 200, 55), player, 2)
    # check if 'player' collides with the bottom of 'center'
    print collide_bottom(center, player)
    pygame.display.flip()
    if pygame.event.get(QUIT): break
    pygame.event.poll()
    clock.tick(60)

rawDescription: How to assign and test for attributes on a rect in Pygame

description: Assign and test for attributes on a rect in Pygame


code:
import socket, json

def socket_to_file(sock):
    try:
        sock.settimeout(15)
        return sock.makefile()
    finally:
        sock.close()

if __name__ == '__main__':
    sock = socket.create_connection(('localhost', 3005))
    sock = socket_to_file(sock)
    try:
        request = {
            'param0': True,
            'param2': 'sztringecske',
        }
        print 'Sending request: %s' % (request,)
        sock.write(json.dumps(request))
        sock.write('\n')
        sock.flush()    # important!!!
        response = json.loads(sock.readline())
        print 'Received response: %s' % (response,)
    finally:
        sock.close()

rawDescription: Python working with sockets the method recv


code:
def capital(uinput):
    print "".join([chr(ord(i) - 32) for i in uinput[:4]])

rawDescription: How do i get the output in one line as a string?

description: Get the output in one line as a string


code:
for res in genDatePeriods('2014-01-15', '2015-02-03'):
    print res

rawDescription: Generate date ranges broken by month for a given period


code:
class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()

        while True:
            print "\n--------"
            next_scene_name = current_scene.enter()  # returns next scene key
            current_scene = self.scene_map.next_scene(next_scene_name)  # initiates next scene and sets it as `current_scene`

rawDescription: Can somebody explain this short python method


code:
from collections import defaultdict
origin_x = 0.0
origin_y = 0.0

P = [(0,1),(1,0),(1,0)]
k = 2

xmid = float(sum(P[0]))/len(P)

xleft = [x for x in P[0] if x <= xmid]
xright = [x for x in P[0] if x > xmid]

Pleft = [(x,y) for x,y in P if x <= xmid ]
Pright = [(x,y) for x,y in P if x > xmid]

print Pleft

def dist(x1,y1):
    import math
    return math.sqrt((x1-origin_x)**2 + (y1-origin_y)**2)

worst = []
nearest = defaultdict(list)

for l in xrange(0,len(Pleft)):
    curr = dist(Pleft[l][0], Pleft[l][1])
    print curr
    if len(nearest) > 1:
        worst[0] = sorted(nearest.keys())[len(nearest)]

    if len(nearest) <= k:
        nearest[curr].append(Pleft[l])
    else:
        if curr < worst[0]:
            nearest[curr].append(Pleft[l])
        else:
            break
    #nearest
        #best[0] = curr
        #best[1] = (Pleft[l])

for r in xrange(0,len(Pright)):
    curr = dist(Pright[r][0],Pright[r][1])
    if len(nearest) > 1:
        worst[0] = sorted(nearest.keys())[len(nearest)-1]
    if len(nearest) <= k:
        nearest[curr].append(Pright[r])
    else:
        if curr < worst[0]:
            nearest[curr].append(Pright[r])
        else:
            break

print nearest

rawDescription: how to store lists as values in python defaultdict lists

description: Store lists as values in python defaultdict lists


code: print pd.to_datetime(df['Dates'])

rawDescription: Datetime strptime in Python pandas : what's wrong?


code:
with open('filename') as f:
    for line in f:
        line = line.rstrip().split(', ')  #split the line at ', '
        for item in line[1:]:    #iterate over slice of the list returned in the previous step
            print line[0], item  #print the first item, and the item from the loop.

rawDescription: Output file formatting and rearrangement


code:
A = [1, 2, 3, 4]
B = [10, 20, 30, 40]
C = [100, 200]
D = [1000, 2000]

from itertools import product, chain
for row in product(zip(A, B), zip(C, D)):
    print list(chain(*row))

rawDescription: Python: pairing up element from one list with every single element from other list


code:
import socket
from time import sleep

class ClientObject:

    def __init__(self,host_address,server_port,port = 0):

        self._server = (host_address,server_port)
        self._s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._s.bind((host_address,port))

    def handshake(self):

        print ' sending marco'

        self._s.sendto('marco',self._server)
        sleep(.1)
        self._s.sendto('marco',self._server)

        while True:
            if str(self._s.recvfrom(1024)[0]) == 'polo':
                break

        #self._s.sendto('marco',self._server)
        #self._s.sendto('marco',self._server)

        print ' connection verified'
        self._s.sendto('confirm',self._server)

        self._s.setblocking(0)

        return True

    def recieve(self,mode = 0):

        _data, _addr = self._s.recvfrom(1024)

        if mode == 0:
            return str(_data)
        if mode == 1:
            return int(_data)
        if mode == 2:
            return float(_data)
        if mode == 3:
            return tuple(_data)

    def send(self,data):
        self._s.sendto(str(data),self._server)

    def close(self):
        self._s.close()
        print '_socket closed_'

if __name__ == '__main__':

    host = '127.0.0.1'
    port = 0

    talk = ClientObject(host,24603,port)
    talk.handshake()

    #while True:
        #print talk.recieve()

rawDescription: How to make multiple python programs communicate in this situation?

description: Make multiple python programs communicate in this situation


code:
class A(object):
    def performProfile(self):
        import cProfile
        cProfile.runctx("self.profileCommand(100)", globals(),locals())

    def profileCommand(self, a):
        for i in xrange(a):
            pass
        print "end."

A().performProfile()

rawDescription: Profiling self and arguments in python?

description: Profiling self and arguments in python


code:
print chr(0xE2) + chr(0x98) + chr(0x85)
#prints ★

rawDescription: Counterpart to Python's chr() in JavaScript


code:
from itertools import product

d = {'key1': ['str0','str1','str2','strn'], 'key2': ['apples','bananas','mangos'], 'key3': ['spam','eggs','more spam']}

foo = [[(key, value) for value in d[key]] for key in sorted(d.keys())]

results = product(*foo)
for result in results:
    for key, value in result:
        print key + '.' + value,
    print

rawDescription: creating n nested loops from a dictionary of lists

description: Creating n nested loops from a dictionary of lists


code:
def closeEvent(self, event):
    reply = QtGui.QMessageBox.question(self, 'Message', "Are you sure to quit?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
    if reply == QtGui.QMessageBox.Yes:
        print "ByeBye"
        QtGui.QApplication.quit()
        event.accept()
    else:
        event.ignore()

rawDescription: PyQt4 WindowFlags don't close program

description: PyQt4 WindowFlags don't close program


rawDescription: Delete Data from a pandas array that is out of range


code:
sDate = "01/05/2014"
iYear = int(sDate.split("/")[-1])
print type(iYear), iYear

rawDescription: month/day/year conversion to just year with python or VB Script

description: Month/day/year conversion to just year with python or VB Script


code: print [filter(lambda x: len(x) >= 3, clist) for clist in lists]

rawDescription: Removing small words in python from nested lists


rawDescription: How to do a running sum in python?

description: Do a running sum in python


code:
#get max count of years => loops
maxYears = (df['maturity'].max() - pd.to_datetime(d)) / np.timedelta64(1, 'D') / (365.25)
print maxYears
2.24229979466

#convert float to int,  if 2.999 => 2, so one year is added
#rather add one more year (leap years, year is only estimated)
maxYears = int(maxYears) + 2
print maxYears
4

rawDescription: Subtracting years pandas dataframe and adding them to a matrix


code:
for i, e in enumerate([1, 3, 3]):
    print "index=%d, element=%s" % (i, e)

# reverse keys and values in a dictionary
d = dict((v, k) for k, v in adict.items()) # or
d = dict(zip(adict.values(), adict.keys()))

rawDescription: Is it pythonic for a function to return multiple values?


code:
import networkx as nx

# Directed Network
D = nx.DiGraph()
D.add_weighted_edges_from([('A', 'B', 0.5), ('A', 'C', 1)])

# Convert to undirected
G = D.to_undirected()

# Default max number of iterations failed to converge for me
print nx.pagerank(G, max_iter=200)

# Outputs:
{'A': 0.48648648872844047, 'C': 0.32567567418103965, 'B': 0.18783783709051982}

rawDescription: Textrank: complementing pagerank for sentence extraction using networkx


code:
from django.contrib.auth.forms import UserCreationForm
from django import forms

class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)

    def __init__(self, *args, **kwargs):
        super(UserCreateForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

print UserCreateForm()

rawDescription: Removing help_text from Django UserCreateForm


code:
xml = """

Content

Content I Want

"""
from BeautifulSoup import BeautifulSoup
p = BeautifulSoup(xml)

# returns a list of texts
print p.div.div.findNextSibling().div.contents
# returns a list of texts
print p.div.div.findNextSibling().div(text=True)
# join (and strip) the values
print ''.join(s.strip() for s in p.div.div.findNextSibling().div(text=True))

rawDescription: Select specific child elements with BeautifulSoup


code:
for base in (obj.__class__,) + obj.__class__.__bases__:
  print "obj depends on module %s" % base.__module__

rawDescription: How can I capture dependancies used by a subset of code in a python source file?

description: Capture dependancies used by a subset of code in a python source file


code:
import cv2
import numpy as np

def getLandmarks(corners):
    holes=[]
    for i in range(0,len(corners)):
        for j in range(i+1,len(corners)):
            x1,y1=corners[i].ravel()
            x2,y2=corners[j].ravel()
            if abs(x1-x2)<=30 and abs(y1-y2)<=30:
                holes.append((int((x1+x2)/2),int((y1+y2)/2)))
    return holes

# lodes in img

img = cv2.imread('img.png', cv2.IMREAD_COLOR)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

corners = cv2.goodFeaturesToTrack(img_gray, 200, 0.05, 10)

holes=getLandmarks(corners)
print len(holes)
for corner in holes:
    cv2.circle(img, (corner), 7, (255,255,0), -1)

cv2.imshow('img',img)
cv2.waitKey(0)

rawDescription: Detect holes, ends and beginnings of a line using openCV?


code:
print result_squares.get(timeout=1)
print result_cubes.get(timeout=1)

rawDescription: Mulitprocess Pools with different functions


code:
import time
import requests
import requests.auth
import praw

username = 'myusernamehere'
userAgent = "MyAppName/0.1 by " + username
clientId = 'myClientId'
clientSecret = "myClientSecret"
password = "passwordformyusernamehere"

def getPraw():
  return praw.Reddit(user_agent=userAgent, client_id=clientId, client_secret=clientSecret)

global accessToken
accessToken = None

def getAccessToken():
  client_auth = requests.auth.HTTPBasicAuth(clientId, clientSecret)
  post_data = {"grant_type": "password", "username": username, "password": password}
  headers = {"User-Agent": userAgent}
  response = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, data=post_data, headers=headers)
  return response.json()

def makeRequest(apiUrl, useGet=True):
  global accessToken
  if accessToken is None:
    accessToken = getAccessToken()
  headers = {"Authorization": "bearer "  + accessToken['access_token'], "User-Agent": userAgent}
  if useGet:
    response = requests.get(apiUrl, headers=headers)
  else:
    response = requests.post(apiUrl, headers=headers)
  time.sleep(1.1)
  responseJson = response.json()
  if 'error' in responseJson:
    if responseJson['error'] == 401:
      print "Refreshing access token"
      time.sleep(1.1)
      accessToken = getAccessToken()
      headers = {"Authorization": "bearer "  + accessToken['access_token'], "User-Agent": userAgent}
      time.sleep(1.1)
      response = requests.get(apiUrl, headers=headers)
      responseJson = response.json()
  return responseJson

global prawReddit
prawReddit = praw.Reddit(user_agent=userAgent, client_id=clientId, client_secret=clientSecret)

# Gets any number of posts
def getPosts(subredditName, numPosts=1000):
  global prawReddit
  subreddit = prawReddit.get_subreddit(subredditName)

  postGetter = praw.helpers.submissions_between(prawReddit, subreddit)

  postArray = []
  numGotten = 0
  while numGotten < numPosts:
    postArray.append(postGetter.next())
    numGotten += 1

  return postArray

# Get all comments from a post
# Submission is a praw submission, obtained via:
# r = redApi.getPraw()
# submission = r.get_submission(submission_id='2zysz7') # (or some other submission id, found via https://www.reddit.com/r/test/comments/2zysz7/ayy/ - the thing after /comments/)
# comments = redApi.getComments(submission)
def getComments(submission):
  requestUrl = 'https://oauth.reddit.com/' + submission.subreddit.url + 'comments/article?&limit=1000&showmore=true&article=' + submission.id
  allData = makeRequest(requestUrl)
  articleData = allData[0]
  comments = allData[1]
  curComments = comments['data']['children']

  resultComments = getCommentsHelper(curComments, submission.name, submission)

  return resultComments

# Print out the tree of comments
def printTree(comments):
  return printTreeHelper(comments, "")

def printTreeHelper(comments, curIndentation):
  resultString = ""
  for comment in comments:
    resultString += curIndentation + comment['data']['body'].replace("\n", "\n" + curIndentation) + "\n"
    if not comment['data']['replies'] == "":
      resultString += printTreeHelper(comment['data']['replies']['data']['children'], curIndentation + "  ")
  return resultString

# Get all comments as a single array
def flattenTree(comments):
  allComments = []
  for comment in comments:
    allComments.append(comment)
    if not comment['data']['replies'] == "":
      allComments += flattenTree(comment['data']['replies']['data']['children'])
  return allComments

# Utility functions for getComments
def expandCommentList(commentList, submission):

  curComments = commentList
  allComments = {}
  while True:
    thingsToExpand = []
    nextComments = []
    allParents = {}
    for comment in curComments:
      if comment['kind'] == "more":
        thingsToExpand += comment['data']['children']
      else:
        if comment['data']['body'][:len("If they are shipping")] == "If they are shipping":
          print comment
        allComments[comment['data']['name']] = comment

    if len(thingsToExpand) == 0:
      curComments = []
      break

    curComments = []
    if not len(thingsToExpand) == 0:
      print "total things to expand: " + str(len(thingsToExpand))
      for i in range(0, len(thingsToExpand)/100+1):
        curCommentIds = thingsToExpand[i*100:min((i+1)*100, len(thingsToExpand))]
        requestUrl = 'https://oauth.reddit.com/api/morechildren.json?api_type=json&link_id=' + submission.name + '&limit=1000&showmore=true&children=' + ",".join(curCommentIds)
        curData = makeRequest(requestUrl)
        if 'json' in curData and 'data' in curData['json']:
          curComments += curData['json']['data']['things']
        print (i+1)*100

  for comment in curComments:
    allComments[comment['data']['name']] = comment

  return allComments.values()

def lookForMore(comment):
  if comment['kind'] == "more":
    return True
  if not comment['data']['replies'] == "":
    for reply in comment['data']['replies']['data']['children']:
      if lookForMore(reply):
        return True
  return False

def getCommentsHelper(curComments, rootId, submission):

  allComments = expandCommentList(curComments, submission)

  commentMap = {}
  for comment in allComments:
    commentMap[comment['data']['name']] = comment

  allRootComments = []
  for comment in allComments:
    if comment['data']['parent_id'] == rootId:
      allRootComments.append(comment)
    elif comment['data']['parent_id'] in commentMap:
      parentComment = commentMap[comment['data']['parent_id']]
      if parentComment['data']['replies'] == "":
        parentComment['data']['replies'] = {'data': {'children': []}}
      alreadyChild = False
      for childComment in parentComment['data']['replies']['data']['children']:
        if childComment['data']['name'] == comment['data']['name']:
          alreadyChild = True
          break
      if not alreadyChild:
        parentComment['data']['replies']['data']['children'].append(comment)
    else:
      print "pls halp"

  completedComments = []
  needMoreComments = []

  for comment in allRootComments:
    if not comment['data']['replies'] == "" or comment['kind'] == 'more':
      hasMore = lookForMore(comment)

      if hasMore:
        needMoreComments.append(comment)
      else:
        replyComments = getCommentsHelper(comment['data']['replies']['data']['children'], comment['data']['name'], submission)
        comment['data']['replies']['data']['children'] = replyComments
        completedComments.append(comment)
    else:
      completedComments.append(comment)
  for comment in needMoreComments:
    requestUrl = 'https://oauth.reddit.com/' + submission.subreddit.url + 'comments/article?&limit=1000&showmore=true&article=' + submission.id + "&comment=" + comment['data']['id']
    allData = makeRequest(requestUrl)
    articleData = allData[0]
    comment = allData[1]['data']['children'][0]
    if comment['data']['replies'] == "":
      completedComments.append(comment)
    else:
      comments = comment['data']['replies']['data']['children']
      actualComments = getCommentsHelper(comments, comment['data']['name'], submission)
      comment['data']['replies']['data']['children'] = actualComments
      completedComments.append(comment)

  return completedComments

rawDescription: Get all comments from a specific reddit thread in python


code:
def window(inputlist, index):
    return inputlist[max(0, index - 2):index + 3]

for index, elem in enumerate(inputlist):
    print window(inputlist, index)

rawDescription: Elegant way to access last two and next two elements in a list?


code:
inputs = [float(x.strip()) for x in raw_input("Enter values: ").split(",")]
results = [x / 1e4 for x in inputs]
print "RESULT: " + ", ".join(str(x) for x in results)

rawDescription: Process multiple input values in Python

description: Process multiple input values in Python


code:
#!/usr/bin/python

def main():
    for line in sys.stdin:
        key = get_my_key(line)
        value = line
        print '{}\t{}'.format(key, value)

if __name__ == "__main__":
    main()

rawDescription: Map Reduce multiple outputs in python boto


code:
counts = dict()

with open("sample.txt", "r") as datafile:
    x = datafile.read().split()
    for word in x:
        words = word.split()
        print words
        counts[word] = counts.get(word,0) + 1
print counts

rawDescription: Split file and turn it into dictionary in python


code:
import os

def getaudiodevices():
    devices = os.popen("arecord -l")
    device_string = devices.read()
    device_string = device_string.split("\n")
    for line in device_string:
            if(line.find("card") != -1):
                print "hw:" + line[line.find("card")+5] + "," +\
 line[line.find("device")+7]

rawDescription: Getting list of audio Input devices in Python


code:
if 'exists_method' in globals():
    print 'Method found!'

rawDescription: __getattr__ within a module in python

description: __getattr__ within a module in python


code:
class A(object):
    class_var = [] # make a list attached to the A *class*
    def __init__(self):
        self.instance_var = [] # make a list attached to any *instance* of A

print 'class var:', A.class_var # prints []
# print 'instance var:', A.instance_var # This would raise an AttributeError!

print

a = A() # Make an instance of the A class
print 'class var:', a.class_var # prints []
print 'instance var:', a.instance_var # prints []

print

# Now let's modify both variables
a.class_var.append(1)
a.instance_var.append(1)
print 'appended 1 to each list'
print 'class var:', a.class_var # prints [1]
print 'instance var:', a.instance_var # prints [1]

print

# So far so good. Let's make a new object...
b = A()
print 'made new object'
print 'class var:', b.class_var # prints [1], because this is the list bound to the class itself
print 'instance var:', b.instance_var # prints [], because this is the new list bound to the new object, b

print

b.class_var.append(1)
b.instance_var.append(1)
print 'class var:', b.class_var # prints [1, 1]
print 'instance var:', b.instance_var # prints [1]

rawDescription: Creating new object in python is not returning a new object


code:
import csv
import re

csv_data = list(csv.reader(open('/home/jon/tmp/data.csv'))) # (1)
csv_text = '\n' + '\n'.join('{0} : {1}'.format(*row) for row in csv_data) # (2)

with open('/home/jon/tmp/other.ldif') as f:
    contents = f.read() # (3)
    print re.sub(r'(\n\n)|(\n$)', csv_text + '\n\n', contents) # (4)

rawDescription: Python ldif injection and csv reading script


code:
def execSp(*args):
  AV = []
  SQL = "exec SP_TEST(";
  for ii in range(0,4) :
    AV.append("NULL");
  ii = 0;

  for a in args:
    AV[ii] = str(a);
    ii+=1;

  SQL = SQL + "\'" + AV[0] + "\'," + AV[1] + "," + AV[2] + "," + AV[3] + ")";
  print SQL

execSp("hello", 1, 2, 3);
execSp("hi", 2, 3);

rawDescription: iterate over function arguments and retain sort order in python

description: Iterate over function arguments and retain sort order in python


code:
my_param = cgi.getfirst('a')

print "Content-Type: text/html\n"
print my_param

rawDescription: POST data to Python CGI script via jQuery AJAX


code:
def unstuff(data):
    i = iter(data)
    dic = {'\xDC' : '\xFC', '\xDD' : '\xFD', '\xFE' : '\xDE'}
    while True:
        d = i.next()  # throws StopIteration on the end
        if d == '\xFE':
            d2 = i.next()
            if d2 in dic:
                yield dic[d2]
            else:
                yield '\xFE'
                yield d2
        else:
            yield d

def stuff(data):
    i = iter(data)
    dic = { '\xFC' : '\xDC', '\xFD' : '\xDD', '\xFE' : '\xDE' }
    while True:
        d = i.next() # throws StopIteration on the end
        if d in dic:
            yield '\xFE'
            yield dic[d]
        else:
            yield d

def main():
    s = 'hello\xFE\xDCWorld'
    unstuffed = "".join(unstuff(s))
    stuffed = "".join(stuff(unstuffed))
    print s, unstuffed, stuffed

    # also possible
    for c in unstuff(s):
        print ord(c)

if __name__ == '__main__':
    main()

rawDescription: Octet (byte) stuffing and unstuffing, i.e. replacing one byte with two or v.v


code:
def func(x,y):
    return cos(x) + cos(y)

def func2(y, a, b):
    return integrate.quad(func, a, b, args=(y,))[0]

print integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0]

rawDescription: 2D integrals in SciPy

description: 2D integrals in SciPy


rawDescription: How to check if list element is present in array in python

description: Check if list element is present in array in python


code:
x = int('600')

# x is now 600, can be used in computations
print x + 1  # No TypeError--prints 601

rawDescription: Text file number to Python number how?

description: Text file number to Python number how


code:
x="""car - superb
company - skoda simply clever
manufactured - 1990
car - sclass
company - mercedes the best or nothing
manufactured - 1990
car - rapid
company - skoda simply clever
manufactured - 1990"""
temp="skoda"
print re.findall(r"car\s+-(?:(?!\bcar\b)[\s\S])*"+temp+r"(?:(?!\bcar\b)[\s\S])*",x)

rawDescription: using regex for text matching a string

description: Using regex for text matching a string


code:
for k in board:
    if k == 5:
        print'\n\n',
    elif k == 4:
        cprint(' TW', 'red', attrs=[], end = ' ')
    #print 'TW',
    elif k == 3:
        cprint(' DW', 'magenta', attrs=[], end = ' ')
    #print 'DW',
    elif k == 2:
        cprint(' TL', 'blue', attrs=[], end = ' ')
    #print 'TL',
    elif k == 1:
        cprint(' DL', 'cyan', attrs=[], end = ' ')
    #print 'DL',
    elif k == 0:
        print '___',

rawDescription: How would I create a text-based board for a scrabble game in python?


code:
import fileinput
for line in fileinput.FileInput(fileinput,inplace=1):
        print  line.replace('None',"").rstrip() # remove newline character to avoid adding extra lines in the output

rawDescription: Removing lines from a csv with Python also adds an extra line


code:
import wx
import  wx.lib.newevent
from ObjectListView import ObjectListView, ColumnDefn, OLVEvent

OvlCheckEvent, EVT_OVL_CHECK_EVENT = wx.lib.newevent.NewEvent()

class MyOvl(ObjectListView):
    def SetCheckState(self, modelObject, state):
        """
        This is the same code, just added the event inside
        """
        if self.checkStateColumn is None:
            return None
        else:
            r = self.checkStateColumn.SetCheckState(modelObject, state)

            # Just added the event here ===================================
            e = OvlCheckEvent(object=modelObject, value=state)
            wx.PostEvent(self, e)
            # =============================================================

            return r

    def _HandleLeftDownOnImage(self, rowIndex, subItemIndex):
        """
        This is the same code, just added the event inside
        """
        column = self.columns[subItemIndex]
        if not column.HasCheckState():
            return

        self._PossibleFinishCellEdit()
        modelObject = self.GetObjectAt(rowIndex)
        if modelObject is not None:
            column.SetCheckState(modelObject, not column.GetCheckState(modelObject))

            # Just added the event here ===================================
            e = OvlCheckEvent(object=modelObject, value=column.GetCheckState(modelObject))
            wx.PostEvent(self, e)
            # =============================================================

            self.RefreshIndex(rowIndex, modelObject)

########################################################################
class Book(object):
    """
    Model of the Book object

    Contains the following attributes:
    'ISBN', 'Author', 'Manufacturer', 'Title'
    """
    #----------------------------------------------------------------------
    def __init__(self, title, author, isbn, mfg):
        self.isbn = isbn
        self.author = author
        self.mfg = mfg
        self.title = title

########################################################################
class MainPanel(wx.Panel):
    #----------------------------------------------------------------------
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
        self.products = [Book("wxPython in Action", "Robin Dunn",
                              "1932394621", "Manning"),
                         Book("Hello World", "Warren and Carter Sande",
                              "1933988495", "Manning")
                         ]

        self.dataOlv = MyOvl(self, wx.ID_ANY, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.setBooks()
        self.dataOlv.CreateCheckStateColumn()
        self.dataOlv.Bind(EVT_OVL_CHECK_EVENT, self.HandleCheckbox)

        # Allow the cell values to be edited when double-clicked
        self.dataOlv.cellEditMode = ObjectListView.CELLEDIT_SINGLECLICK

        # create an update button
        updateBtn = wx.Button(self, wx.ID_ANY, "Update OLV")
        updateBtn.Bind(wx.EVT_BUTTON, self.updateControl)

        # Create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)

        mainSizer.Add(self.dataOlv, 1, wx.ALL|wx.EXPAND, 5)
        mainSizer.Add(updateBtn, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(mainSizer)

    def HandleCheckbox(self, e):
        print(e.object.title, e.value)

    #----------------------------------------------------------------------
    def updateControl(self, event):
        """

        """
        print "updating..."
        product_dict = [Book("Core Python Programming", "Wesley Chun",
                         "0132269937", "Prentice Hall"),
                        Book("Python Programming for the Absolute Beginner",
                         "Michael Dawson", "1598631128", "Course Technology"),
                        Book("Learning Python", "Mark Lutz",
                         "0596513984", "O'Reilly")
                        ]
        data = self.products + product_dict
        self.dataOlv.SetObjects(data)

    #----------------------------------------------------------------------
    def setBooks(self, data=None):
        self.dataOlv.SetColumns([
            ColumnDefn("Title", "left", 220, "title"),
            ColumnDefn("Author", "left", 200, "author"),
            ColumnDefn("ISBN", "right", 100, "isbn"),
            ColumnDefn("Mfg", "left", 180, "mfg")
        ])

        self.dataOlv.SetObjects(self.products)

########################################################################
class MainFrame(wx.Frame):
    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY,
                          title="ObjectListView Demo", size=(800,600))
        panel = MainPanel(self)

########################################################################
class GenApp(wx.App):

    #----------------------------------------------------------------------
    def __init__(self, redirect=False, filename=None):
        wx.App.__init__(self, redirect, filename)

    #----------------------------------------------------------------------
    def OnInit(self):
        # create frame here
        frame = MainFrame()
        frame.Show()
        return True

#----------------------------------------------------------------------
def main():
    """
    Run the demo
    """
    app = GenApp()
    app.MainLoop()

if __name__ == "__main__":
    main()

rawDescription: Python create an event to an ObjectListView check box


code:
functions = [type, id, hex]
for result in apply_all(functions, 55):
    print result

rawDescription: How do you apply a list of lambda functions to a single element using an iterator?

description: Apply a list of lambda functions to a single element using an iterator


code:
a = ["foo", "bar", "baz"]
for i in reversed(a):
    print i

rawDescription: Traverse a list in reverse order in Python


code:
from bs4 import BeautifulSoup
import requests

xmlDict = {}

r = requests.get("http://www.site.co.uk/sitemap.xml")
xml = r.text

soup = BeautifulSoup(xml)
sitemapTags = soup.find_all("sitemap")

print "The number of sitemaps are {0}".format(len(sitemapTags))

for sitemap in sitemapTags:
    xmlDict[sitemap.findNext("loc").text] = sitemap.findNext("lastmod").text

print xmlDict

rawDescription: Parse XML Sitemap with Python

description: Parse XML Sitemap with Python


rawDescription: Do I use Merge or Join to compare two dataframes?


rawDescription: iterating dicts out of a dict of matched-length lists

description: Iterating dicts out of a dict of matched-length lists


code:
with open('text.txt') as f:
    word1 = f.readline().strip()
    word2 = f.readline().strip()

print word1, word2

# now you can compare word1 and word2 if you like

rawDescription: Reading two strings from file

description: Reading two strings from file


code:
import textwrap

from collections import OrderedDict

words = ['a', 'the', 'go', 'python']
meanings = ['meaning1', 'meaning2', 'meaning3',
            'Python is a programming language that lets you work more quickly '
            'and integrate your systems more effectively. You can learn to '
            'use Python and see almost immediate gains in productivity and '
            'lower maintenance costs.']

wrapped_meanings = ['\n'.join(textwrap.wrap(meaning)) for meaning in meanings]

dictionary = OrderedDict(zip(words, wrapped_meanings))

for word, meaning in dictionary.items():
    print word
    print meaning
    print

rawDescription: Wrap texts in table with Python

description: Wrap texts in table with Python


code:
from itertools import combinations
for c1,c2 in combinations(cList, 2):
    o= overlap(c1,c2)
    if not o is None:
        print "left: %s, right: %s, length: %s" % o

rawDescription: Python: optimizing pairwise overlaps between intervals


code:
import csv

class client(threading.Thread):
    Username_List = []
    def __init__(self, conn):
        super(client, self).__init__()
        self.conn = conn

    def run(self):
        print "Client thread started"
        data = self.conn.recv(1024)
        print "Received: {0}".format(data)
        if data in client.Username_List:
            self.send_msg("Welcome Back!")
        else:
            for cnt in threadz:
                cnt.send_msg(data)
            print("Sent new username to everyone")
            client.Username_List.append(data)
        while True:
            # dont need nothing now
            pass

    def send_msg(self,msg):
        self.conn.send(msg)

host = input("Host: ")
port = input("Port: ")

ss = socket() #AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
print "Server Opening on port: {0}".format(port)
ss.listen(2)
threadz = []
print "Begining Wait for connections"

while True:
    try:
        connection, address = ss.accept()
        print "Got ONE!"
        c = client(connection)
        print "Recevied connection from:{0} On port:{1}".format(address[0],address[1])
        c.start()
        threadz.append(c)
        print "Client appended to threadz, currently {0} threadz active".format(len(threadz))

    except IOError,KeyboardInterrupt:
        connection.close()
        print("An exception with a connected user occured")
        break

rawDescription: Client socket not receiving data correctly


code:
class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

rawDescription: Python calling method in class

description: Python calling method in class


code:
def fastFib(n, memo):
    global numCalls
    numCalls += 1
    print 'fib1 called with', n
    if not n in memo:
        memo[n] = fastFib(n-1, memo) + fastFib(n-2, memo)
    #this should be outside of the if clause:
    return memo[n] #<<<<<< THIS

rawDescription: Memoization fibonacci algorithm in python


code:
json_str_improper = '''
{
    "publisher": "\"O'Reilly Media, Inc.\""
}
'''
print json_str_improper
json.loads(json_str_improper)

rawDescription: Python breaks parsing json with characters \"


code:
from PyQt4 import QtCore
from PyQt4 import QtGui

OFFSET_Y = 15
OFFSET_X = 5
SPACER_Y = 20
SPACER_X = 50
switch = [1.0, 2.0, 3.0, 6.0, 9.0, 12.0, 18.0]

class MainWindow(QtGui.QMainWindow):

    sliderUpdate = QtCore.SIGNAL('sliderUpdate()')

    def __init__(self):
        super(MainWindow, self).__init__()
        sdlg = SliderDialog(self, 5)
        self.connect(sdlg, QtCore.SIGNAL('sliderUpdate'), self.scalers)
        sdlg.show()

    def scalers(self) :
        print "In scalers of MainWindow!"

class SliderDialog(QtGui.QDialog) :

    sliderMoved  = QtCore.pyqtSignal()

    def __init__( self, parent, dataCount ) :
        super(SliderDialog, self).__init__(parent)

        sliderLayout = QtGui.QVBoxLayout()
        sliderLayout.addStretch()

        self.slider = []
        self.sliderLabel = []
        for i in range(dataCount) :

            s = QtGui.QSlider(QtCore.Qt.Horizontal, self)
            s.setMinimum(0)
            s.setMaximum(len(switch)-1)
            s.setTickInterval(1)
            s.setSingleStep(1)
            s.move(170, OFFSET_Y+30 + 3*SPACER_Y*i)
            s.sliderReleased.connect(self.sliderMoved)

            sl = QtGui.QLabel("Scaling to : 1.0", self)
            sl.move(5, OFFSET_Y+30 + 3*SPACER_Y*i)

            self.slider.append(s)
            self.sliderLabel.append(sl)

            sliderLayout.addWidget(self.slider[i])
            sliderLayout.addWidget(self.sliderLabel[i])

    def sliderMoved(self) :
        for i, slides in enumerate(self.slider) :
            scaler = slides.sliderPosition()
            self.sliderLabel[i].setText("Scaling to: {}".format(switch[scaler]))
            self.emit(QtCore.SIGNAL('sliderUpdate'))

if __name__ == '__main__':

    import sys

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

rawDescription: Python signals and slots between classes


code:
import pandas as pd

#parse data to dataframe df
#sep - http://stackoverflow.com/a/1546245/2901002
df = pd.read_table('test/file.txt',
                   sep = '\s\s+',
                   skiprows = 3,
                   skip_footer = 1,
                   header=None,
                   index_col=[0],
                   engine = 'python',
                   names=['i','1','2','3','TOT']
                    )
print df
df = df['TOT']
print df

rawDescription: Assigning columns to a pandas dataframe constructed from a string


code: print '\n'.join(' '.join('{:3d}'.format(n) for n in row).center(80) for row in triangle)

rawDescription: getting pascals to print in multiple rows

description: Getting pascals to print in multiple rows


code:
def genRange(start_time, end_time):
    return xrange(start_time / 10L * 10L, ((end_time / 10) + 1) * 10)

pairs = rdd.flatMap(lambda (s, e): ((r, (s, e)) for r in genRange(s, e)))
candidates = (pairs
    .join(pairs)
    .map(lambda (k, ((s1, e1), (s2, e2))): (s1, e1, s2, e2))
    .distinct())

candidates.filter(lambda (s1, e1, s2, e2): overlaps(s1, e1, s2, e2))

rawDescription: PySpark - Time Overlap for Object in RDD


code:
import time
import sys

i = 0
while True:
    print 'some output %d' % i
    sys.stdout.flush() # you need this to see the output
    time.sleep(.5)
    i += 1

rawDescription: Regarding running a script from another

description: Regarding running a script from another


code:
from apiclient.discovery import build

DEVELOPER_KEY = '<API key provided by Google>'
youtube = build('youtube', 'v3', developerKey=DEVELOPER_KEY)

ids = '9bZkp7q19f0,eHvccEXfacM'
results = youtube.videos().list(id=ids, part='snippet').execute()
for result in results.get('items', []):
    print result['id']
    print result['snippet']['description']
    print '-----'

rawDescription: Use BeautifulSoup to get youtube description?


code:
from bs4 import BeautifulSoup

html = """

"""

soup = BeautifulSoup(html)

# This tells BS to look at all the h3 tags, and find the ones that have an ID of me
# This however should not be done because IDs are supposed to be unique, so
# soup.find_all(id="me") should be used
one = soup.find_all("h3", {"id": "me"})
print one

# Same as above, if something has an ID, just use the ID
two = soup.find_all("li", {"id": "test1"})  # ids should be unique
print two

# Tells BS to look at all the li tags and find the node with a custom attribute
three = soup.find_all("li", {"custom": "test2321"})
print three

# Again ID, should have been enough
four = soup.find_all("li", {"id": "test1", "class": "tester"})
print four

# Look at ul tags, and find the one with a class attribute of "here"
four = soup.find_all("ul", {"class": "here"})
print four

rawDescription: BeautifulSoup "Scraping" using their name and their id


code:
import csv, collections, socket

d_ip = collections.defaultdict(set)

with open("report_log.csv", "r") as f_input:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    headers = next(csv_input)

    for row in csv_input:
        d_ip[row[0]].add(row[1])
        #d_ip[row[0]].append(row[1])   # if a list is preferred

with open("port_usage.csv", "wb") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(headers)
    print "%-20s %s" % (headers[0], headers[1])

    # Sort by IP address
    ip_sorted = d_ip.keys()
    ip_sorted.sort(key=lambda x: socket.inet_aton(x))

    for ip in ip_sorted:
        l_ports = list(d_ip[ip])
        l_ports.sort(key=lambda x: int(x))
        csv_output.writerow([ip, ", ".join(l_ports)])
        print "%-20s %s" % (ip, ", ".join(l_ports))

rawDescription: Python combine (Concatenate) data from multiple rows in CSV into one cell in another CSV


code:
import re
s = u"２34"
digit = re.compile(r"\d", re.U)
for d in re.findall(digit, s):
    print d,

wdigit = re.compile(u"[０-９]+")
for wd in re.findall(wdigit, s):
    print wd,

rawDescription: How to detect double-byte numbers

description: Detect double-byte numbers


code:
target_facet_name = "soggettof"

for record in json_obj["facetRecords"]:
    if record["facetName"] == target_facet_name:
        for value in record["facetValues"]:
            print value

rawDescription: Parsing a complex JSON object with Python: search a specific key/value pair


code:
import urllib2

@tornado.web.asynchronous
def getUrlRes(self, url, params, req_type):
    def urlCallBack(response):
        print "Got response {}".format(response)
        self.finish()
    self.client.fetch("http://www.google.com?" + urllib2.urlencode(params),
                      urlCallBack, method=req_type)

rawDescription: Tornado asynchttpclient results in None

description: Tornado asynchttpclient results in None


code:
import re

s = 'this-is,-toronto.-and-this-is,-boston'
t = re.sub(',-[a-z]', lambda x: x.group(0).upper(), s)
print t

rawDescription: How to convert specific character sequences in a string to upper case using Python?

description: Convert specific character sequences in a string to upper case using Python


code:
it = itertools.cycle( ['D1', 'D2', 'D3'] )

print next(it)
print next(it)
print next(it)
print next(it)
print next(it)
print next(it)

rawDescription: Writing files to directories in a round robin pattern


code:
import numpy as np
A = np.unique(np.random.randint(0, 100, 100))
B = np.random.choice(A, 10)

idxA = np.argsort(A)
sortedA = A[idxA]
idxB = np.searchsorted(sortedA, B)
pos = idxA[idxB]
print A[pos]
print B

rawDescription: Different results using numpy.in1d() with an array and with its single elements


code:
#!/usr/bin/env pytohn

with open('myFile.txt','r') as f:
    lines = readlines(f)

for line in lines:
    line = line.strip()
    start = line.find('"')
    end = line.find('"',start+1)
    data = line[start+1:end].split(',')
    data = [x.strip() for x in data]
    for x in data:
        print line[:start],x,line[end+1:]

rawDescription: Create new line based on each regex match in python


code:
import sqlite3

conn = sqlite3.connect('test.db')
try:
    conn.execute('''CREATE TABLE urbandictionary
           (SEARCH_WORD TEXT NOT NULL,
           SEARCH_STRING TEXT NOT NULL)''')
    print "Table created successfully";
except:
    pass

conn.close()

rawDescription: how save output from python to database?

description: How save output from python to database


rawDescription: Python, Numpy, and OLS

description: Python, Numpy, and OLS


code:
import time
from socket import *

for pings in range(10):
    clientSocket = socket(AF_INET, SOCK_DGRAM)
    clientSocket.settimeout(1)
    message = 'test'
    addr = ("127.0.0.1", 12000)

    start = time.time()
    clientSocket.sendto(message, addr)
    try:
        data, server = clientSocket.recvfrom(1024)
        end = time.time()
        elapsed = end - start
        print '%s %d %d' % (data, pings, elapsed)
    except timeout:
        print 'REQUEST TIMED OUT'

rawDescription: UDP Client/Server Socket in Python

description: UDP Client/Server Socket in Python


code:
import re

with open('/tmp/tgt.txt') as f:
    for line in f:
        m=re.match(r'Checked out revision (\d+)\s+(\w+)', line)
        if m:
            print m.group(1), m.group(2)

rawDescription: How do I extract information from a text file after a certain word in python or linux?

description: Extract information from a text file after a certain word in python or linux


code:
def BarGraphify1(nums):
    '''
    see http://stackoverflow.com/a/23257715/940217
    >>> BarGraphify1([1,2,3])
              *
             **
            ***
    '''
    for num in nums:
        print " {:>10}".format("*" * num)

def BarGraphify2(nums):
    '''
    >>> BarGraphify2([1,2,3])
      *
     **
    ***
    >>> BarGraphify2([1,3,2])
      *
    ***
     **
    '''
    output = []
    maxVal = max(nums)
    for n in nums:
        space = (maxVal-n)*' '
        asterisks = n*'*'
        output.append(space + asterisks)
    print '\n'.join(output)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: Bar Making - Python

description: Bar Making - Python


code:
from Tkinter import *

#-------------------------------------------

def count_monkeypatch(self, index1, index2, *args):
    args = [self._w, "count"] + ["-" + arg for arg in args] + [index1, index2]

    result = self.tk.call(*args)
    return result

Text.count = count_monkeypatch

#-------------------------------------------

def test(): # without "event"
    print "displaylines:", text.count("1.0", "end", "displaylines")
    print "lines:", text.count("1.0", "end", "lines")

#-------------------------------------------

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

Button(root, text="Count", command=test).pack()

root.mainloop()

rawDescription: Tkinter - Counting lines in a Text widget with word wrapping


code:
list1 = ['name', 'age', 'sex']
list2 = ['test', 10, 'female']
f = lambda l: ','.join(["'%s'" % str(s) for s in l])
print 'INSERT INTO (%s) VALUES (%s)' % (f(list1), f(list2))

rawDescription: related to List (want to insert into database)

description: Related to List (want to insert into database)


code:
import random

list2d = [range(0, 5), range(5, 10), range(10, 15), range(15, 20)]

for i in range(0, 10):
    random_suite = random.choice(list2d)
    random_card = random.choice(random_suite)
    print random_suite, random_card

rawDescription: How do I select a random element from a 2d list

description: Select a random element from a 2d list


code:
import collections
# Create a new sub-tuple named Credential
Credential = collections.namedtuple('Credential', 'username, password')

credential = Credential(username='joeuser', password='secret123')

print 'Username:', credential.username
print 'Password:', credential.password

rawDescription: Structure accessible by attribute name or index options


code:
import itertools
print "For n = 2: " + str(list(itertools.product(*[(0, 1)] * 2)))
print "For n = 3: " + str(list(itertools.product(*[(0, 1)] * 3)))

rawDescription: Get a list of all possible binary tuples with length n


code:
global totalBottles, totalPayout, todayBottles
totalBottles=0 #store the accumulated bottle values
counter=1 #will control the loop
todayBottles=0 #store the number of bottles returned on a day
totalPayout=0 #store the calculated value of totalBottles x.10

def main():
    global totalBottles, totalPayout, todayBottles
    keepGoing='y'

    while keepGoing =='y':
        getBottles (counter)
        calcPayout ()
        printInfo(totalBottles, totalPayout)
        keepGoing == raw_input ('Do you want to run the program again?')

def getBottles (counter):
    global totalBottles, todayBottles
    while counter <8:
        todayBottles = input ('Enter number of bottles returned for the day:')
        totalBottles = todayBottles + totalBottles
        counter=counter + 1

def calcPayout():
    global totalBottles, totalPayout, todayBottles
    totalPayout = totalBottles * .10

def printInfo(totalBottles, totalPayout):
    print totalBottles,('is the total bottles')
    print totalPayout, ('amount due')

main()

rawDescription: Python dumps variable from loop

description: Python dumps variable from loop


code:
pattern = r'([A-Z]{2,}(?=[A-Z]|$)|[A-Z][a-z]*)'
print ' '.join(re.findall(pattern, 'HDMWhoSomeMONKEYThingX'))

rawDescription: Regex divide with upper-case

description: Regex divide with upper-case


code:
import shlex, subprocess
command_line = raw_input()
args = shlex.split(command_line)
print args
p = subprocess.Popen(args) # Success!

rawDescription: Running an executable with multiple parameters in python


code:
for attr in sorted(dir(name)):
    print attr

rawDescription: How do I get a formatted list of methods from a given object?

description: Get a formatted list of methods from a given object


code:
print mat1
print mat2

rawDescription: Sparse matrix manipulation

description: Sparse matrix manipulation


code:
tags = soup('a', limit=3)

for tag in tags:
    print tag.get('href', None)

rawDescription: Not able to retrieve the HREF from the tag


code:
with open(fn) as f:
    txt=f.read()
    for m in re.finditer(r'^PATTERN1\s*(.*?)(?=^PATTERN2)', txt, re.M | re.S):
        print re.findall(r'(^\w+)', m.group(1), re.M)

rawDescription: Retreiving text from Pattern1 to Pattern2 - Python


rawDescription: how to show Percentage in python

description: Show Percentage in python


code:
for l in window([1,2,3,4,5], 4):
    for l1, l2 in l:
        print l1, l2

rawDescription: Python nested loop - get next N lines

description: Python nested loop - get next N lines


code:
import itertools

def generateLists(n, k):
    numberOfZeroes = n - k
    for numberOfOnes in range(0, k+1):
        numberOfNegativeOnes = k - numberOfOnes
        orderedList = [-1] * numberOfNegativeOnes + [0] * numberOfZeroes + [1] * numberOfOnes
        for possibleOrderings in itertools.permutations(orderedList):
            yield possibleOrderings

for i in generateLists(3, 2):
    print i

rawDescription: Generating list with constraints

description: Generating list with constraints


code:
## CLASSES START
class Object(object):
    """Object Set"""
    def __init__(self, name, description):
        self.name = name
        self.description = description
    # end Constructor

    def show(self):
        print self.description
    # end show

    def __str__(self):
        return self.description
    # end str magic method
# end class Object

class Inventory(object):
    """Inventory for Objects"""
    def __init__(self, target):
        self.objects = []
        self.target = target
    # end Constructor

    def create(self, objects, target):
        self.objects = list(objects)
        self.target = str(target)
    # end creates

    def show_objects(self):
        for i in self.objects:
            print i
    # end show_object

    def addobject(self, obj):
        self.objects.append(obj)
        print str(obj), "added to", str(self.target)
    # end addobject
# end class Inventory

class Room(object):
    """Single Room Data"""
    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.inventory = Inventory(self)

    def show(self):
        print self.name.upper() # Probably want .title() instead
        print self.description
        self.inventory.show_objects()

    def create(self, name, description):
        self.append(name)
    # end create

    def __str__(self):
        """Str method display the name."""
        return str(self.name)
    # end __str__
# end class Room

if __name__ == "__main__":
    ground_zero = Room("Ground Zero", "First Empty Room")
    item_zero = Object("Item Zero", "A non-descript item.")
    item_one = Object("Item One", "A non-descript item.")
    ground_zero.inventory.addobject(item_zero)
    ground_zero.inventory.addobject(item_one)
    ground_zero.show()

rawDescription: Python Class Shenanigans

description: Python Class Shenanigans


code:
exec( compile(config,'config.py','exec') )
print animals

rawDescription: Python text processing and parsing

description: Python text processing and parsing


code:
from settings import Config as settings
# or from settings import ProductionConfig as settings

print settings.DEBUG # for example

rawDescription: How to initialize helper method?

description: Initialize helper method


rawDescription: Filtering a Pythons Pandas DataFrame based on values from dictionary


code:
import threading
import time
import datetime

class Worker1( threading.Thread ):
    def __init__(self, state):
        super(Worker1, self).__init__()
        self.state = state

        def run(self):
            print_time_helper("Worker1 Start")
        time.sleep(4)
        print_time_helper("Worker1 End")
        self.state.keepOnRunning = False

class Worker2( threading.Thread ):
    def __init__(self, state):
        super(Worker2, self).__init__()
        self.state = state

    def run(self):
        while self.state.keepOnRunning:
            print_time_helper("Worker2")
            time.sleep(1)

class State( object ):
    def __init__(self):
        self.keepOnRunning = True

def main():
    state = State()

    thread1 = Worker1(state)
    thread2 = Worker2(state)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

def print_time_helper(name):
    print "{0}: {1}".format(name, datetime.datetime.now().time().strftime("%S"))

rawDescription: Multi threading in python using parallel threads


code:
import netifaces
netifaces.interfaces()
netifaces.ifaddresses('eth0')
for interface in netifaces.interfaces():
  print netifaces.ifaddresses(interface)[netifaces.AF_INET]
for interface in netifaces.interfaces():
  for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
    print link['addr']

rawDescription: How do I determine all of my IP addresses when I have multiple NICs?

description: Determine all of my IP addresses when I have multiple NICs


code:
with open("file", "r") as f:
    m = f.readlines()
    print [i.strip().split() for i in m]

rawDescription: Make a list of list with string in a text file in Python 3


code:
import argparse
parser = argparse.ArgumentParser(description='Simple PostScript Interpreter')
parser.add_argument('-s', action="store_true")
parser.add_argument('-d', action="store_true")
args = parser.parse_args()
print args

rawDescription: Accessing argument values for argparse in Python


code:
v1('100')
vR('104')
v1('108')

print v1  #<bound method somclass.somemethod of <__main__.someclass instance at 0x7fcfd8556758>

rawDescription: Setting a variable for lineEdits

description: Setting a variable for lineEdits


code:
def pairs(it):
    it = iter(it)
    for element in it:
        yield element, next(it)

for word1, word2 in pairs(tmpstr):
    print word1, word2

rawDescription: The pythonic way of printing a value

description: The pythonic way of printing a value