code:
url = 'http://www.theguardian.com/sport/rss'
open_page = urlopen(url)
html_code = open_page.read()
open_page.close()

descriptions = re.findall(r'<description>(.*?)</description>',html_code)

for description in descriptions:
    if 'Latest news and features from theguardian.com' in description:
        pass
    else:

        #edited here
        cont = re.sub("&lt.*?&gt","",description)

        print "Description:" ,cont

rawDescription: Stripping content using regular expressions in python


code:
# It's probably more common to define your STOP_WORDS in a file and then read
# them into your data structure to keep things simple for large numbers of those
# words.
STOP_WORDS = set([
    'het',
    'om'
])

all_words = set()
for item in g_data:
    all_words |= set(item.text.split())
all_words -= STOP_WORDS
print all_words

rawDescription: Removing words from python lists?

description: Removing words from python lists


code:
filename = 'uid.txt'

with open(filename) as uid_file:
    uid_dict={}

    backData = [164, 168, 124, 90, 42]
    no_matches = True

    for line in uid_file:
        info = line.split(",")
        key = info[0]
        uname = info[1]
        print info[0], info[1]
        c = len(uname)-1
        uname = uname[0:c]
        uid_dict[key] = uname
        USER = [int(i) for i in key.split()]

        if backData == USER:
            print "user matches"
            no_matches = False
            break

    if no_matches:
        print "Access Denied"

rawDescription: Why is my Python Dictionary only returning the last value?


code:
A = ['a.png', 'b.png', 'c.png', 'd.png', 'e.png']
B = ';'.join(A)
print b #this will return -> a.png;b.png;c.png;d.png;e.png

rawDescription: Manipulation of list of strings in python


code:
import subprocess
p = subprocess.Popen("whatever.exe",stdout=subprocess.PIPE)
print p.stdout.read()
p.wait()

rawDescription: Run a .exe file serverside by a CGI python script


code:
#!/grid/common/bin/python
import sys, time

for i in range(10):
    print str(i)
    sys.stdout.flush()
    time.sleep(1)

rawDescription: Python cgi script displays output in the browser only after its completion


code:
MAX = 100000

from time import sleep
def f(i):
    sleep(0.01)
    return i

def summer(summand):
    global SUM, FINISHED
    SUM += summand
    FINISHED += 1

if __name__ == "__main__":
    import multiprocessing as mp
    SUM = 0
    FINISHED = 0
    pool = mp.Pool(4)

    print "queuing", MAX, "work descriptions"
    for i in xrange(MAX):
        pool.apply_async(f, args=(i,), callback=summer)
        if i % 1000 == 0:
            print "{}/{}".format(FINISHED, i),
    print

    print "closing pool"
    pool.close()

    print "waiting for processes to end"
    pool.join()

    print "verifying result"
    print "got", SUM, "expected", sum(xrange(MAX))

rawDescription: Starting a large number of async processes with multiprocessing


code:
with open('file.txt') as fp:
    print ','.join(fp.read().splitlines())

rawDescription: python file iteration to change the formatting of output (going from a column to line)

description: Python file iteration to change the formatting of output (going from a column to line)


code:
T = lambda i: {j: T(j) for j, h in enumerate(H) if h[3] == i}
print T(-1)

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


code:
#!/usr/bin/python

import random
import string

digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars

rawDescription: Generating random text strings of a given pattern


code:
from lxml import etree
context = etree.parse(handle)
print next(x.text for x in context.xpath('.//*[local-name()="servlet-class"]'))

rawDescription: parse xml with lxml including namespace

description: Parse xml with lxml including namespace


code:
companies = {}
for line in open('/home/ibrahim/Desktop/Test.list'):
    # line is "(Number)Name,Year,Employees"
    company, founding_year, number_of_employee = line.split(',')
    # company is "(Number)Name"
    number, name = company.split(")")
    number = number[1:] # trim '('
    companies[number] = (name, founding_year, number_of_employee)
    print "Company: %s" % company

rawDescription: python saving information from text data

description: Python saving information from text data


code:
#!/usr/bin/env python

import sys, time
from daemon import Daemon

class MyDaemon(Daemon):
        def run(self):
                while True:
                        time.sleep(1)

if __name__ == "__main__":
        daemon = MyDaemon('/tmp/daemon-example.pid')
        if len(sys.argv) == 2:
                if 'start' == sys.argv[1]:
                        daemon.start()
                elif 'stop' == sys.argv[1]:
                        daemon.stop()
                elif 'restart' == sys.argv[1]:
                        daemon.restart()
                else:
                        print "Unknown command"
                        sys.exit(2)
                sys.exit(0)
        else:
                print "usage: %s start|stop|restart" % sys.argv[0]
                sys.exit(2)

rawDescription: Implementing a full Python Unix-style daemon process


code:
import string
s = "a\nb\rc\td"
print s.translate(string.maketrans("\n\t\r", "   "))

rawDescription: Deleting specific control characters(\n \r \t) from a string


rawDescription: Linear interpolation on a numpy array

description: Linear interpolation on a numpy array


code:
import xml.dom.minidom

def get_coord_list_from_earth(filename):

    filename = str(filename)

    data = xml.dom.minidom.parse(filename)

    coordinates = data.getElementsByTagName('coordinates')[0].firstChild.nodeValue
    coordinates = str(coordinates.strip())

    lol = list()
    ls = coordinates.split(',')
    for group_ls in zip(ls[0::2], ls[1::2]):
        f = group_ls[0].split()[-1]
        s = group_ls[1].split()[-1]
        # creating list of tuples, if you are not going to mutate it
        # then tuple is must more memory efficient then list.
        lol.append((f,s))
    return lol

print get_coord_list_from_earth('test.xml')

rawDescription: Parse output to get a list in python

description: Parse output to get a list in python


code:
#!/usr/bin/env python
# a.py
import inspect

def foo():
    for item in inspect.stack():
        print item

rawDescription: How do I find out in which file or module is my function called?

description: Find out in which file or module is my function called


code:
import sys

def trace(frame, event, arg):
    print "%s, %s:%d" % (event, frame.f_code.co_filename, frame.f_lineno)
    return trace

def test():
    print "Line 8"
    print "Line 9"

sys.settrace(trace)
test()

rawDescription: python tracing a segmentation fault

description: Python tracing a segmentation fault


code:
with open('data.txt') as f:
    for l in f:
        name,hours = l.split(',',1)
        print '%s:%s' % (name, sum([float(x) for x in hours.split(',')]))

rawDescription: How to load txt and sum hours?

description: Load txt and sum hours


code:
if "token" in mystring:
    print mystring

rawDescription: Search and get a line in Python

description: Search and get a line in Python


code:
from pprint import pprint as pp

# you don't need to store the ordering in a list,
# because lists are ordered by their nature
text = ['My', 'arm', 'has', 'no', 'chin', '.']
print 'Text to annotate'
pp(text)

# slurp the data, throw away the header, split on whitespace
data = [row.split() for row in open('datafile.csv').readlines()[1:]]
print '\nData as a list of rows'
pp(data)

# turn into a dictionary with lists of ints
data = {row[1]:[int(elt) for elt in row[2:]] for row in data}
print '\nData as a dictionary of lists of scores'
pp(data)

annotated_text = [tuple([word]+data[word]) if word in data else (word,)
                  for word in text]
print '\nAnnotated text'
pp(annotated_text)
print '\nNB: the order of the words in the text is preserved in the annotated text.'

rawDescription: Get CSV values for words in list

description: Get CSV values for words in list


code:
data = ('(Laughter flower)', {'laughter': (8.5, 0.9313), 'flower': (7.88, 1.1718),
'the':(4.98, 0.9145), 'puppy':(7.58, 1.4581), 'died':(1.56, 1.198), 'laugh':
(9.5, 0.1),'flow': (2.3, 0.51)})

# Unpack for naming
keys, vals = data
# Assume () and first and last
look_for = keys[1:-1].lower().split()
# Get relevant numbers
nums = [vals[k][0] for k in look_for]
# Print average
print sum(nums) / len(nums)

rawDescription: Using list comprehension

description: Using list comprehension


code: print ''.join(map('<img src="{}">'.format, foo))

rawDescription: Python: Print list of unknown length?

description: Python: Print list of unknown length


code:
class Weapon():
    def __init__(self):
        self.ammoCount = 0
    def fire():
        print "fire!"
    def reload():
        print "reloading!"

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

    def bark(self):
        print "Arf!"

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

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


code:
@receiver(pre_save, sender=MyModel)
def my_handler(sender, **kwargs):
    my_model = kwargs.get('instance')
    if my_model.column2:
        my_model.slug = slugify(my_model.column1 + " " + my_model.column2)
    else:
        my_model.slug = slugify(my_model.column1)
    print my_model.slug

rawDescription: django model save - override method not invoked during migrations

description: Django model save - override method not invoked during migrations


code:
x = 0 # some arbitrary context

# Define a simple function to return a wrapped class
def wrap_class(base, towrap):
    class ClassWrapper(base):
        def __getattribute__(self, name):
            original = base.__getattribute__(self, name)
            if name in towrap:
                def func_wrapper(*args, **kwargs):
                    global x
                    x = 1
                    try:
                        return original(*args, **kwargs)
                    finally:
                        x = 0
                return func_wrapper
            return original
    return ClassWrapper

# Our existing base class
class Base(object):
    def a(self):
       print "a x: %s" % x

    def b(self):
       print "b x: %s" % x

# Create a wrapped class in one line, without needing to define a new class
# for each class you want to wrap.
Wrapped = wrap_class(Base, ('a',))

# Now use it
m = Wrapped()
m.a()
m.b()

# ...or do it in one line...
m = wrap_class(Base, ('a',))()

rawDescription: Wrap calls to methods of a Python class

description: Wrap calls to methods of a Python class


code:
def print_row_maj(m):
    for row in m:
       print ' '.join(str(x) for x in row)

rawDescription: Invert the matrix values

description: Invert the matrix values


code:
sum = 0

def numberofdays ():
    sum = 0
    for i in range (1901, 2000):
        if i%4 == 0:
            sum = sum + 366
        else:
            sum = sum + 365
    return sum

sum = numberofdays() + 365 #to account for year 2000.

print sum

rawDescription: Simple For loop confusion

description: Simple For loop confusion


code:
from itertools import islice
def formatted_bin(inp):
   output = format(int(inp.rstrip('UL'), 16), 'b')
   le = len(output)
   m = le % 4
   padd = 4 - m if m != 0 else 0
   output  = output.zfill(le + padd)
   it = iter(output)
   return ' '.join(''.join(islice(it, 4)) for _ in xrange((le+padd)/4))

print formatted_bin('0x0202020202UL')
print formatted_bin('0x10')
print formatted_bin('0x101010')
print formatted_bin('0xfff')

rawDescription: print out binary representation of c type in python

description: Print out binary representation of c type in python


code:
def get_table_data(driver, table_name):
    table = driver.find_element_by_xpath('//div[@class="fixedpage_heading" and contains(., "{table_name}")]/following-sibling::table'.format(table_name=table_name))

    result = {}
    for row in table.find_elements_by_tag_name('tr')[1:]:
        month = str(row.find_element_by_class_name('quotefield_shortmonthonly').text)
        low = str(row.find_element_by_class_name('quotefield_low').text)
        high = str(row.find_element_by_class_name('quotefield_high').text)
        result[month]=[low, high]

    return result

print get_table_data(driver, 'CORN')
print get_table_data(driver, 'SOYBEANS')

rawDescription: Filtering through multiple xpath elements on web page


code:
import socket
import struct

def make_ip(proto, srcip, dstip, ident=54321):
    saddr = socket.inet_aton(srcip)
    daddr = socket.inet_aton(dstip)
    ihl_ver = (4 << 4) | 5
    return struct.pack('!BBHHHBBH4s4s' ,
                       ihl_ver, 0, 0, ident, 0, 255, proto, 0, saddr, daddr)

def make_tcp(srcport, dstport, payload, seq=123, ackseq=0,
             fin=False, syn=True, rst=False, psh=False, ack=False, urg=False,
             window=5840):
    offset_res = (5 << 4) | 0
    flags = (fin | (syn << 1) | (rst << 2) |
             (psh <<3) | (ack << 4) | (urg << 5))
    return struct.pack('!HHLLBBHHH',
                       srcport, dstport, seq, ackseq, offset_res,
                       flags, window, 0, 0)

srcip = dstip = '127.0.0.1'
srcport, dstport = 11001, 11000
payload = '[TESTING]\n'

ip = make_ip(socket.IPPROTO_TCP, srcip, dstip)
tcp = make_tcp(srcport, dstport, payload)
packet = ip + tcp + payload

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
s.sendto(packet, (dstip, 0))
response, addr = s.recvfrom(65535)
response_id = struct.unpack('!H', response[4:6])
print response_id

rawDescription: Using raw socket in Python

description: Using raw socket in Python


code:
import os
import sys

fd = os.open("test-output.txt", os.O_WRONLY | os.O_CREAT, 0644)
os.dup2(fd, sys.stdout.fileno())
os.close(fd)

rawDescription: Capturing log information from bunch of python functions in single file


code:
from ete2 import ClusterTree, TreeStyle
import scipy.cluster.hierarchy as sch
import scipy.spatial.distance
import matplotlib.pyplot as plt
import numpy as np
from itertools import combinations

tree = ClusterTree('(A:0.1,B:0.2,(C:0.3,D:0.4):0.5);')
leaves = tree.get_leaf_names()
ts = TreeStyle()
ts.show_leaf_name=True
ts.show_branch_length=True
ts.show_branch_support=True

idx_dict = {'A':0,'B':1,'C':2,'D':3}
idx_labels = [idx_dict.keys()[idx_dict.values().index(i)] for i in range(0, len(idx_dict))]

#just going through the construction in my head, this is what we should get in the end
my_link = [[0,1,0.3,2],
        [2,3,0.7,2],
        [4,5,1.0,4]]

my_link = np.array(my_link)

dmat = np.zeros((4,4))

for l1,l2 in combinations(leaves,2):
    d = tree.get_distance(l1,l2)
    dmat[idx_dict[l1],idx_dict[l2]] = dmat[idx_dict[l2],idx_dict[l1]] = d

print 'Distance:'
print dmat

schlink = sch.linkage(scipy.spatial.distance.squareform(dmat),method='average',metric='euclidean')

print 'Linkage from scipy:'
print schlink

print 'My link:'
print my_link

print 'Did it right?: ', schlink == my_link

dendro = sch.dendrogram(my_link,labels=idx_labels)
plt.show()

tree.show(tree_style=ts)

rawDescription: Newick tree representation to scipy.cluster.hierarchy linkage matrix format


code:
#!/usr/bin/python2

from os import setgroups, setuid, setgid, environ
from sys import argv, exit
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        testme = QtGui.QPushButton('\nTEST ME\n')
        self.connect(testme, QtCore.SIGNAL('clicked()'), self.test)
        self.setCentralWidget(testme)

    def test(self):
        sp = SandboxProcess()
        sp.start('python2 ./detach.py firefox')
        sp.waitForFinished()
        print str(sp.readAllStandardOutput()).strip()

class SandboxProcess(QtCore.QProcess):

    def __init__(self, *args, **kwargs):
        super(SandboxProcess, self).__init__(*args, **kwargs)
        env = environ.copy()
        if 'SUDO_USER' in environ:
            username = environ['SUDO_USER']
            del env['SUDO_USER']
            del env['SUDO_GID']
            del env['SUDO_UID']
        elif 'KDESU_USER' in environ:
            username = environ['KDESU_USER']
            del env['KDESU_USER']
        else:
            username = 'nobody'
        env['USERNAME'] = username
        env['LOGNAME'] = username
        env['USER'] = username
        env['MAIL'] = '/var/mail/' + username
        env['HOME'] = '/home/' + username
        #cleaning environment....
        qenv = QtCore.QProcessEnvironment()
        for k, v in env.iteritems():
            qenv.insert(k, v)
        self.setProcessEnvironment(qenv)

    def setupChildProcess(self):
        super(SandboxProcess, self).setupChildProcess()
        if 'SUDO_USER' in environ:
            gid = environ['SUDO_GID']
            uid = environ['SUDO_UID']
        elif 'KDESU_USER' in environ:
            gid = environ['KDE_SESSION_UID']
            uid = environ['KDE_SESSION_UID']
        else:
            uid = 65534
            gid = 65534
        setgroups([])
        setgid(int(gid))
        setuid(int(uid))

if __name__ == '__main__':
    app = QtGui.QApplication(argv)
    main = MainWindow()
    main.show()
    exit(app.exec_())

rawDescription: Unable to drop privileges for a new process with QProcess in PyQt4


code:
from lxml import etree

data = """<X>
    <X03>3</X03>
    <X02>2</X02>
    <A>
        <A02>Y</A02>
        <A01>X</A01>
        <A03>Z</A03>
    </A>
    <X01>1</X01>
    <B>
        <B01>Z</B01>
        <B02>X</B02>
        <B03>C</B03>
    </B>
</X>"""

doc = etree.XML(data,etree.XMLParser(remove_blank_text=True))

for parent in doc.xpath('//*[./*]'): # Search for parent elements
  parent[:] = sorted(parent,key=lambda x: x.tag)

print etree.tostring(doc,pretty_print=True)

rawDescription: LXML - Sorting Tag Order

description: LXML - Sorting Tag Order


rawDescription: How to return a view of several columns in numpy structured array

description: Return a view of several columns in numpy structured array


code:
class MyTest(object):

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

    def __setattr__(self, name, value):
        if name=="device":
            print "device test"
        else:
            super(MyTest, self).__setattr__(name, value)
            # in python3+ you can omit the arguments to super:
            #super().__setattr__(name, value)

rawDescription: How to use __setattr__ correctly, avoiding infinite recursion

description: Use __setattr__ correctly, avoiding infinite recursion


code: print 'token:', token, 'current result:', result

rawDescription: Convert number to Italian and Italian to number in python


code:
from sys import modules

print modules['sys'].path

rawDescription: difference between various import statements in python

description: Difference between various import statements in python


code:
sdb = shelve.open('foo.db')
sdb['abc'] = {'a': 1, 'b': 2}
tmp = cPickle.dumps(dict(sdb), 2)
print cPickle.loads(tmp)
{'abc': {'a': 1, 'b': 2}}

rawDescription: allow a shelve object to be pickled in python, pypar and mpich2

description: Allow a shelve object to be pickled in python, pypar and mpich2


rawDescription: Tweepy rate limit / pagination issue.

description: Tweepy rate limit / pagination issue.


rawDescription: How to turn a Dataframe into an Array with certain specifications on Python Pandas

description: Turn a Dataframe into an Array with certain specifications on Python Pandas


code:
from pygoogle import pygoogle
g = pygoogle('quake 3 arena')
g.pages = 5
print '*Found %s results*'%(g.get_result_count())
g.get_urls()

rawDescription: How do I use the Python API pygoogle?

description: Use the Python API pygoogle


code:
class ChildlessChildVisitor(DictionaryVisitor):
    def visit(self, node, parents, result):
        """ Collect the nodes that have parents but no children """
        if parents and 'childs' not in node:
            # slightly odd data structure here, a list of dicts where the only
            # dict key is unique. It would be better to be a plain dict, which
            # is what is done here:
            result[parents[-1]['name']].append(node)

    def start(self, dict_list):
        """ This just handles the parents and result argument of traverse """
        # Here it is much better to have a dict as the result.
        # This is an example of why wrapping all this logic in the start method
        # is not normally appropriate.
        result = defaultdict(list)
        for node in dict_list:
            self.traverse(node, [], result)
        return result

visitor = ChildlessChildVisitor()
results = visitor.start(listDict)
print dict(results)
# prints {'C': [{'fun': 'funE', 'name': 'E'}, {'fun': 'funF', 'name': 'F'}], 'B': [{'fun': 'funD', 'name': 'D'}], 'G': [{'fun': 'funH', 'name': 'H'}]}

rawDescription: create different list of dicts from master list of dict

description: Create different list of dicts from master list of dict


code:
from collections import Counter
c = Counter(['hello', 'hello', 1])
print c

rawDescription: Counting unique words in python

description: Counting unique words in python


code:
fname = raw_input("Enter file name: ")

with open(fname, 'rb') as fn:
    l = [line.split()[1]for line in fn if line.startswith('From:')]

print "\n".join(l)
print "There were", len(l), "lines in the file with From as the first word"

rawDescription: List is printing index value twice

description: List is printing index value twice


code:
results=api.search(q="microsoft",count=100)

print type(results)
print json.load(results)

rawDescription: AttributeError: 'dict' object has no attribute 'read'


code:
from gpio import GPIO
import module1

print "main: %s" % GPIO.__name__
# Do stuff wth GPIO

module1.Relay()

rawDescription: Python: How to use variables acros modules


code:
def movies_added_last(**kwargs):
    current_time = dateconvert.arrow.utcnow().naive
    tf_hours_ago = current_time - timedelta(**kwargs)
    movies_within_the_last_tf = models.Movie.query.filter(models.Movie.timeadded > tf_hours_ago).count()
    print movies_within_the_last_tf

rawDescription: Passing Arguments to Inner Function

description: Passing Arguments to Inner Function


code:
from pyparsing import *

ESC = Literal('\x1b')
integer = Word(nums)
escapeSeq = Combine(ESC + '[' + Optional(delimitedList(integer,';')) +
                oneOf(list(alphas)))

nonAnsiString = lambda s : Suppress(escapeSeq).transformString(s)

unColorString = nonAnsiString('\x1b[1m0.0\x1b[0m')
print unColorString, len(unColorString)

rawDescription: Getting correct string length in Python for strings with ANSI color codes


code:
from PyQt4 import QtGui, QtCore, QtNetwork
import sys
import time

def finished(reply):
  print "Finished: ", reply.readAll()
  app.quit()

def construct_multipart(data, files):
  multiPart = QtNetwork.QHttpMultiPart(QtNetwork.QHttpMultiPart.FormDataType)
  for key, value in data.items():
    textPart = QtNetwork.QHttpPart()
    textPart.setHeader(QtNetwork.QNetworkRequest.ContentDispositionHeader,
      "form-data; name=\"%s\"" % key)
    textPart.setBody(value)
    multiPart.append(textPart)

  for key, file in files.items():
    imagePart = QtNetwork.QHttpPart()
    #imagePart.setHeader(QNetworkRequest::ContentTypeHeader, ...);
    fileName = QtCore.QFileInfo(file.fileName()).fileName()
    imagePart.setHeader(QtNetwork.QNetworkRequest.ContentDispositionHeader,
      "form-data; name=\"%s\"; filename=\"%s\"" % (key, fileName))
    imagePart.setBodyDevice(file);
    multiPart.append(imagePart)
  return multiPart

app = QtGui.QApplication(sys.argv)
file1 = QtCore.QFile('/tmp/1.txt')
file1.open(QtCore.QFile.ReadOnly)
url = QtCore.QUrl('http://localhost:3000/qwertytest1');
data = { 'text1': 'test1', 'text2': 'test2' }
files = {'file1': file1 }
multipart = construct_multipart(data, files)
request_qt = QtNetwork.QNetworkRequest(url)
request_qt.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader,
  'multipart/form-data; boundary=%s' % multipart.boundary())
manager = QtNetwork.QNetworkAccessManager()
manager.finished.connect(finished)
request = manager.post(request_qt, multipart)

sys.exit(app.exec_())

rawDescription: upload files through http post in Pyside/PyQt

description: Upload files through http post in Pyside/PyQt


code:
if not place:
    blah = combo[:pos+1]
    listx = [x for x in listx if not x[:pos+1] == combo[:pos+1]]
    print 'Fail', combo, count
    return solve(listx)

rawDescription: Recursion results in unwanted looping

description: Recursion results in unwanted looping


code:
words= 'military  troop  deployment  number  need'
sent = words.split()

matched = []
with open("file2","r") as f1:
    for i, line in enumerate(f1):
        for word in sent:
            if word in line:
                matched.append('%s %d' % (word, i + 1))

print ', '.join(matched)

rawDescription: Get line numbers of words present in a file


code:
class Animal:
     voice = '...'
     def speak(self):
         return "A %s Says '%s'"%(self.__class__.__name__, self.voice)

class Dog(Animal):
     voice = "Bark, Bark"

class Duck(Animal):
     voice = "Quack, Quack"

print Dog().speak()
print Duck().speak()

rawDescription: Avoid using global without confusing new programming students in Python?


rawDescription: Looping through a list from a specific key to the end of the list


code:
from itertools import combinations

def perm(chars, length):
    s = ''.join([c * length for c in list(chars)])
    combs = combinations(s, length)
    combs = [''.join(comb) for comb in combs]
    combs = list(set(combs))
    combs.sort()
    return combs

for x in perm('012', 4):
    print x

rawDescription: All permutation of number with replacement


code:
#!/usr/bin/env python

import heapq

def makeHuffTree(symbolTupleList):
   trees = list(symbolTupleList)

   heapq.heapify(trees)
   while len(trees) > 1:
      childR, childL = heapq.heappop(trees), heapq.heappop(trees)
      parent = (childL[0] + childR[0], childL, childR)
      heapq.heappush(trees, parent)

   return trees[0]

def printHuffTree(huffTree, prefix = ''):
   if len(huffTree) == 2:
      print huffTree[1], prefix, len(prefix)
   else:
      printHuffTree(huffTree[1], prefix + '0')
      printHuffTree(huffTree[2], prefix + '1')

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

def buildHuffTree(huffTree, prefix = ''):
   if len(huffTree) == 2:
      return (huffTree[1], prefix, len(prefix))
   else:
      return (buildHuffTree(huffTree[1], prefix + '0'),
              buildHuffTree(huffTree[2], prefix + '1'))

if __name__ == '__main__':

   exampleData = [
     (0.124167  , 'e'),
     (0.0969225 , 't'),
     (0.0820011 , 'a'),
     (0.0768052 , 'i'),
     (0.0368052 , 'h')
   ]

   freqs = dict([(b,a) for (a,b) in exampleData])

   huffTree = makeHuffTree(exampleData)
   tot = printHuffTree2(freqs, huffTree)
   print 'Sum = ', tot

rawDescription: Python, SUM of multiply

description: Python, SUM of multiply


code:
a = "They all are white a sheet of spotless paper " \
    "when they first are born but they are to be " \
    "scrawled upon and blotted by every goose quill"
b = "You are all white, a sheet of lovely, spotless " \
    "paper, when you first are born; but you are to " \
    "be scrawled and blotted by every goose's quill"

print match(to_words(a), to_words(b))

rawDescription: Find maximum length of all n-word-length substrings shared by two strings


code:
import sys

# make sure the --args flag was passed
if '--args' not in sys.argv:
    print >> sys.stderr, 'Please pass the "--args" flag followed by a list of'\
            ' arguments'
    sys.exit(1) #terminate execution if it wasn't

four = sys.argv[sys.argv.index('--args')+1:] # everything passed after --args
print four

rawDescription: How to pass a list and other values as command line arguments?

description: Pass a list and other values as command line arguments


code:
# removing returns by row
row_idx =0
while row_idx < sheet.nrows:
    col_idx = 0
    while col_idx < sheet.ncols:
        new_value = remove_returns1(row_idx, col_idx)
        col_idx += 1
        print new_value,

    print
    row_idx += 1

rawDescription: How do I iterate through more than just one variable in a loop in Python?

description: Iterate through more than just one variable in a loop in Python


code:
from gzip import GzipFile
from StringIO import StringIO

http = 'HTTP/1.1 200 OK\r\nServer: nginx\r\nDate: Tue, 09 Feb 2016 12:02:25 GMT\r\nContent-Type: application/json\r\nContent-Length: 115\r\nConnection: close\r\nContent-Encoding: gzip\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Credentials: true\r\n\r\n\x1f\x8b\x08\x00\xa0\xda\xb9V\x02\xff\xab\xe6RPPJ\xaf\xca,(HMQ\xb2R()*M\xd5Q\x00\x89e\xa4&\xa6\xa4\x16\x15\x03\xc5\xaa\x81\\\xa0\x80G~q\t\x90\xa7\x94QRR\x90\x94\x99\xa7\x97_\x94\xae\x04\x94\xa9\x85(\xcfM-\xc9\xc8\x07\x99\xa0\xe4\xee\x1a\xa2\x04\x11\xcb/\xcaL\xcf\xcc\x03\x89\x19Z\x1a\xe9\x19\x9aY\xe8\x19\xea\x19*q\xd5r\x01\x00\r(\xafRu\x00\x00\x00'

body = http.split('\r\n\r\n', 1)[1]
print GzipFile(fileobj=StringIO(body)).read()

rawDescription: How to decode a source code which is compressed with gzip in python

description: Decode a source code which is compressed with gzip in python


code:
def is_power(a,b):
    if not a%b==0:
        return a%b==0
    elif a/b==1:
       return a/b==1
    else:
        a = a/b
        return is_power(a, b)

print is_power(10, 3)
print is_power(8, 2)

rawDescription: why doesn't python return booleans

description: Why doesn't python return booleans


code:
import sys
import StringIO

def frob():
    sys.stdout.write("Hello, how are you doing?")

#we want to call frob, storing its output in a temporary buffer.

#hold on to the old reference to stdout so we can restore it later.
old_stdout = sys.stdout

#create a temporary buffer object, and assign it to stdout
output_buffer = StringIO.StringIO()
sys.stdout = output_buffer

frob()

#retrieve the result.
result = output_buffer.getvalue()

#restore the old value of stdout.
sys.stdout = old_stdout

print "This is the result of frob: ", result

rawDescription: How to get this Python method to return a string instead of writing it to stdout?

description: Get this Python method to return a string instead of writing it to stdout


code:
class classA(object):
   def __init__(self, parent):
       self.parent = parent

   def method(self):
       self.parent.methodB()
class classB(object):
   def __init__(self):
       self.a=classA(self)
   def methodB(self):
       print "ClassB-s methodB called"
b = classB()
a = b.a
a.method()

rawDescription: Getting the attribute holder of an attribute


code:
def buildClass(name, node):
  global _classes
  symbol_table = {}
  args = []
  varnames = ""
  varnameswithtypes = ""
  for subnode in node:
    args.append(buildClass(subnode.tag, subnode))
    if (subnode.tag not in symbol_table):
      symbol_table[subnode.tag] = 1
      varnames += subnode.tag + " "
      if (not subnode.tag[0] == subnode.tag[0].upper()):
        varnameswithtypes += subnode.tag + ":array "
      else:
        varnameswithtypes += subnode.tag + ":object "

  print 'Building class for:', name
  for (key, value) in node.items():
    args.append(value)
    varnames += key + " "
    if (key == "variable_name"):
      varnameswithtypes+= key + ":" + value + " "
    elif (is_numeric(value)):
      varnameswithtypes+= key + ":numeric" + " "
    else:
      varnameswithtypes+= key + ":text" + " "
  varnames = varnames.strip()
  varnameswithtypes = varnameswithtypes.strip()

  if (_classes.has_key(name)):
    if (len(_classes[name]) < len(varnameswithtypes)):
      _classes[name] = varnameswithtypes
  else:
    _classes[name] = varnameswithtypes

  if (not name[0] == name[0].upper()):
    #this is an array, do not create a class, just return an array
    return args
  #print varnames, args
  globals()[name] = namedtuple(name, varnames)
  obj = globals()[name](*args)
  #print dump(obj)
  return obj

rawDescription: using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class

description: Using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class


code:
import re

def main():
    file = open("url.txt",'r')

    domains = set()
    # will works for any web like https://www.domain.com/something/somethingmore... , also without www, without https or just for www.domain.org
    matcher= re.compile("(h..ps?://)?(?P<domain>(www\.)?[^/]*)/?.*")

    for line in file:
        # make here any replace you need with obfuscated urls like: line = line.replace('[.]','.')
        if line[-1] == '\n': # remove "\n" from end of line if present
            line = line[0:-1]
        match = matcher.search(line)
        if match != None: # If a url has been found
            domains.add(match.group('domain'))

    print domains

    file.close()

main()

rawDescription: Remove duplicates after altering items

description: Remove duplicates after altering items


code:
print 'I have',
a=input()
print 'apples and',
p=input()
print 'pears.'

rawDescription: Python: "Print" and "Input" in one line

description: Python: "Print" and "Input" in one line


code:
def unique_words(input_file):
    file = open(input_file)
    wordlist = {}
    dups = []
    copy = []
    for index, value in enumerate(file):
        words = value.split()
        for word in words:
            wordlist[word] = index
            dups.append(word)
    for word in dups:
        if dups.count(word) != 1 and word not in copy:
            del(wordlist[word])
            copy.append(word)
    for item in wordlist:
        print 'The unique word '+item+' occurs on line '+str(wordlist[item])

rawDescription: Storing a string and a set in a dictionary


code:
import itertools

nums = [4, 94, 9, 14, 1]
max_num = 0
max_nums = None
for p in itertools.permutations(map(str, nums)):
    num = int(''.join(p))
    if num > max_num:
        max_num = num
        max_nums = p
print map(int, max_nums)
print max_num

rawDescription: to get max number after concatenation in list

description: To get max number after concatenation in list


code:
import numpy as np

# half-threshold in nanoseconds
threshold_ns = threshold * 60 * 1e9

# compute "interval" to which each session belongs
df1['interval'] = to_datetime(np.round(df1.date_start_time.astype(np.int64) / threshold_ns) * threshold_ns)
df2['interval'] = to_datetime(np.round(df2.date_start_time.astype(np.int64) / threshold_ns) * threshold_ns)

# join
cols = ['interval', 'employee_id', 'session_id']
print df1.merge(df2, on=cols, how='outer')[cols]

rawDescription: pandas merging based on a timestamp which do not match exactly

description: Pandas merging based on a timestamp which do not match exactly


code:
import re

adn = ('TCGCGCCCCCCCCCCATCAAGACATGGTTTTTTTTTTATTTATCAGATTACAGATACA'
       'GTTATGGGGGGGGGGATATACAGATGCATAGCGATTAGCCTAGCTA')

regx = re.compile('(.{10})(AT.{3,6}CA)(.{10})')
res = regx.findall(adn)
for u in res:
    print u

print

pat = re.compile('(.{10})(AT.{3,6}CA)')
li = []
for mat in pat.finditer(adn):
    x = mat.end()
    li.append(mat.groups()+(adn[x:x+10],))
for u in li:
    print u

rawDescription: python len function question

description: Python len function question


code:
from tornado import gen, ioloop

@gen.coroutine
def another_async_func(x):
    print "aaf"
    raise gen.Return(x + 1)

@gen.coroutine
def myfunc(x):
    print "myfunc"
    y = yield another_async_func(x)
    print "back"
    raise gen.Return(y)

@gen.coroutine
def main():
    y = yield myfunc(1)
    print "Callback called with %d" % y

if __name__ == "__main__":
    ioloop.IOLoop.instance().run_sync(main)

rawDescription: Use tornado async code in a regular python script


code:
from collections import defaultdict
d = defaultdict(list)
for s, i in seq:
    d[i].append(s)
print d

rawDescription: Python Get row in a list by one of its attributes


code:
import shlex
my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True)
my_splitter.whitespace += ','
my_splitter.whitespace_split = True
print list(my_splitter)

rawDescription: How can i parse a comma delimited string into a list (caveat)?

description: Parse a comma delimited string into a list (caveat)


rawDescription: Python remove JSON substring

description: Python remove JSON substring


code:
for row in soup('table')[5].findAll('tr'):
    tds = row('td')
    if not tds:
        continue
    print u' '.join([cell.string for cell in tds if cell.string])

rawDescription: Python: Read Content of Hidden HTML Table


code:
print a.shape, b.shape
# (3, 2) (3, 2)

rawDescription: understanding numpy's dstack function

description: Understanding numpy's dstack function


code:
class z(v):
  def visit_Name(self, node): print 'Name:', node.id

z().visit(t)

rawDescription: Simple example of how to use ast.NodeVisitor?


code:
s = "hello"
s = s[:-3] # string without last three characters
print s
# he

rawDescription: String Manipulation in Python

description: String Manipulation in Python


code:
def random_grid(file):
    grid = []
    num_rows = raw_input("How many raws would you like in your grid? ")
    num_columns = raw_input("How many columns would you like in your grid? ")
    min_range = raw_input("What is the minimum number you would like in your grid? ")
    max_range = raw_input("what is the maximum number you would like in your grid? ")
    for row in range(int(num_rows)):
        grid.append([])
        for column in range(int(num_columns)):
            grid[row].append(random.randint((int(min_range)),(int(max_range))))
    for row in grid:
        x = (' '.join([str(x) for x in row]))
        print x

        with open(r"test.txt", 'a') as text_file:
            text_file.write(x)
            text_file.write("\n")

rawDescription: Python list to txt

description: Python list to txt


code:
def print_sorted(d,is_float=0):
    l = [(v, k) for k, v in d.items()]
    l.sort()
    for v, k in l[::-1]:
        if is_float:
            print "%-12s%5.2" % (k+" :", v)
        else:
            print "%-12s%2d" % (k+" :", v)

rawDescription: How do you sort a list which is inside a dictionary?

description: Sort a list which is inside a dictionary


code:
@app.route('/testpost', methods = ['POST'])
def postTesting():
    name = request.form['name']
    print name #This is the posted value

rawDescription: Form Handling Using Flask

description: Form Handling Using Flask


rawDescription: making a function that takes a list of any size as an argument Python 3

description: Making a function that takes a list of any size as an argument Python 3


code:
tag = soup.find('p')  # this will give you the first p tag
data = ''
while True:
    if isinstance(tag, bs4.element.Tag):
        if tag.name == 'form':
            break
        else:
            data = data + tag.text  # string concatenation
            tag = tag.nextSibling
    else:
        tag = tag.nextSibling

print data

rawDescription: beautiful soup find all p until form

description: Beautiful soup find all p until form


code:
import re

s = "m * x + b"
print re.sub("([a-wyzA-Z])", r"var['\1']", s)

rawDescription: Python Find all letter chars in string and surround with text


code:
for attribute in product.attributes.all():
    mapping = attribute.attributemapping_set.get(product=product)
    print attribute.name, mapping.value

rawDescription: Django ManyToMany relation QuerySet using custom intermediate table


code:
rs = mySession.query(Items)
firstItem = rs.first()
for attribute in firstItem.attributes:
   print attribute

rawDescription: How to store and search list in SQLAlchemy?

description: Store and search list in SQLAlchemy


code:
import numpy as np
import pandas as pd
data = np.array([[1,2,3,4,5], [2,2,2,2,2], [3,3,3,3,3], [4,4,3,4,4], [7,2,3,4,5]])
columns = ["one", "two", "three", "four", "five"]
dframe_main = pd.DataFrame(data=data, columns=columns)
print "All columns:"
print dframe_main
del dframe_main[dframe_main.columns[0]] # get rid of the first column
print "All columns except the first:"
print dframe_main

rawDescription: reading into pandas data frame excluding the first column

description: Reading into pandas data frame excluding the first column


code:
import os
filename = "ThisFileName.txt"
print os.path.splitext(filename)
# Prints: ('ThisFileName', '.txt')

rawDescription: Python regex: Turn "ThisFileName.txt" into "This File Name.txt"


code: print A.func1.__doc__

rawDescription: Python - using decorator.py to preserve a method docstring


code:
contents = u'''\
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head>
<meta http-equiv="Content-Type" content="text/html; charset=unicode">
<meta name="ProgId" content="Word.Document">[snip]
</body></html>'''
contents.encode('utf16').decode('cp1252')
print contents.encode('utf16').decode('cp1252')[:2]

rawDescription: Requests Session with local HTTP adapter output-ing junk


code:
from subprocess import check_output, STDOUT, CalledProcessError

args = ['/usr/bin/ffmpeg', '-i', the_file, out_file]
try:
    txt = check_output(args, stderr=STDOUT)
except CalledProcessError as e:
    print "conversion failed", e
else:
    print the_file, 'converted to', out_file

rawDescription: ffmpeg converts anything to mp4

description: Ffmpeg converts anything to mp4


code:
import re

def get_sections(filename):
  with open(filename) as f:
    data = f.read()
  return re.findall(r'(?sm)^/\*!(.*?)^\*', data)

for section in get_sections('inputfile.txt'):
  print section

rawDescription: peak next character in a file

description: Peak next character in a file


code:
def square_less_than(n):
    i = 0
    while True:
       if i*i < n:
          yield i
          i += 1
       else:
          break

print list(square_less_than(10))

rawDescription: Python SyntaxError when creating a list using a generator


rawDescription: I can't decipher my list

description: I can't decipher my list


code:
import os
print os.path.expandvars(r"C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup")

rawDescription: Calling Upon An Enviromental Variable in a Path


rawDescription: Unstack or Pivot Only Some Columns

description: Unstack or Pivot Only Some Columns


rawDescription: Split a list into sublists on a value and keep the value


code:
from twisted.internet import reactor, protocol

HOST = 'localhost'
PORT = 9000

class MyClient(protocol.Protocol):
    def connectionMade(self):
        print "connected!"

class MyClientFactory(protocol.ClientFactory):
    protocol = MyClient

factory = MyClientFactory()
reactor.connectTCP(HOST, PORT, factory)

reactor.run()

rawDescription: Twisted server for multiple clients

description: Twisted server for multiple clients


code:
def validate_arguments(arg1, arg2):
    def decorator(func):
        def wrapped():
            print arg1, arg2
            return func()
        return wrapped
    return decorator

def f1():
  return True
f1 = validate_arguments(1, 2)(f1)
print f1()
#1 2
#True

rawDescription: Manually calling a decorator that takes arguments


code:
import urllib

url = "http://www.omdbapi.com/?t=UN%20HOMME%20ID%C3%89AL"
res = urllib.urlopen(url)
print  res.code
data = res.read()

rawDescription: Parse Json data to Excel

description: Parse Json data to Excel


code:
class CallWrapper(object):
    def __init__(self, fn):
        self.fn = fn

    def __call__(self, *args, **kwargs):
        self.args   = args
        self.kwargs = kwargs
        return self

    def invoke_with_value(self, value):
        return self.fn(value, *self.args, **self.kwargs)

class ConfigDict(dict):
    def __init__(self, ldic):
        myvars = globals()
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and not name.startswith('_'):
                myvars[name] = CallWrapper(attr)

        wrapped_dic = eval(ldic.func_code, myvars)

        dic = {}
        for key, value in wrapped_dic.iteritems():
            # Check if value is a tuple with call wrappers
            if isinstance(value, tuple) and len(value) > 1 and \
                        isinstance(value[1], CallWrapper):
                wrappers = value[1:]
                value = value[0]
                for wrapper in wrappers:
                    # Run wrappers
                    result = wrapper.invoke_with_value(value)
                    if result:
                        value = result # Wrapper modified value

            dic[key] = value # No wrappers

        super(ConfigDict, self).__init__(dic)

    def prefix(self, value, pref):
        print 'prefix called for value: ', value
        return pref + '_' + value

    def required(self, value, keys_array):
        print 'required called for value: ', value
        print 'with keys: ', keys_array

    def valid(self, value):
        print 'valid called for value: ', value

cfg = ConfigDict(lambda: {'A': ('a', required(['test']), valid()),
                          'B': ('b', prefix('hello')),
                          'C': 'c'})
print cfg

rawDescription: Passing function from another class to this class


code:
import random

d =[random.choice('ACUG') for x in xrange(3355)]
s = "".join(d)

print s

rawDescription: Python: Random sequence

description: Python: Random sequence


code:
class Record(object):
  def __init__(self,record_dict):
    try:
      self.id = record_dict['id']
      self.name = record_dict['name']
      self.description = record_dict['description']
      self.image = record_dict['image']
      self.flavor = record_dict['flavor']
    except KeyError:
      print 'KeyError'

  def get_name(self):
    return self.name

adict = {"id":3,"name":"MySQL","description":"MySQL Database Server - Fedora 21 - medium","image":"","flavor":""}

one_obj = Record(adict)

print one_obj
print one_obj.get_name()

rawDescription: How to extract string values into object fields

description: Extract string values into object fields


rawDescription: How To Find Complex Roots of A Multivariate Polynomial Equation System (Python)


code:
import contextlib
import functools

class Prof(object):
    def __init__(self, p='s'):
        self.p = p

    @staticmethod
    def do(x, obj=None):
        if obj is None:
            obj = Prof()
        obj.dprint(x)
        print

    def dprint(self, x):
        print self.p, x
        self.p += x

def wrapper(st):
    @contextlib.contextmanager
    def prof_context(obj):  # could also be defined outside of wrapper function
        # save current staticmethod and replace it with partial below
        saved_method, Prof.do = Prof.do, functools.partial(Prof.do, obj=obj)
        yield
        # undo staticmethod modification
        Prof.do = staticmethod(saved_method)

    def decorator(fn):
        @functools.wraps(fn)
        def wrapped():
            obj = Prof(st)
            print 'current: obj.p is %r' % obj.p
            with prof_context(obj):
                fn()

        return wrapped

    return decorator

def do_p():
    Prof.do('do')

@wrapper('do_p2')
def do_p2():
    Prof.do('do2')

print '#A do_p():'
do_p()
print '#B do_p2():'
do_p2()
print '#C do_p():'
do_p()
print '#D do_p2():'
do_p2()
print '#E do_p():'
do_p()
print '#F do_p():'
do_p()

rawDescription: How to use decorator to bind a argument to a staticmethod function?

description: Use decorator to bind a argument to a staticmethod function


code:
def foo1(arg):
    print "I got this as my argument:", arg

rawDescription: Calling random functions from a list when functions have different number of parameters


code:
from reportlab.platypus import BaseDocTemplate

class MyDocTemplate(BaseDocTemplate):
    """Override BaseDocTemplate for "progress bar" information"""

    def __init__(self, *args, **kwargs):
        BaseDocTemplate.__init__(self, *args, **kwargs)
        # BaseDocTemplate keeps a "progress" dictionary for its own
        # internal use, which is updated as various drawings are done.
        # This directs reportlab to use your own custom method
        # as the "callback" function when updates are made.
        # Notice the use of the __ prefix for the method, which ensures
        # that it calls *your* custom class's method, and not the default.
        # Should match the signature of the original callback: (self, type, value)
        self.setProgressCallBack(self.__onProgress)

    def __onProgress(self, prog_type, value):
        """Progress monitoring"""

        # One example "progress type" is the "PAGE" key. Which indicates
        # which page reportlab is working on.
        if prog_type == "PAGE":
            print "Drawing page: %s" % value
        elif prog_type == "FINISHED":
            print "Drawing complete!"

rawDescription: Django PDF: How to display progress in browser?


code:
for k,v in sorted(opt_dict.items(),
                  key = lambda item: int(item[0][len("option"):])
                            if item[0].startswith("option")
                            else int(item[0][len("nonoption"):])
                    ):
    print k,v

rawDescription: Pattern matching in dictionary using python


code:
def do_something(args):
    print 'from do_something ', args

def my_parse_args():
    parser = argparse.ArgumentParser(description='A demo script')
    parser.add_argument('arg1', help='an arg')
    return vars(parser.parse_args())

if __name__=="__main__":
    args = my_parse_args()
    do_something(args)

rawDescription: How to access argparse parse_args from another function

description: Access argparse parse_args from another function


code:
N = 5
R = 4

b = []
for i in range(N):
    b.append([])
    for j in range(R):
        b[i].append([])
        for k in range(0,R,2):
            b[i][j].append(j - k)
print b

rawDescription: How to append a 3d list and print its contents?

description: Append a 3d list and print its contents


code:
if 'foobar'.endswith('bar'):
    print "Yes sir :)"

rawDescription: strncmp in python

description: Strncmp in python


code:
from django.utils.termcolors import colorize
red_hello = colorize("Hello", fg="red")
red_hello # by not printing; it will not appear red; special characters are escaped
print red_hello # by print it will appear red; special characters are not escaped

rawDescription: ANSI graphic codes and Python

description: ANSI graphic codes and Python


code: print ' '.join(reversed(a.split()))  # Python 2

rawDescription: Reverse an input using tuples Python

description: Reverse an input using tuples Python


code:
print data['name']
data['score'] += 5  # add 5 points to the score

rawDescription: Reading/Writing/Appending using json module


code:
print method_results
{'Calc1': 1, 'Calc3': 2, 'Calc5': 3}

rawDescription: How do you return the results of all the methods of a class object as one list?

description: Return the results of all the methods of a class object as one list


code: print gettattr(self, s, 'No such attribute: '+s)

rawDescription: In Python, how do I get a variable via a string representation of the name of the variable?


code:
list1=[[['B', 10], 1], [['C', 15], 1], [['F', 30], 1]]
list2=[[['G', 20], 2], [['D', 25], 1]]

list2_iter = iter(list2)
for item1 in list1:
    in_list2 = False
    for item2 in list2_iter:
        if item1[1] == item2[1]:
            print "Match" if item1 == item2 else "Modified", item1, item2
            in_list2 = True
            break
        else:
            print "Inserted", item2
    if not in_list2:
        print "Deleted", item1

rawDescription: Two list comparison in Python

description: Two list comparison in Python


code:
from functools import wraps

def callonce(f):

    @wraps(f)
    def wrapper(*args, **kwargs):
        if not wrapper.called:
            wrapper.called = True
            return f(*args, **kwargs)
        print 'Function already called once.'
    wrapper.called = False
    return wrapper

rawDescription: How to make a few lines of function execute only once in python? preferably using lambda?

description: Make a few lines of function execute only once in python? preferably using lambda


code:
import sys
import operator
from pyparsing import nums, oneOf, Word, Literal, Suppress
from pyparsing import ParseException, Forward, Group

op_map = { '*' : operator.mul,\
           '+' : operator.add,\
           '/' : operator.div,\
           '-' : operator.sub}

exp = Forward()

number = Word(nums).setParseAction(lambda s, l, t: int(t[0]))
lparen = Literal('(').suppress()
rparen = Literal(')').suppress()
op = oneOf('+ - * /').setResultsName('op').setParseAction(lambda s, l, t: op_map[t[0]])

exp << Group(lparen + op + (number | exp) + (number | exp) + rparen)

def processArg(arg):
    if isinstance(arg, int):
        return arg
    else:
        return processList(arg)

def processList(lst):
    args = [processArg(x) for x in lst[1:]]
    return lst.op(args[0], args[1])

def handleLine(line):
    result = exp.parseString(line)
    return processList(result[0])

while True:
    try:
        print handleLine(raw_input('> '))
    except ParseException, e:
        print >>sys.stderr,\
              "Syntax error at position %d: %s" % (e.col, e.line)
    except ZeroDivisionError:
        print >>sys.stderr,\
              "Division by zero error"

rawDescription: Executing mathematical user inputed statements as code in Python 3


code:
names = {'name1': 34, 'name2':45, 'name3': 98, 'name4':34, 'name5': 66}
sorted_names = sorted(names.iteritems(), key=lambda (k, v): (-v, k))[:10]
sorted_names

rawDescription: How to get the top 10 students in the class using Python dict

description: Get the top 10 students in the class using Python dict


code:
class Foo(object):
    def __getitem__(self, index):
        print 'Getting', index
    def __setitem__(self, index, val):
        print 'Setting', index, 'to', val

f = Foo()
print 'Getting...'
f[:]
f[4:10, ::-1, ...]

print 'Equivalently:'
f.__getitem__(slice(None))
f.__getitem__((slice(4, 10), slice(None, None, -1), Ellipsis))

print 'Setting...'
f[0] = 1
f[5:10, 100] = 2
f[...] = 100

print 'Equivalently:'
f.__setitem__(0, 1)
f.__setitem__((slice(5,10), 100), 2)
f.__setitem__(Ellipsis, 100)

rawDescription: Use Numpy Multidimensional Array Slicing Without Using the [slice,slice] Syntax?


code: for p in myList: print p

rawDescription: Pythonic way to print list items

description: Pythonic way to print list items


code:
from kivy.uix.popup import Popup
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout

class LoginScreen(GridLayout):
    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.cols = 2
        self.row = 2
        self.add_widget(Label(text='User Name'))
        self.username = TextInput(multiline=False)
        self.add_widget(self.username)
        self.add_widget(Label(text='password'))
        self.password = TextInput(password=True, multiline=False)
        self.add_widget(self.password)
        self.hello = Button(text="hello")
        self.hello.bind(on_press=self.auth)
        self.add_widget(self.hello)

    def auth(self,instance):
        print "auth called"
        if self.username == "Hendricko":
            popup = Popup(title="success",
                content=Label(text="Howdy !"),
                size=(100, 100),
                size_hint=(0.3, 0.3),
                auto_dismiss=False)
            popup.open()

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()

rawDescription: Bind function to Kivy button

description: Bind function to Kivy button


code: print ball.curx()

rawDescription: Not recognizing object parameter as int

description: Not recognizing object parameter as int


code:
result, data = mail.uid('search', None, "ALL")
print data[0].split()

rawDescription: getting emails from gmail via python

description: Getting emails from gmail via python


code:
def method(**kwargs):
  print kwargs

keywords = {'keyword1': 'foo', 'keyword2': 'bar'}
method(keyword1='foo', keyword2='bar')
method(**keywords)

rawDescription: Passing a list of kwargs?

description: Passing a list of kwargs


code:
def totalArea(start, stop, step):
    def f(x):
        return 10*math.e**(math.log(0.5)/5.27 * x)

    area = 0.0
    j = start

    for j in range(start, stop):
        area += float(step) * f(j)

    print area

rawDescription: Python Generating Infinite Loop When First Arg is 0


rawDescription: How to check if a word appears in ID(location in element list) of another word(key)

description: Check if a word appears in ID(location in element list) of another word(key)


code:
pattern = r"[\n^]([A-Za-z]+)"
print re.findall(pattern, text)

rawDescription: Python: A good regular expression for text parsing in this example


code:
from BeautifulSoup import BeautifulSoup
import imdb

access = imdb.IMDb()
movie = access.get_movie(1132626)

page = urllib2.urlopen(access.get_imdbURL(movie))
soup = BeautifulSoup(page)
cover_div = soup.find(attrs={"class" : "photo"})
cover_url = (photo_div.find('img'))['src']
print "Cover url: %s" % cover_url

rawDescription: How do you get a thumbnail of a movie using IMDbPy?

description: Get a thumbnail of a movie using IMDbPy


code:
import requests
from lxml import html

with requests.Session() as session:
    page = session.get('http://financials.morningstar.com/company-profile/c.action?t=AAPL')
    tree = html.fromstring(page.text)

    # get the operational details
    response = session.get("http://financials.morningstar.com/company-profile/component.action", params={
        "component": "OperationDetails",
        "t": "XNAS:AAPL",
        "region": "usa",
        "culture": "en-US",
        "cur": "",
        "_": "1444848178406"
    })

    tree_details = html.fromstring(response.content)
    print tree_details.xpath('.//th[@class="row_lbl"]//text()')

rawDescription: Web scraping, getting empty list

description: Web scraping, getting empty list


code: print sorted(l, key=lambda item: int(item[1:]))

rawDescription: Most pythonic way to reorder repeating list


code:
from bs4 import BeautifulSoup, Comment

html = """

p tag text

I would like to get this text

I would also like to find this text

"""
soup = BeautifulSoup(html, 'lxml')

for comment in soup.findAll(text=lambda text:isinstance(text, Comment)):
    if comment in ['UNIQUE COMMENT', 'SECOND UNIQUE COMMENT']:
        print comment.next_element.strip()

rawDescription: Extracting Text Between HTML Comments with BeautifulSoup


code:
import threading;

def display ():
    threading.Timer(1., display).start ();
    print "display"

display ()

rawDescription: python get arrow keys from command line

description: Python get arrow keys from command line


code:
rd = csv.reader(fd, delimiter=' ', skipinitialspace=True)
for row in rd:
    print row

rawDescription: How to remove more than one space when reading text file

description: Remove more than one space when reading text file


code:
# original
print row.xpath(".//td[@class='time']/text()").extract()
# ported
print extract_text(row.find(r'.//td[@class="time"]'))

rawDescription: converting scrapy to lxml

description: Converting scrapy to lxml


code:
import lxml.html
import requests

url = 'http://www.hltv.org/?pageid=2'
response = requests.get(url)

tree = lxml.html.fromstring(response.content)
for item in tree.xpath('//div[@class="centerNoHeadline"]//div[@class="hotmatchbox"]//div[@class="hotmatchbox"]/div/img/following-sibling::text()'):
    print item.strip()

rawDescription: XPath not "seeing" the img element?

description: XPath not "seeing" the img element


code:
counter = {}

for s in (listOfLists):
    for elem in s:
        counter[elem] = counter.get(elem, 0) + 1

for item, nbItems in counter.iteritems():
    if nbItems == 3:
        print '%s belongs to three lists.' % item

rawDescription: How to get the smallest list of duplicate items from list of lists?

description: Get the smallest list of duplicate items from list of lists


code:
p = re.compile(r'texture\s+(\S+)\s+\[(\d+\s+\d+\s+\d+)\]\s+(.*?)\n\s*\n', re.DOTALL)
matches = p.findall(input)
for match in matches:
    print match[0]
    print match[1]
    print match[2]
    print "---------------"

rawDescription: Python multiline regular expression

description: Python multiline regular expression


code:
temp, result = {(cd["dept"], cd["sku"]):cd["qty"] for cd in returned}, []

for cd in sold:
    temp_dict = {}
    for k, v in cd.items():
        if k == "sold":
            temp_dict["sold"] = cd["qty"]
        else:
            temp_dict[k] = cd[k]
    temp_dict["return"] = temp.get((cd["dept"], cd["sku"]), 0)
    result.append(temp_dict)

print result

rawDescription: Merge multiple lists of dictionaries and rename the key


code:
code
with open("0.txt") as f:
    t=[x.rstrip("\n").split("\t") for x in f.readlines()]
    intervals=[(int(x[0]),int(x[1])) for x in t]

def find_ints(intervals, mn, mx):
    next_start = mn
    for x in intervals:
        if next_start < x[0]:
            yield next_start,x[0]
            next_start = x[1]
        elif next_start < x[1]:
            next_start = x[1]
    if next_start < mx:
        yield next_start, mx

print list(find_ints(intervals, 0, 200))

rawDescription: Python interval interesction

description: Python interval interesction


code:
from __future__ import division

import numpy as np

def find_transition_times(t, y, threshold):
    """
    Given the input signal `y` with samples at times `t`,
    find the times where `y` increases through the value `threshold`.

    `t` and `y` must be 1-D numpy arrays.

    Linear interpolation is used to estimate the time `t` between
    samples at which the transitions occur.
    """
    # Find where y crosses the threshold (increasing).
    lower = y < threshold
    higher = y >= threshold
    transition_indices = np.where(lower[:-1] & higher[1:])[0]

    # Linearly interpolate the time values where the transition occurs.
    t0 = t[transition_indices]
    t1 = t[transition_indices + 1]
    y0 = y[transition_indices]
    y1 = y[transition_indices + 1]
    slope = (y1 - y0) / (t1 - t0)
    transition_times = t0 + (threshold - y0) / slope

    return transition_times

def periods(t, y, threshold):
    """
    Given the input signal `y` with samples at times `t`,
    find the time periods between the times at which the
    signal `y` increases through the value `threshold`.

    `t` and `y` must be 1-D numpy arrays.
    """
    transition_times = find_transition_times(t, y, threshold)
    deltas = np.diff(transition_times)
    return deltas

if __name__ == "__main__":
    import matplotlib.pyplot as plt

    # Time samples
    t = np.linspace(0, 50, 501)
    # Use a noisy time to generate a noisy y.
    tn = t + 0.05 * np.random.rand(t.size)
    y = 0.6 * ( 1 + np.sin(tn) + (1./3) * np.sin(3*tn) + (1./5) * np.sin(5*tn) +
               (1./7) * np.sin(7*tn) + (1./9) * np.sin(9*tn))

    threshold = 0.5
    deltas = periods(t, y, threshold)
    print "Measured periods at threshold %g:" % threshold
    print deltas
    print "Min:  %.5g" % deltas.min()
    print "Max:  %.5g" % deltas.max()
    print "Mean: %.5g" % deltas.mean()
    print "Std dev: %.5g" % deltas.std()

    trans_times = find_transition_times(t, y, threshold)

    plt.plot(t, y)
    plt.plot(trans_times, threshold * np.ones_like(trans_times), 'ro-')
    plt.show()

rawDescription: Digitizing an analog signal

description: Digitizing an analog signal


code:
class A(object):
    def __init__(self):
        self.x = 1 # set some attribute

    def __getattr__(self,attr):
        try:
            return super(A, self).__getattr__(attr)
        except AttributeError:
            return self.__get_global_handler(attr)

    def __get_global_handler(self, name):
        # Do anything that you need to do before simulating the method call
        handler = self.__global_handler
        handler.im_func.func_name = name # Change the method's name
        return handler

    def __global_handler(self, *args, **kwargs):
        # Do something with these arguments
        print "I am an imaginary method with name %s" % self.__global_handler.im_func.func_name
        print "My arguments are: " + str(args)
        print "My keyword arguments are: " + str(kwargs)

    def real_method(self, *args, **kwargs):
        print "I am a method that you actually defined"
        print "My name is %s" % self.real_method.im_func.func_name
        print "My arguments are: " + str(args)
        print "My keyword arguments are: " + str(kwargs)

rawDescription: Instance of Python class that responds to all method calls


rawDescription: Split string by unique patterns

description: Split string by unique patterns


code:
v = 10*units.miles/units.hour
print v # = 2794*m/(625*s)

print v.subs(converter) # = 10*mile/hour

rawDescription: SymPy: How to return an expression in terms of other expression(s)?


code:
pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT)
for line in pMerge.stdout:
    print line,

rawDescription: Python subprocess + mencoder not working, same command works in terminal


code:
import datetime
args1 = 2014, 10, 01
args2 = 2014, 10, 01, 12
args3 = 2014, 10, 01, 12, 25
'{0}'.format(datetime.datetime(*args1))
'{0}'.format(datetime.datetime(*args2))
'{0}'.format(datetime.datetime(*args3))

rawDescription: Pythonic insertion of variable number of arguments into a string


code:
a = "ACdA(a = %b, ccc= 2r2)"
b = "\ewfsd\ss.jpg"
print a[:-1] + ', b_holder = ' + b + ')'

rawDescription: Python: Regular expression to change image filename


code:
from multiprocessing import Pool, current_process

def start_exe():
    return 'done', current_process().name

if __name__ == '__main__':
    p = Pool(5)
    result = p.apply_async(start_exe)

    print result.get()

rawDescription: In multiprocess module of python , how to find which worker process has executed the job


code:
NAND_TIME= (Literal("NAND TIMES") + Word(nums)+Literal(":").suppress()+Word(nums)).setParseAction(lambda t: print_cal('NAND TIME'))
TEST_TIME= (Literal("TEST TIMES") + Word(nums)+Literal(":").suppress()+Word(nums)).setParseAction(lambda t: print_cal('TEST TIME'))
testing =NAND_TIME | TEST_TIME

testdata = f.read()
for match in testing.searchString(testdata):
    print match.asList()

rawDescription: PyParsing : how to use SkipTo and OR(^) operator


code:
all_instances_of_foo = allInstancesOfFoo[:]
print all(x is y for x,y in zip(all_instances_of_foo,allInstancesOfFoo))  #True

rawDescription: Will adding an instance of a class to a list copy the instance or just 'reference' it?


code:
with open("sample.txt") as f:
    lines = f.readlines()
    print sorted(lines, key=lambda x:float(x.split(';')[0]), reverse=True)

rawDescription: sort text file by first element

description: Sort text file by first element


code: raise RuntimeException, "The variable does not exist in the expression."

rawDescription: Python returns list but to variable, but variable is null


code:
for i in range(27):
    if (i >= 0) and (i <= 11):
        print "   value %d = %02X" % (i, data.next())
    elif (i >= 16) and (i <= 27):
        print "   value %d = %02X" % (i, data.next())
    else:
        data.next()

rawDescription: How to skip ahead a certain number with .next()

description: Skip ahead a certain number with .next()


code:
import arcpy
columns = ['column1', 'something', 'someothercolumn']
curObj = arcpy.da.SearchCursor(r"C:/somefile.shp", columns)
for row in curObj:
    print 'column1 is', row[0]
    print 'someothercolumn is', row[2]

rawDescription: iterating through attribute tables (ArcGIS 10.1, Python)

description: Iterating through attribute tables (ArcGIS 10.1, Python)


code:
# Will print the same as the others:
print np.einsum('ij,ji->', a, b)

rawDescription: What is the best way to compute the trace of a matrix product in numpy?


code: print ".".join(x.name for x in fixedpoint(lambda p:p.parent, self, None))

rawDescription: How to walk up a linked-list using a list comprehension?

description: Walk up a linked-list using a list comprehension


code:
def userOptions(event):
    count = IntVar()
    pattern = r'[-\w]+'

    # find the beginning of the "word", starting _after_
    # the character clicked on
    start = "@%d,%d +1c" % (event.x, event.y)
    index1 = text.search(pattern, start, backwards=True, regexp=True)

    # starting with the beginning, find the end and save
    # the number of characters that matched.
    text.search(pattern, index1, regexp=True, count=count)

    # compute the ending index of the match
    index2=text.index("%s + %s c" % (index1, count.get()))

    # get the text
    user = text.get(index1, index2)
    print user
    return

rawDescription: Tkinter indexing words issue

description: Tkinter indexing words issue


code:
#!/usr/bin/env python
import ctypes
from ctypes import POINTER, c_int, c_void_p
class Node(ctypes.Structure):
    pass
Node._fields_ = (
        ("self", c_void_p),
        ("next", POINTER(Node)),
        ("value", c_int),
        )

def define_function(res, args, paramflags, name, lib):

    prot = ctypes.CFUNCTYPE(res, *args)
    return prot((name, lib), paramflags)

def main():

    import os.path

    libpath = os.path.abspath("libnode.so")
    lib = ctypes.cdll.LoadLibrary(libpath)

    allocate_nodes = define_function(
            res=POINTER(Node),
            args=(
                c_int,
                ),
            paramflags=(
                (1, "n"),
                ),
            name="allocate_nodes",
            lib=lib,
            )

    deallocate_nodes = define_function(
            res=None,
            args=(
                POINTER(Node),
                ),
            paramflags=(
                (1, "cptr"),
                ),
            name="deallocate_nodes",
            lib=lib,
            )

    node_ptr = allocate_nodes(10)

    n = node_ptr[0]
    print "value", "f_ptr", "c_ptr"
    while True:
        print n.value, n.self, ctypes.addressof(n)
        if n.next:
            n = n.next[0]
        else:
            break

    deallocate_nodes(node_ptr)

if __name__ == "__main__":
    main()

rawDescription: interoperability between Cpython and fortran linked lists

description: Interoperability between Cpython and fortran linked lists


code:
TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

print ' '.join(TEST.split())
# Prints:
# This is a test with a mix of tabs, newlines and repeating whitespace

rawDescription: Is there a string-collapse library function in python?


code:
import re

with open('imperfections', 'r') as imp:
  imperfections = imp.readlines()
with open('code', 'r') as cod:
  code = cod.readlines()
for imp in imperfections:
  parsed = re.search('(.*); \((\w+) NEEDS (\w+)', imp)
  find = parsed.group(1).replace('(', '\(')
  find = find.replace(')', '\s*(\{.*\})*\)')
  find = find.replace(';', ';\s*(\{.*\})*')
  replace = parsed.group(2)
  replace_with = ' '.join([parsed.group(3), replace])
  #print 'find: "%s" replace "%s" with "%s"' % (find, replace, replace_with)
  for line in code:
    match = re.search(find, line)
    if match:
        print re.sub(replace, replace_with, line)[:-1]

rawDescription: python regex ignoring text

description: Python regex ignoring text


code:
from select import *

# the rest of your code until the reading loop

while True:
    for line in f:
        print line
    kq = kqueue()
    kq.control([kevent(f.fileno(), filter=KQ_FILTER_READ, flags=KQ_EV_ADD)], 0, 0)
    kq.control(None, 1)
    kq.close()

rawDescription: Read a file continuously and sending the output to another file


code:
for file_hash, file_path in hash_vs_file.iteritems():
    if len(file_path) > 1:
        print file_path
        print file_hash

rawDescription: filter list of values in a dictionary

description: Filter list of values in a dictionary


code:
if any(x > 5 in di):
    print "some digit was greater than five"

rawDescription: Find sequences of digits in long integers efficiently


code:
import urllib2
from bs4 import BeautifulSoup

url = "http://www.hdwallpapers.in/cars-desktop-wallpapers/page/2"
soup = BeautifulSoup(urllib2.urlopen(url))

links = soup.find_all('div', {'class': 'pagination'})[1].find_all('a')

print next('/'.join(link['href'].split('/')[:-1]) for link in links
           if link.text.isdigit() and link.text != "1")

rawDescription: Improving a python snippet

description: Improving a python snippet


code:
from django.utils.html import mark_safe

class ParagraphTag(object):

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

    def __str__(self):
        return mark_safe('<p>{}</p>'.format(self.text + 'baz'))

print str(ParagraphTag("foo")).__class__
print str(ParagraphTag("foo"))
print
print unicode(ParagraphTag("foo")).__class__
print unicode(ParagraphTag("foo"))
print mark_safe(unicode(ParagraphTag("foo"))).__class__

rawDescription: Marking a class as "safe" for rendering in templates


code: print '\n'.join(' ' * len('\\'.join(x[:p])) + '\\'.join(x)[len('\\'.join(x[:p])):] for p, x in eachWithPrefix(x.split('\\') for x in v))

rawDescription: How to group strings with similar beginnings in a sorted list?

description: Group strings with similar beginnings in a sorted list


code:
import re

def find_header(lines):
  for (i, line) in enumerate(lines):
    if 'eng_tot' in line.split():
      return i
  return None

def find_next_separator(lines, start):
  for (i, line) in enumerate(lines[start+1:]):
    if re.match("\s*-+\s*", line):
      return i + start + 1
  return None

if __name__ == '__main__':
  totals = []
  lines = open('so.txt').readlines()

  header = find_header(lines)
  start = find_next_separator(lines, header+1)

  while True:
    end = find_next_separator(lines, start+1)
    if end is None: break

    # Pull out block, after line of dashes.
    metrics_block = lines[start+1:end]

    # Pull out 2nd column from 1st line of metrics.
    eng_total = metrics_block[0].split()[1]
    totals.append(eng_total)

    start = end

  print totals

rawDescription: How to extract data from an irregularly formatted data file in python

description: Extract data from an irregularly formatted data file in python


code:
text = """this is part 1, this is part 2, this is part 3
this is part 4, this is part 5, this is part 6
this is part 7, this is part 8, this is part 9"""

for t in text.split("\n"):
    print t.split(',')[0]

rawDescription: How do you print certain words in a text file that are between commas?

description: Print certain words in a text file that are between commas


code:
proc = subprocess.Popen(["bjobs"],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
print proc.stdout.read()

rawDescription: Python redirecting output from an LSF command


code:
import csv
import requests

r = requests.get('http://vote.wa.gov/results/current/export/MediaResults.txt')
data = r.text
reader = csv.reader(data.splitlines(), delimiter='\t')
for row in reader:
    print row

rawDescription: Tab-delimited file using csv.reader not delimiting where I expect it to


code:
import pandas as pd
import numpy as np

k = 5
N = 10

alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')

#http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html

df = pd.DataFrame({ 'A' : range(1, N + 1 ,1),
    'B' : np.random.randint(k, k + 100 , size=N),
    'C' : np.random.choice(np.array(alphabet, dtype="|S1"), N) })

print df
#    A    B  C
#0   1   16  U
#1   2   76  X
#2   3  101  N
#3   4   61  F
#4   5   52  J
#5   6   62  A
#6   7   99  L
#7   8   23  N
#8   9   75  D
#9  10   16  Q

rawDescription: pandas create a series with n elements (sequential or randbetween)

description: Pandas create a series with n elements (sequential or randbetween)


code:
def tabClicked(self):
    print "tab clicked!"
    some_intiger = 0
    self.tabClicked.emit(some_intiger)

rawDescription: PyQt4: How/when to emit custom signal from subclass of QTabWidget?


code:
print '%r' % 'ऋ ॠ ऌ'
print '%s' % 'ऋ ॠ ऌ'

rawDescription: Tried to print letter of hindi and strange output


code:
def combining_function (max_a, min_a):
    constants = { }
    checks    = []

    if max_a is not None:
        constants['max_a'] = max_a
        checks.append ('x.a < max_a')

    if min_a is not None:
        constants['min_a'] = min_a
        checks.append ('x.a > min_a')

    if not checks:
        return lambda x: True
    else:
        func = 'def check (x): return (%s)' % ') and ('.join (checks)
        exec func in constants, constants
        return constants['check']

class X:
    def __init__(self, a):
        self.a = a

check = combining_function (3, 1)
print check (X (0)), check (X (2)), check (X (4))

rawDescription: Can you dynamically combine multiple conditional functions into one in Python?

description: Dynamically combine multiple conditional functions into one in Python


code:
def func1(a):
    def func2(b):
        c = a + b
        print c
    return func2

rawDescription: What's a variable in a inner function definition in python?


code:
import pipes
dirname='/path/to/directory with spaces'
foo_val='value with * wildcards * that need escaping and \t\t tabs!'
print 'cd %s; export FOO=%s;' % (pipes.quote(dirname), pipes.quote(foo_val))

rawDescription: Change parent shell's environment from a subprocess


code:
from c import MyGlobals

def func2():
    print MyGlobals.x
    MyGlobals.x = 2

rawDescription: make variable global to multiple files in python

description: Make variable global to multiple files in python


code:
for letters in zip('hello', 'apple', 'green', 'paint', 'sting'):
  print letters

rawDescription: In Python, is it possible to unpack a list of strings and put a single character from each string into a generator?


code:
primers_names_list = [
{'part number': 1, 'notes': 'Fw Gibson primer on pEM113 to extract CmR resistance and pSC101 backbone and T7 promoter and term.', 'direction': 'fw primer', 'construct': '24', 'source': 'pEM113'},
{'part number': 1, 'notes': 'Re Gibson primer on pEM113 to extract CmR resistance and pSC101 backbone and T7 promoter and term.', 'direction': 're primer', 'construct': '24', 'source': 'pEM113'},
{'part number': 2, 'notes': 'Fw Gibson primer on BBa_K274100 to extract crtEBI operon', 'direction': 'fw primer', 'construct': '24', 'source': 'BBa_K274100'},
{'part number': 2, 'notes': 'Re Gibson primer on BBa_K274100 to extract crtEBI operon', 'direction': 're primer', 'construct': '24', 'source': 'BBa_K274100'},
{'part number': 1, 'notes': 'Fw Gibson primer on pEM114 to extract CmR resistance and pSC101 backbone and K1F promoter and term.', 'direction': 'fw primer', 'construct': '25', 'source': 'pEM114'},
{'part number': 1, 'notes': 'Re Gibson primer on pEM114 to extract CmR resistance and pSC101 backbone and K1F promoter and term.', 'direction': 're primer', 'construct': '25', 'source': 'pEM114'},
]

primers_without_names = [
{'Part Number': '1', 'Construct Number': '24', 'Direction': 're primer', 'Primer Sequence': 'agaccgtcatctagtacctcTCTCCCTATAGTGAGTCGTATTACTCTAGAAGCGGCCGCg'},
{'Part Number': '1', 'Construct Number': '24', 'Direction': 'fw primer', 'Primer Sequence': 'tggaggatctgatataataaTAGCATAACCCCTTGGGGCCTCTAAACGGGTCTTGAGGGG'},
{'Part Number': '2', 'Construct Number': '24', 'Direction': 'fw primer', 'Primer Sequence': 'TACGACTCACTATAGGGAGAgaggtactagatgacggtctgcgcaaaaaaacacgttcat'},
{'Part Number': '2', 'Construct Number': '24', 'Direction': 're primer', 'Primer Sequence': 'GGCCCCAAGGGGTTATGCTAttattatatcagatcctccagcatcaaacctgctgtcgct'},
{'Part Number': '1', 'Construct Number': '25', 'Direction': 're primer', 'Primer Sequence': 'agaccgtcatctagtacctcTCTCCCTATAGTGATAGTTATTACTCTAGAAGCGGCCGCg'},
{'Part Number': '1', 'Construct Number': '25', 'Direction': 'fw primer', 'Primer Sequence': 'tggaggatctgatataataaTAGCATAACCCCTTGGGGCCTCTAAACGGGTCTTGAGGGG'},
{'Part Number': '2', 'Construct Number': '25', 'Direction': 'fw primer', 'Primer Sequence': 'TAACTATCACTATAGGGAGAgaggtactagatgacggtctgcgcaaaaaaacacgttcat'},
{'Part Number': '2', 'Construct Number': '25', 'Direction': 're primer', 'Primer Sequence': 'GGCCCCAAGGGGTTATGCTAttattatatcagatcctccagcatcaaacctgctgtcgct'},
]

primers_with_names = []
for row in primers_names_list: #recall that primers_names_list is a list of dictionaries
    for x in primers_without_names:
        if (
            int(x['Part Number']) == row['part number'] and
            x['Construct Number'] == row['construct'] and
            x['Direction'] == row['direction']
        ):
            primers_with_names.append(
                {
                    'part number': row['part number'],
                    'construct number': row['construct'],
                    'notes': row['notes'],
                    'primer sequence':x['Primer Sequence']
                }
            )
            # If you are only expecting one match from the primers_without_names
            # collection, or wish to enforce that, you can add a break statement after
            # the insertion here to break out of the inner comparison loop and move on
            # to the next row item

for p in primers_with_names:
    print p

print
print len(primers_with_names)

rawDescription: How to check whether a subset of dictionary items exists in another list of dictionaries?

description: Check whether a subset of dictionary items exists in another list of dictionaries


code:
for sent in brown.tagged_sents():
    if any(pos for word, pos in sent if pos == 'NPS'):
            print " ".join([word for word, pos in sent])
            break

from nltk import pos_tag
pos_tag("Georgia Republicans are getting strong encouragement to enter a candidate in the 1962 governor's race , a top official said Wednesday .".split())

rawDescription: Provoke the NLTK part-of-speech tagger to report a plural proper noun


code:
for x in range (2,13):
    print "{0:d} - {1:d} {2:0.4f}%".format(x, results[x], results[x] / count * 100)

print("Doubles- {0:d}-{1:0.6f}%".format(number_of_double_dice, number_of_double_dice / count *100))

rawDescription: Rolling two dice and tabulating outcomes


code:
from itertools import combinations
from string import ascii_lowercase as alphabet

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
          47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
letter_id = dict(zip(alphabet, primes))

def get_word_id(word):
    product = 1
    for letter in word:
        product *= letter_id[letter]
    return product

words = ['sidecar', 'owl', 'low', 'acid', 'bread', 'slower']
dictionary = {}
for w in words:
    dictionary[w] = get_word_id(w)

base_string = 'Oscar Wilde'

for comb in combinations(words, 2):
    comb_id = 1
    for word in comb:
        comb_id *= dictionary[word]
    if get_word_id(base_string.replace(' ', '').lower()) == comb_id:
        print comb

rawDescription: Python: anagram finder

description: Python: anagram finder


code:
import foo
import os
print os.path.dirname(foo.__file__)
foo.foo()

rawDescription: Finding a module's directory

description: Finding a module's directory


code:
def distance_from_zero(n):
    try:
        return abs(float(n))
    except ValueError:
        print "Not a number!"
        return float("NaN")  # or remove this line to return None

rawDescription: Review: Built-In Functions

description: Review: Built-In Functions


code:
import itertools

a = [(1, 'a'), (1, 'b'), (2, 'c')]

# groupby need sorted value so sorted in case
a.sort(key=lambda x:x[0])

for i, j in itertools.groupby(a, key=lambda x:x[0]):
    print i, [k[1] for k in j]

rawDescription: Pythonistas, how do I move data from top to bottom to left to right in MySQL (think multiple values for each ID)?


code:
from cStringIO import StringIO
import xml.etree.ElementTree
from xml.etree import ElementTree as ET

doc = StringIO("""
<document>
 <title>People working for me</title>
 <person xmlns:foaf="http://xmlns.com/foaf/0.1/"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
   <name>Jim</name>
   <title>Porch Light Switcher</title>
   <foaf:homepage rdf:resource="http://example.com/his_page" />
 </person><person>
   <name>Joe</name>
   <title>Bottle Washer, 3rd class</title>
   <nick xmlns="http://xmlns.com/foaf/0.1/">Joe-Joe</nick>
 </person>
</document>
""")

tree = ET.parse(doc)
print tree.findall("person/title")

rawDescription: Is there a function to get an element by its DOM address?


code:
a = range(5)
b = range(5)
c = range(5)
d = [a, b, c]
for items in itertools.izip(*d):
    for item in items:
        print item,
for item in itertools.chain(*d):
    print item,

rawDescription: An elegant and fast way to consecutively iterate over two or more containers in Python?


code:
import re

def Main():
    m = "12312312ranger12312319"
    pattern = re.compile('\d(\d$)')
    r = pattern.search(m)
    if r:
        print r.group(0) + ' ' + r.group(1)
    else:
        print "Not Matched"

if __name__ == '__main__':
    Main()

rawDescription: Getting more matches than the expected in python


code:
header = "000100a0"
footer = "00000000000"

with open('bindata.txt', 'r') as f:
    data = f.read()
    print "Data: %s" % data
    header_index = data.find(header, 0)
    footer_index = data.find(footer, 0)
    if header_index >= 0 and footer_index >= header_index:
        print "Found header at %s and footer at %s" \
              % (header_index, footer_index)
        body = data[header_index + len(header): footer_index]
        while body is not None:
            print "body: %s" % body
            header_index = data.find(header,\
                                     footer_index + len(footer))
            footer_index = data.find(footer,\
                                     footer_index + len(footer) + len(header) )
            if header_index >= 0 and footer_index >= header_index:
                print "Found header at %s and footer at %s" \
                       % (header_index, footer_index)
                body = data[header_index + len(header): footer_index]
            else:
                body = None

rawDescription: Taking a hex file and extracting data

description: Taking a hex file and extracting data


code:
for ij in indices:
    print ij

rawDescription: Is there a Python library for handling complicated mathematical sets (constructed using mathematical set-builder notation)?


code:
import example
b = example.make_B()
print b.var
b.var = 0

rawDescription: boost.python exposing members of members

description: Boost.python exposing members of members


code:
def f(a):
    def inner(h, a):
        print h+a
        return lambda (x): inner(h+1, x)
    return inner(1, a)

rawDescription: Simulate static variables in python with closures


code:
import dateutil.parser as dateparser

date_list = ['1963 to 1969',
             'Aug. 1968 to Sept. 1968',
             'Mar-73',
             '24-Jul',
             'Oct. 2 1980',
             'Aug 29, 1980',
             'July 1946',
             'undated']

for d in date_list:
    if 'to' in d:
        a, b = d.split('to')
        # Get the higher number. Use min to get lower of two.
        print max(dateparser.parse(a.strip()).year, dateparser.parse(b.strip()).year)
    elif d == 'undated':
        print '0000'
    else:
        yr = dateparser.parse(d).year
        print yr

rawDescription: Dates to categories

description: Dates to categories


code:
#for contour
def p_0(num,t) :
    esc_p = np.sum((((-1)**n)*(np.exp(t)**n)*((math.factorial(n)*((n+1)**0.5))**-1)) for n in range(1,num,1))
    return esc_p+1

tau = np.arange(-2,3,0.1)

x,y= np.meshgrid(tau,tau)
cs = plt.contour(x, y, np.log(p_0(51, y)/p_0(51, x)),[0.2],colors='k')

p=0.75
logp = (np.log(p*np.exp(tau)))
plt.plot(tau,logp)

from shapely.geometry import LineString
v1 = cs.collections[0].get_paths()[0].vertices

ls1 = LineString(v1)
ls2 = LineString(np.c_[tau, logp])
points = ls1.intersection(ls2)
x, y = points.x, points.y

from scipy import optimize

def f(p):
    x, y = p
    e1 = np.log(0.75*np.exp(x)) - y
    e2 = np.log(p_0(51, y)/p_0(51, x)) - 0.2
    return e1, e2

x2, y2 = optimize.fsolve(f, (x, y))

plt.plot(x, y, "ro")
plt.plot(x2, y2, "gx")

print x, y
print x2, y2

rawDescription: Finding intersection between straight line and contour


code:
from urllib import quote
from urlparse import urlparse, urlunparse

url = "http://www.website.com/search/si/1/doctors/Vancouver, BC"

scheme, netloc, path, params, query, fragment = urlparse(url)
path = quote(path)
print urlunparse((scheme, netloc, path, params, query, fragment))

rawDescription: python: encode a url with percentage signs?

description: Python: encode a url with percentage signs


code:
import urllib2

data = urllib2.urlopen("http://www.google.com").read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines

for line in data:
    print line

rawDescription: In Python, given a URL to a text file, what is the simplest way to read the contents of the text file?


code:
import multiprocessing
import subprocess

def calculate(value):
    return value * 10

if __name__ == '__main__':
    pool = multiprocessing.Pool(None)
    tasks = range(10000)
    results = []
    r = pool.map_async(calculate, tasks, callback=results.append)
    r.wait() # Wait on the results
    print results

rawDescription: How to spawn parallel child processes on a multi-processor system?

description: Spawn parallel child processes on a multi-processor system


code:
import inspect
print inspect.getsource(pos_tag)

rawDescription: Probing a python function

description: Probing a python function


code:
class MyObject(object):

    def method(self):
        print "method called on %s" % str(self)

    @property
    def result(self):
        return "Some derived property"

    def common(self, a=None):
        print self

def my_decorator(func):
    def _wrapped(*args, **kwargs):
        print "Calling decorated function %s" % func
        return func(*args, **kwargs)
    return _wrapped

class WrappedObject(object):

    def __init__(self, cls):
        for attr, item in cls.__dict__.items():
            if attr != '__init__' and callable(item):
                setattr(cls, attr, my_decorator(item))
            elif  isinstance(item, property):
                new_property = property(my_decorator(item.__get__), item.__set__, item.__delattr__)
                setattr(cls, attr, new_property)
        self._cls = cls

    def __call__(self, *args, **kwargs):
        return self._cls(*args, **kwargs)

inst = WrappedObject(MyObject)()

rawDescription: Decorating a class method after @property


code:
query_separate_sql
[]
[]
[(1L,)]

rawDescription: Python MySQLdb doesn't wait for the result


code:
# make some objects, some FooA, some FooB
fa = FooA('a', 'b', 'c','d')
fb = FooB('xx', 'yy', 'zz')
fc = FooA('e', 'f', 'g','h')

# create list of items that are FooA's, or FooA lookalikes
coll = [fa, FooAMimic(fb), fc]

# access objects like FooA's, but notice that the wrapped FooB
# attributes are still available too
for f in sorted(coll, key=lambda k : k.id):
    print f.id, '=',
    try:
        print f.namefoo, "(really a namefoo)"
    except AttributeError:
        print f.name

rawDescription: Best way to construct a "complex" data structure in Python

description: Construct a "complex" data structure in Python


rawDescription: Space between words in matplotlib plot axis label


code:
f = open('tempfile', 'w'); f.close()
os.system('icacls tempfile /deny Guests:(M)')
print get_file_security('tempfile')

rawDescription: Python - Get windows folder ACL permissions


code:
# Enter the main loop, where we check to see if there's a shot to upload
# every 1 second
path = cfg.get("paths","watch_path")
def check_for_new():

    if(os.path.exists(path)):
        linup.uploadImage(path)
        url = linup.getURL()
        linup.toClipboard(url)
        linup.json = ""

        print "Screenshot uploaded!"
        os.remove(path)
    # Return True to keep calling this function, False to stop.
    return True

if __name__ == "__main__":

    gobject.timeout_add(1000, check_for_new)

    gtk.main()

rawDescription: Pygtk StatusIcon not loading?

description: Pygtk StatusIcon not loading


code:
for i in mylist:
   print "student: %s" % i.student

rawDescription: How to display object properties in python

description: Display object properties in python


code:
def unzip_artifact( local_directory, file_path ):
    fileName, ext = os.path.splitext( file_path )
    if ext == ".zip":
        print 'unzipping file ' + basename(fileName) + ext
        try:
            zipfile.ZipFile(file_path).extractall(local_directory)
        except zipfile.error, e:
            print "Bad zipfile: %s" % (e)
        return

rawDescription: unzip extract in python

description: Unzip extract in python


code:
import re

def manip(m):
    return m.groups()[0].lower()

data = ['CAT{TT} Dog{DD} Horse{AA}',
        'Snail{LL} RAT{TT}',
        'ANT{AA}']

for line in data:
    new_line = re.sub(r'((?:[^{]|^)[A-Z]+(?:[^}]|$))', manip, line)
    print new_line

rawDescription: Working with pieces of text in python

description: Working with pieces of text in python


code:
import matplotlib.pyplot as plt

start = 97523.29783
increment = .000378912098
target = 97585.23452

# build a timeline
times = []
time = start
actual_index = None
for i in range(1000000):
    trunc = float(str(time)[:10])  # truncate the time value
    times.append(trunc)
    if actual_index is None and time>target:
        actual_index = i
    time = time + increment

# now test
intervals = [1, 2, 5, 10, 100, 1000, 10000]

for i in intervals:
    dt = (times[i] - times[0])/i
    index = int((target-start)/dt)
    print "    %6i  %8i  %8i  %.10f" % (i, actual_index, index, dt)

rawDescription: Can I make an O(1) search algorithm using a sorted array with a known step?

description: Make an O(1) search algorithm using a sorted array with a known step


code:
choice = 'restart';

while choice == 'restart':
        choice = raw_input('What do you want? ')

print 'Break!'

rawDescription: How to restart a simple coin tossing game

description: Restart a simple coin tossing game


code:
import re
Field= "In Field 'Testing':(Value1) has changed from (1) to (2)"
print re.findall("'(.*?)'", Field) #Will print Testing

rawDescription: Catching a selected text from the string in python


code:
import re

data = []

for block in re.findall(r'(?s)\|-(.+?)(?=\|-|})', text):
    r = [x.split()[-1] for x in re.findall(r'\[(.+?)\]', block)]
    if r:
        data.append(r)

print data

rawDescription: Parsing text within block "|-" and "|- or }"


code:
import lxml.etree

data = """
<document>
    <pages>

    <page>
       <paragraph>XBV</paragraph>

       <paragraph>GFH</paragraph>
    </page>

    <page>
       <paragraph>ash</paragraph>

       <paragraph>lplp</paragraph>
    </page>

    </pages>
</document>
"""

tree = lxml.etree.fromstring(data)
print [item.text for item in tree.xpath("./pages/page/paragraph[contains(text(),'ash')]//preceding::paragraph")]

rawDescription: Python lxml: How to traverse back up a tree


rawDescription: how to perform an inner or outer join of DataFrames with Pandas on non-simplistic criterion

description: Perform an inner or outer join of DataFrames with Pandas on non-simplistic criterion


code:
for encoded_content in soup.findAll("encoded"):
    for child in encoded_content.children:
        print child

rawDescription: Reading <content:encoded> tags using BeautifulSoup 4


code: print handle_csrf.__doc__

rawDescription: How do I break a link in a rst docstring to satisfy pep8?

description: Break a link in a rst docstring to satisfy pep8


code:
for lst in (l1,l2,l3):  #parenthesis unnecessary, but I like them...
    print lst   #[ 1, 2, 3 ]
                #[ 4, 5, 6 ]
                #[ 7, 8, 9 ]

rawDescription: Printing all the values from multiple lists at the same time


code:
phonebook = [
           {'name':'R','email': 'r@gmail.com','phone':'905-246-1234'},
           {'name':'A','email': 'a@gmail.com','phone':'416-275-4565'},
           {'name':'S','email': 's@gmail.com','phone':'905-478-2690'},
           {'name':'T','email': 't@gmail.com','phone':'647-756-2552'},
           {'name':'Bob','email': 'bob@gmail.com','phone':'905-456-5789'}
           ]
name=input("Enter the name you would like to search for :  ")
print next((item for item in phonebook if item["name"] == name),"Does not exist")

rawDescription: Phonebook dictionary

description: Phonebook dictionary


code:
import re

def get_words_from_string(s):
    return set(re.findall(re.compile('\w+'), s.lower()))

def get_words_from_file(fname):
    with open(fname, 'rb') as inf:
        return get_words_from_string(inf.read())

def all_words(needle, haystack):
    return set(needle).issubset(set(haystack))

def any_words(needle, haystack):
    return set(needle).intersection(set(haystack))

search_words = get_words_from_string("This is my test")
find_in = get_words_from_string("If this were my test, I is passing")

print any_words(search_words, find_in)

print all_words(search_words, find_in)

rawDescription: Extract Words from a file

description: Extract Words from a file


code:
import collections
import itertools
from operator import itemgetter

from django.db import connection

cursor = connection.cursor()
cursor.execute('SELECT car_id, mod_id FROM someapp_car_mod ORDER BY 1, 2')
cars = collections.defaultdict(list)
for row in cursor.fetchall():
    cars[row[0]].append(row[1])

# Here's one I prepared earlier, which emulates the sample data we've been working
# with so far, but using the car id instead of the previous string.
cars = {
    1: [1,2],
    2: [2],
    3: [1],
    4: [1,2],
    5: [1],
    6: [2],
    7: [1,2,3],
    8: [1,2],
}

sorted_cars = sorted(cars.iteritems(), key=itemgetter(1))
cars_by_common_mods = []
for k, g in itertools.groupby(sorted_cars, key=itemgetter(1)):
    cars_by_common_mods.append({'mods': k, 'cars': map(itemgetter(0), g)})

print cars_by_common_mods

# Which, for the sample data gives me (reformatted by hand for clarity)
[{'cars': [3, 5],    'mods': [1]},
 {'cars': [1, 4, 8], 'mods': [1, 2]},
 {'cars': [7],       'mods': [1, 2, 3]},
 {'cars': [2, 6],    'mods': [2]}]

rawDescription: Django/Python - Grouping objects by common set from a many-to-many relationships