code:
print timeit.timeit("pf(600851475143)", setup="from __main__ import pf", number=1)
print timeit.timeit("pf2(600851475143)", setup="from __main__ import pf2", number=1)

rawDescription: Python code stucks in Iterating although it found the solution


code:
import sqlite3 as sql
from this import s as nonsense
import subprocess
import shlex
import time

max_parallel_processes = 10

def getdb(tableid = "test"):
    dbid = ":memory:"

    stmt_create = "CREATE TABLE %s (id int, comment text)" % tableid
    stmt_insert = "INSERT INTO %s VALUES (?, ?)" % tableid

    values = enumerate(nonsense.split())

    db = sql.connect(dbid)
    db.execute(stmt_create)
    db.executemany(stmt_insert, values)
    return db

def get_ids(db, tableid = "test"):
    stmt_select_id = "SELECT id from %s " % tableid
    crs = db.execute(stmt_select_id)
    result = crs.fetchall()
    for i in result:
        yield i

def main():
    from random import randint

    db = getdb()
    process_lst = {}
    sleep_between_polls_in_seconds = 0.1

    for rowid in get_ids(db):
        if len(process_lst) < max_parallel_processes:
            cmd_str = "sleep %s"  % randint(1, 3)
            cmd = shlex.split(cmd_str)

            print "adding : %s (%s)" % (rowid, cmd_str)

            proc = subprocess.Popen(cmd)
            process_lst[proc] = rowid
            proc.poll()
        else:
            print "max processes (%s) reached" % max_parallel_processes

            for proc in process_lst.keys():
                finished = proc.poll() is not None
                if finished:
                    print "%s finished" % process_lst[proc]
                    del process_lst[proc]

                time.sleep(sleep_between_polls_in_seconds)

    print "All processes processed: %s "  %(len (process_lst) == 0)

if __name__ == "__main__":
    main()

rawDescription: Having multiple processes/threads running at all times, accessing a sqlite3 db until a condition is met


code:
list1 = ['Mary','had','a','little','lamb','which','was','very','naughty']

def drop(sequence,start,end):
    keep = False
    for item in sequence:
        if item == start:
            keep = True
        if keep and item == end:
            yield item
            break
        if keep:
            yield item

list3 = drop(list1, 'little', 'very')

print list(list3)

rawDescription: Creating a smaller list from an existing list


code:
print [v() for v in method_results.values()]
[1, 2, 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:
import re
r = re.compile(r'^/(?!(?:people|dungen)/[^?]+$).+/[^?]+$')
for s in ['/a/b/c/d', '/a/b', '/people/b/c/d', '/peoples/b/c/d', '/a/b/c?x=y']:
    print not not r.search(s)

rawDescription: How can I make regex not accept some values?

description: Make regex not accept some values


code:
import numpy as np
import pandas as pd
ranges = np.asarray([(np.datetime64('2013-12-24T00:00:00Z'), np.datetime64('2013-12-24T00:02:00Z')),
                     (np.datetime64('2013-12-24T00:02:00Z'), np.datetime64('2013-12-24T00:04:00Z')),
                     (np.datetime64('2013-12-24T00:03:00Z'), np.datetime64('2013-12-24T00:05:00Z'))])
us = pd.Series(index=np.unique(ranges), data=0)
for start, end in ranges:
    us[start:end] += 1
print us

rawDescription: Pandas: Overlapping time count

description: Pandas: Overlapping time count


code:
import numpy as np
P = np.array([[0.6,0.4,0.,0.],[0.3,0.7,0.,0.],[0.2,0.4,0.2,0.2],[0.,0.,0.,1.]])

g = nx.from_numpy_matrix(P, create_using=nx.DiGraph())
for subg in absorbing_classes(g):
    print subg.nodes()

rawDescription: Identifying absorbing classes in a sparse graph


rawDescription: python: check if IP or DNS

description: Python: check if IP or DNS


code:
def SaysHelloAfterEveryMethod(klass):
  def __getattribute__(self, name):
    def f():
      # todo: check if it's actually a function or not
      r = object.__getattribute__(self, name)()
      print 'hello world'
      return r
    return f
  klass.__getattribute__ = __getattribute__
  return klass

@SaysHelloAfterEveryMethod
class Example(object):
  def method1(self):
    print 1
  def method2(self):
    print 2

rawDescription: Making sure each method ends with a specific statement


code: print [x.split(' ')[1] for x in a.split('\r\n\r\n') if len(x) > 1]

rawDescription: Python Split Operator

description: Python Split Operator


code:
from xml.dom.minidom import parse

xmldata = open("abc.txt", "r")

domdata = parse(xmldata)

def getDescriptionData(title):
    titledata = [x.toxml().lstrip('<title>').rstrip('</title>') for x in domdata.getElementsByTagName('title')]
    descriptiondata = [x.toxml().lstrip('<description>').rstrip('</description>') for x in domdata.getElementsByTagName('description')]

    l =  [v for (x, v) in zip(titledata, descriptiondata) if x == title]
    if l:
        return l[0]
    return None

print getDescriptionData('Lake Louis')

rawDescription: Find a line and read next line in Python


code:
print seq
print seq[-6:]

rawDescription: How to parse ambiguous characters with BioPython

description: Parse ambiguous characters with BioPython


code:
import ast
def config_file(filename):
    result = {}
    with open(filename) as f:
        for line in f:
            line = line.split('=',1)
            result[line[0]] = ast.literal_eval(line[1].strip())
    return result

print config_file('cfg.txt')

rawDescription: Read list from text file

description: Read list from text file


code:
def build_char_records(phrase):
    phrase = phrase.lower()
    resultList = []
    for character in phrase: ## iterates through the phrase
        if character not in resultList:
            resultList.append(character) ## This adds each character to the list
                                         ## if it is not already in the list
    resultList.sort() ## sorts the list
    for i in range(len(resultList)): ## goes through each unique character
        character = resultList[i] ## the character in question
        tphrase = phrase ## a copy of the phrase
        num = phrase.count(character) ## the number of occurences
        acc = 0 ## an accumulator to keep track of how many we've found
        locs = [] ## list of the locations

        while acc < num: ## while the number we've found is less than how many
                         ## there should be
            index = tphrase.find(character) ## finds the first occurance of the character
            tphrase = tphrase[index+1:] ## chops off everything up to and including the
                                        ## character
            if len(locs) != 0: ## if there is more than one character
                index = locs[acc-1] + index + 1 ## adjusts because we're cutting up the string
            locs.append(index)## adds the index to the list
            acc += 1 ## increases the accumulator

        resultList[i] = [character, num, locs] ## creates the result in the proper spot

    return resultList ## returns the list of lists

print build_char_records('Hi there bye')

rawDescription: find the index of element the number of occurence in string

description: Find the index of element the number of occurence in string


code:
x = set(['item1','item2','item3'])
print list(x)

rawDescription: Writing a Set To a File in Python

description: Writing a Set To a File in Python


code:
import HTMLParser
h = HTMLParser.HTMLParser()
print h.unescape('שלך')
h.unescape('שלך')

rawDescription: With reading hebrew in urllib2 python

description: With reading hebrew in urllib2 python


code:
cmd = "C:\\FIOCheck\\xutil.exe  -i get phy " +HBEA + ">C:\\FIOCheck\\HBEAResult.txt"
print cmd
os.system(cmd)

rawDescription: os.system commands

description: Os.system commands


code:
#!/usr/bin/env python2.7

import os
import zipfile

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print 'zipping %s as %s' % (os.path.join(dirname, filename),
                                        arcname)
            zf.write(absname, arcname)
    zf.close()

zip("src", "dst")

rawDescription: Create .zip in Python?

description: Create .zip in Python


code:
for _i, _v in enumerate(info):
    print 'start....', _i
    _p = multiprocessing.Process(target=select, args=(_v, ))
    _p.start()
    _p.join()

rawDescription: Python, how to implement parallel process


code:
import json
import inspect

def viewable(fnc):
        '''
            Decorator, mark a function as viewable and gather some metadata in the process

        '''
        def call(*pargs, **kwargs):
                return fnc(*pargs, **kwargs)
        # Mark the function as viewable
        call.is_viewable = True
        return call

class BaseJsonable(object):

    def to_json(self):
        result = {}
        for name, member in inspect.getmembers(self):
            if getattr(member, 'is_viewable', False):
                value = member()
                result[name] = getattr(value, 'to_json', value.__str__)()
        return json.dumps(result)

class Person(BaseJsonable):

    @viewable
    def name(self):
        return self._name

    @viewable
    def surname(self):
        return self._surname

    def __init__(self, name, surname):
        self._name = name
        self._surname = surname

p = Person('hello', 'world')
print p.to_json()

rawDescription: python convert custom object to json using properties

description: Python convert custom object to json using properties


code:
for i in MyString("abcdef"):
    print type(i)

rawDescription: Inheriting from "str" class

description: Inheriting from "str" class


code:
ch = '''//Last modified: Sat, Apr 16, 2011 09:55:04 AM
//Codeset: ISO-8859-1
fileInfo "version" "20x64";
createNode newnode -n "a_SET";
    addAttr -ci true -k true -sn "connections" -ln "connections" -dt "string";
    setAttr -l on -k off ".tx";
    setAttr -l on -k off ".ty";
    setAttr -l on -k off ".sz";
    setAttr -l on -k on ".test1" -type "string" "blabla";
    setAttr -l on -k on ".test2" -type "string" "blablabla";
createNode newnode -n "b_SET";
    addAttr -ci true -k true -sn "connections" -ln "connections" -dt "string";
    setAttr -l on -k off ".tx";
    setAttr -l on -k off ".ty";
    setAttr -l on -k off ".sz";
    setAttr -l on -k on ".test1" -type "string" (
      "hmm bl
      abla\tbla" );
    setAttr -l on -k on ".tes\nt\t2" -type "string" "ehm\tehm";
    setAttr -l on -k on ".test3" -type "string" "too
    much" "pff" """ "feretini" "gol\nolo";
    '''

import re

pat = re.compile('createNode newnode -n ("\w+?_SET");(.*?)(?=createNode|\Z)',re.DOTALL)
pot = re.compile('^ *setAttr.+?'
                 '"((?:\n(?! *setAttr)|[^"\n])+)"'
                 '(?:\n(?! *setAttr)|.)+'
                 '"((?:\n(?! *setAttr)|[^"\n])+)"'
                 '.*;(?:\n|\Z)',re.MULTILINE)

dic = dict( (mat.group(1),dict(pot.findall(mat.group(2)))) for mat in pat.finditer(ch))
for x in dic:
    print x,'\n',dic[x],'\n'

rawDescription: Python multiline regex + multi entries reading a file in one go


code: print "I want :",max_sum(groups) #i will leave the implementation of this up to you

rawDescription: Writing program to choose values from a list of integers


code:
result = unittest.TextTestRunner(stream = open(os.devnull, 'w')).run(alltests)
if len(result.failures) or len(result.errors):
    print "Sorry."

rawDescription: Python, unittest: Can one make the TestRunner completely quiet?


code:
print 'gc.collect'
import gc
gc.collect()
print 'after gc.collect'

rawDescription: internal reference prevents garbage collection

description: Internal reference prevents garbage collection


code:
RS=False
LS=False
for each in dict:
    if "L_" in each:
        LS=True
    if "R_" in dict:
        RS=True
    if LS and RS:
        print 'has both'
        break

rawDescription: Does dictionary contain key containing multiple partial strings?


code:
from datetime import datetime, timedelta

n = 25
print datetime(datetime.today().timetuple().tm_year, 1, 1) + timedelta(n - 1)

rawDescription: Is there an inverse of python's date.timetuple().tm_yday?


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

BASE_URL = 'http://topsy.com/trackback?url=http%3A%2F%2Fmashable.com%2F2014%2F08%2F27%2Faustralia-retail-evolution-lab-aopen-shopping%2F&offset={offset}'

driver = webdriver.Chrome()

# get tweets count
driver.get('http://topsy.com/trackback?url=http%3A%2F%2Fmashable.com%2F2014%2F08%2F27%2Faustralia-retail-evolution-lab-aopen-shopping%2F')
tweets_count = int(driver.find_element_by_xpath('//li[@data-name="all"]/a/span').text)

for x in xrange(0, tweets_count, 10):
    driver.get(BASE_URL.format(offset=x))

    # page header appears in case no more tweets found
    try:
        driver.find_element_by_xpath('//div[@class="page-header"]/h3')
    except NoSuchElementException:
        pass
    else:
        break

    # wait for results
    WebDriverWait(driver, 5).until(
        EC.presence_of_element_located((By.ID, "results"))
    )

    # get tweets
    for tweet in driver.find_elements_by_class_name('result-tweet'):
        print tweet.find_element_by_xpath('.//div[@class="media-body"]//ul[@class="inline"]/li//a').get_attribute('href')

driver.close()

rawDescription: Urllib Python is not providing with the html code I see with with inspect element


code:
import re
# Check if contains at least one digit
if re.search(r'\d', password):
    print "Has a digit"
# Check if contains at least one uppercase letter
if re.search(r'[A-Z]', password):
    print "Has uppercase letter"
# Check if contains at least one lowercase letter
if re.search(r'[a-z]', password):
    print "Has lowercase letter"

rawDescription: Python password strength

description: Python password strength


code:
Subbasins_Imp = [['22', '1'], ['21', '15'], ['11', '3'], ['31', '4'], ['41', '13'], ['21', '1']]

Subbasin_1 = []
Subbasin_1.extend([x for x in Subbasins_Imp if x[1] == '1'])
print Subbasin_1

OS_Count1 = []
OS_Count1.extend([x for x in Subbasin_1 if x[0] == '21'])
print OS_Count1

rawDescription: how to create a sub list for a specific string in a nested list

description: Create a sub list for a specific string in a nested list


code:
stuff = [lambda x: n+x for n in [1, 2, 3]]
for f in stuff:
    print f(1)
stuff = [lambda x, n=n: n+x for n in [1, 2, 3]]
for f in stuff:
    print f(1)

rawDescription: Python lambda closure scoping

description: Python lambda closure scoping


code:
from pyparsing import *

enclosed = Forward()
nestedParens = nestedExpr('(', ')', content=enclosed)
nestedBrackets = nestedExpr('[', ']', content=enclosed)
nestedCurlies = nestedExpr('{', '}', content=enclosed)
enclosed << (Word(alphas) | ',' | nestedParens | nestedBrackets | nestedCurlies)

data = '(gimme [some {nested, nested [lists]}])'

print enclosed.parseString(data).asList()

rawDescription: How can I use pyparsing to parse nested expressions that have mutiple opener/closer types?

description: Use pyparsing to parse nested expressions that have mutiple opener/closer types


code:
import argparse
parser = argparse.ArgumentParser(prog='My Prog')
sub_parsers = parser.add_subparsers(dest='cmd')

subcommand_a = sub_parsers.add_parser('subcommand_a', help='a help')
subcommand_a.add_argument('req1', help='required argument 1 help')
subcommand_a.add_argument('--opt1', help='option 1 help')
subcommand_a.add_argument('--opt2', nargs=3, help='option 2 help')

subcommand_b = sub_parsers.add_parser('subcommand_b', help='b help')
subcommand_b.add_argument('req1', help='required argument 1 help')
subcommand_b.add_argument('--opt1', help='option 1 help')
subcommand_b.add_argument('--opt2', help='option 2 help')
subcommand_b.add_argument('--opt3', nargs=3, help='option 3 help')

argv = "subcommand_a FOO --opt1=bar --opt2 1 2 3 subcommand_b BAR --opt1=foo --opt3 a b c"
rest = argv.split()
while rest:
    [args, rest] = parser.parse_known_args(rest)
    print args
    print rest

rawDescription: Python argparse, run one or more sub-commands


code:
import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
    'numpy.isnan(a).any()',
    'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
    print "  %.2f s" % timeit.Timer(m, s).timeit(1000), m

rawDescription: Detect if a NumPy array contains at least one non-numeric value?


code:
#!/usr/local/bin/python

import subprocess

res = subprocess.check_output(["./example"], universal_newlines=True)

print "The value of 2*" + u"\u03C0" + " is approximately " + str(2*float(res))

rawDescription: Send value back from c++ to python

description: Send value back from c++ to python


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # wait up to 10 seconds while trying to locate elements
for page in range(1, 2):
    driver.get("http://somesite.com/page/"+str(page))
    table = driver.find_element_by_css_selector('div.datatable')
    links = table.find_elements_by_tag_name('a')
    for link in links:
        print link.text

rawDescription: Waiting for a table to load completely using selenium with python


code: print json.dumps(e, cls=new_alchemy_encoder(False, ['parents']), check_circular=False)

rawDescription: How to serialize SqlAlchemy result to JSON?

description: Serialize SqlAlchemy result to JSON


code:
# get lloyds average score
lloyd_score = get_average(lloyd)

# get the letter grade corresponding to lloyd's average score
lloyd_letter_grade = get_letter_grade(lloyd_score)

# print that letter grade
print lloyd_letter_grade

rawDescription: Explain the function

description: Explain the function


code:
import textwrap
from nltk.corpus import wordnet as wn

POS = {
    'v': 'verb', 'a': 'adjective', 's': 'satellite adjective',
    'n': 'noun', 'r': 'adverb'}

def info(word, pos=None):
    for i, syn in enumerate(wn.synsets(word, pos)):
        syns = [n.replace('_', ' ') for n in syn.lemma_names]
        ants = [a for m in syn.lemmas for a in m.antonyms()]
        ind = ' '*12
        defn= textwrap.wrap(syn.definition, 64)
        print 'sense %d (%s)' % (i + 1, POS[syn.pos])
        print 'definition: ' + ('\n' + ind).join(defn)
        print '  synonyms:', ', '.join(syns)
        if ants:
            print '  antonyms:', ', '.join(a.name for a in ants)
        if syn.examples:
            print '  examples: ' + ('\n' + ind).join(syn.examples)
        print

info('near')

rawDescription: Fully parsable dictionary/thesaurus

description: Fully parsable dictionary/thesaurus


code:
import numpy as np
A = np.arange(1,122)
print A
print A.reshape((11,11))

rawDescription: Array reshape not mapping correctly to numpy meshgrid


code:
# Start two subprocesses in the background
worker1 = Worker([r'c:\python26\python.exe', 'sub1.py'])
worker2 = Worker([r'c:\python26\python.exe', 'sub2.py'])

# Wait for both to finish, kill after 10 seconds timeout
worker1.wait_to_finish(timeout_seconds = 10)
worker2.wait_to_finish(timeout_seconds = 10)

# Start another subprocess giving it 5 seconds to finish
worker3 = Worker([r'c:\python26\python.exe', 'sub3.py'])
worker3.wait_to_finish(timeout_seconds = 5)

print "----LOG1----\n" + worker1.log
print "----LOG2----\n" + worker2.log
print "----LOG3----\n" + worker3.log

rawDescription: Custom Scheduler to have sequential + semi-sequential scripts with timeouts/kill switches?


code:
import pandas as pd
import copy

df = pd.DataFrame([1,1,1,0,1,1,0,0,0,1,1,1,0])

df.columns = ['D']
d= copy.copy(df.D)

def transform(l):
  count=1
  for index,x in enumerate(l):
    if x==0:
      l[index]=count
      count=1
    else:
      l[index]=0
      count+=1
  return l

df['intervales']=transform(t)
df['D']=d

print df

rawDescription: Python Pandas count interval of occurrence


code:
from operator import attrgetter

print sorted(your_objects, key=attrgetter('the name of your int'))

rawDescription: Quick Method for Sorting User Defined Classes


code:
from ctypes import *
containerTYPE = POINTER( c_uint ) * 10 #Array of pointers to UINTs of size 10
containerA = containerTYPE()
containerB = containerTYPE()

for i in range( 10 ):
    val = c_uint( i )
    containerA[ i ] = pointer( val )
    containerB[ -1 - i ] = pointer( val )

print "A\tB"
for i in range( 10 ):
    print containerA[ i ].contents.value, "\t", containerB[ i ].contents.value

for i in range( 10 ): #affects both arrays
    derefed = containerA[ i ].contents
    derefed.value = i * 2

print
print "A\tB"
for i in range( 10 ):
    print containerA[ i ].contents.value, "\t", containerB[ i ].contents.value

rawDescription: Python - copy by reference

description: Python - copy by reference


code:
from constants import ComplexTypes
from inspect import getmembers, isfunction

print dir(ComplexTypes)

for o in getmembers(ComplexTypes):
    print o

rawDescription: Python: Grouped constants with possibility to iterate over group


code:
for item in bases:
    print item
    get_bases(item)

rawDescription: generate a dependency tree of the inheritance hierarchy

description: Generate a dependency tree of the inheritance hierarchy


code:
for i in list:
    if (i[0])==6:
        print "Yes"
        print i

rawDescription: Printing the sublist in which the required number is found


code:
def to_percents(data):
    total = float(sum(v for _, v in data))
    data[:] = [(k, v / total) for k, v in data]
    return data

data = to_percents([("foo", 1), ("bar", 3), ("baz", 5), ("ao", 7)])
print data

rawDescription: Display data in (%) for pie chart using the PyChart library in Python


code:
def cb(k,v):
    print k,v

d=DictWatch(callback=cb)
d['key']='100'

rawDescription: Python 3: hook list & dict changes

description: Python 3: hook list & dict changes


code:
text = "500 Minutes + Unlimited Text + Your Choice of Data"
a, b, c = [part.strip() for part in text.split('+')]
print a
print b
print c

rawDescription: How do I separate a long string into 3 different strings using a separator in Python

description: Separate a long string into 3 different strings using a separator in Python


code:
a.sort(key=lambda x:int(x.split()[1]))
print a

rawDescription: how to sort a list of string by every element's numeric value

description: Sort a list of string by every element's numeric value


code:
from scipy.sparse import csr_matrix
docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
indptr = [0]
indices = []
data = []
vocabulary = {}
for d in docs:
    for term in d:
        index = vocabulary.setdefault(term, len(vocabulary))
        indices.append(index)
        data.append(1)
    indptr.append(len(indices))

print csr_matrix((data, indices, indptr), dtype=int).toarray()

rawDescription: NumPy or Dictionary?

description: NumPy or Dictionary


code:
Example
ipv6 = mac2ipv6("52:74:f2:b1:a8:7f")
back2mac = ipv62mac(ipv6)
print "IPv6:", ipv6    # prints IPv6: fe80::5074:f2ff:feb1:a87f/64
print "MAC:", back2mac # prints MAC: 52:74:f2:b1:a8:7f

rawDescription: How to convert IPv6 link-local address to MAC address in Python

description: Convert IPv6 link-local address to MAC address in Python


code:
from xml.etree import ElementTree as et
x='''

text1

  t1

text2

  t2

text3

'''
t=et.fromstring(x)
for el in t.iter():
  print '%s: %r, %r' % (el.tag, el.text, el.tail)

rawDescription: Using lxml to find order of text and sub-elements


code:
print r"C:\Users\jake\Documents\files\DataFiles\pandas.txt".split("\\")[-1]
print r"C:\Users\whom\content.bmp".split("\\")[-1]
print r"C:\Users\jake\Documents\cats.txt".split("\\")[-1]

rawDescription: Use pickAFile delete file path but keep file name Python


code:
from sqlalchemy.sql import select

s = select([users_table.c.user_name, users_table.c.user_country], users_table.c.user_name == username)

for user_name, user_country in s.execute():
   print user_name, user_country

rawDescription: SQLAlchemy: Operating on results

description: SQLAlchemy: Operating on results


code:
enteramt = raw_input ("How many")
value = int(enteramt) * 275
print "This is worth" , value

rawDescription: Issues multiplying in python

description: Issues multiplying in python


code:
a = '''

            ${t}

'''

from chameleon import PageTemplate

pt = PageTemplate(a)

class Literal(object):
    def __init__(self, s):
        self.s =s

    def __html__(self):
        return self.s

print pt(t=Literal('
Hi!
'))

rawDescription: Python Pyramid & Chameleon templating language escapes html


code:
import socket,hashlib,base64

MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
HSHAKE_RESP = "HTTP/1.1 101 Switching Protocols\r\n" + \
            "Upgrade: websocket\r\n" + \
            "Connection: Upgrade\r\n" + \
            "Sec-WebSocket-Accept: %s\r\n" + \
            "\r\n"

HOST = ''
PORT = 9876
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
data = conn.recv(4096)
headers = {}
lines = data.splitlines()
for l in lines:
    parts = l.split(": ", 1)
    if len(parts) == 2:
        headers[parts[0]] = parts[1]
headers['code'] = lines[len(lines) - 1]
key = headers['Sec-WebSocket-Key']
resp_data = HSHAKE_RESP % ((base64.b64encode(hashlib.sha1(key+MAGIC).digest()),))
conn.send(resp_data)

while 1:
    data = conn.recv(4096)
    if not data:
        break
    databyte = bytearray(data)
    datalen = (0x7F & databyte[1])
    str_data = ''
    if(datalen > 0):
        mask_key = databyte[2:6]
        masked_data = databyte[6:(6+datalen)]
        unmasked_data = [masked_data[i] ^ mask_key[i%4] for i in range(len(masked_data))]
        str_data = str(bytearray(unmasked_data))
    print str_data
    resp = bytearray([0b10000001, len(str_data)])
    for d in bytearray(str_data):
        resp.append(d)
    conn.sendall(resp)
conn.close()

rawDescription: html5 websocket connecting to python

description: Html5 websocket connecting to python


code:
foo = """
this is
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('\n', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

rawDescription: Iterate over the lines of a string

description: Iterate over the lines of a string


code:
from os.path import basename

# now you can call it directly with basename
print basename("/a/b/c.txt")

rawDescription: How to get the filename without the extension from a path in Python?

description: Get the filename without the extension from a path in Python


code:
#!/usr/bin/env python

class human(object):
    def __init__(self):
        self.name = '<unnamed baby>'

    def nameBaby(self, name):
        self.name = name

    def getName(self):
        return self.name

kid = human()
print kid.getName()
kid.nameBaby('Bruce')
print kid.getName()

rawDescription: Instance Variable Assignment in def other than __init__?


code:
common = l1.intersection(l2)  # common will give common elements
print len(common) # this will give you the number of elements in common.

rawDescription: Python - Comparing two lists of sets

description: Python - Comparing two lists of sets


code:
with open("russ.txt", "r") as f, open("output.txt", "w") as fh:
    for line in f:
        symbol = line.split()[-1]
        if symbol != "Ticker":
            print symbol
            fh.write(symbol + "\n")

rawDescription: Reading/writing files in Python

description: Reading/writing files in Python


code:
from gi.repository import Gtk, Gdk

def focus_in(*args):
    print 'focus_in called'

def focus_out(*args):
    print 'focus_out called'

window = Gtk.Window()
window.connect('destroy', Gtk.main_quit)
screen = Gdk.Screen.get_default()
css_provider = Gtk.CssProvider()
css_provider.load_from_path('style.css')
priority = Gtk.STYLE_PROVIDER_PRIORITY_USER
context = Gtk.StyleContext()
context.add_provider_for_screen(screen, css_provider, priority)
fname = Gtk.Entry(text='First Name')
lname = Gtk.Entry(text='Last Name')
button = Gtk.Button('Submit')
fname.connect('focus-in-event', focus_in)
fname.connect('focus-out-event', focus_out)
vbox = Gtk.VBox()
vbox.add(fname)
vbox.add(lname)
vbox.add(button)
window.add(vbox)
window.show_all()
Gtk.main()

rawDescription: Gtk 3 python entry color

description: Gtk 3 python entry color


code:
class IN(object):
    def __init__(self):
        print "i am the original IN"

class C(object):
    def __init__(self, x):
        pass

    def func(self):
        print "going to create IN from C's func"
        cl = IN()

rawDescription: How can I override class call inside of an imported class in python?

description: Override class call inside of an imported class in python


code:
import re
data=r'<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">"'

matches=re.findall('synset-([0-9]+).*label="{(.*)_1}"', data)
print "matches:", matches

rawDescription: Python regexp find two keywords in a line


code:
import example
class PythonDerived(example.Base):
    def __init__(self, x):
        print "PYTHON DEFAULT CONSTRUCTOR"
        example.Base.__init__(self, x)
    def Say(self):
         return "Python Say"

d = PythonDerived(5)
d
d.Say()
d.CallSay()

rawDescription: Virtual override in boost python objects created by static method (or factory (?))


code:
ranges = ((n, n+step) for n in xrange(start, stop, step))

# Usage
for block in ranges:
    print block

rawDescription: Generate list of range tuples with given boundaries in python


code:
for music in f_music:
    for verified_page in f_music:
        for page in verified_page:
            page_verified = page.find_all('span',{'aria-label':'Verified Page'})
            print page_verified
            check= "Verified Page"
            print page_verified[0]
            print type(page_verified[0])
            print check in page_verified[0]

rawDescription: Python 'in' function , pandas dataframe wrongly populated


code:
treasure = "Success!"

def primary(input):
    def second():
        print "something"

    def third():
        print treasure

rawDescription: Access a variable defined in function

description: Access a variable defined in function


code:
import os
import errno

print {i:os.strerror(i) for i in sorted(errno.errorcode)}

rawDescription: How to get the list of error numbers (Errno) for an Exception type in python?

description: Get the list of error numbers (Errno) for an Exception type in python


code:
from itertools import izip
print set(izip(cpos, cal)).intersection(izip(mpos, mal))

rawDescription: Finding a match in two sets of synchronized lists


code:
for i in range(0,l):
  print "c%d is %d" % (i,a[i])

rawDescription: Count the number of lines after each pattern


code:
import urllib

try:
    html=urllib.urlopen('http://robolab.in/home-automation.html#ON')
    htmltext=html.read()
except:
    print 'error opening link'

print htmltext

rawDescription: Read a URL in Raspberry Pi

description: Read a URL in Raspberry Pi


code: print [list(x) for x in {frozenset(x) for x in l}]

rawDescription: Removing repeated sub-lists from a list

description: Removing repeated sub-lists from a list


code:
class My_Num(object):
    def __init__(self, val):
        self.val = val
    def __radd__(self, other_num):
        if isinstance(other_num, My_Num):
            return self.val + other_num.val
        else:
            return self.val + other_num

n1 = My_Num(1)
n2 = 3

print n2 + n1
print n1 + n2

rawDescription: Operator overloading in python with the object on the right hand side of the operator


code:
import datetime as DT
import pytz
import calendar
mtl = pytz.timezone('America/Montreal')
naive_time3 = DT.datetime.strptime('2013/11/03', '%Y/%m/%d')
print repr(naive_time3)
#datetime.datetime(2013, 11, 3, 0, 0)
localized_time3 = mtl.localize(naive_time3)
print repr(localized_time3)
#datetime.datetime(2013, 11, 3, 0, 0, tzinfo=<DstTzInfo 'America/Montreal' EDT-1 day, 20:00:00 DST>)
print calendar.timegm(localized_time3.utctimetuple())
#1383451200.0
def add_day(x):
    d = x.date()+DT.timedelta(1)
    return mtl.localize(x.replace(year=d.year, month=d.month, day=d.day, tzinfo=None))
print repr(add_day(localized_time3))
#datetime.datetime(2013, 11, 4, 0, 0, tzinfo=<DstTzInfo 'America/Montreal' EST-1 day, 19:00:00 STD>)

rawDescription: How to find next day's Unix timestamp for same hour, including DST, in Python?

description: Find next day's Unix timestamp for same hour, including DST, in Python


code:
for i in range(2,10,3):
  print i

rawDescription: Manipulate for loop to increment by specific value? - Python


code:
def f():print "hello"

def g(f):
    def call_global_f():
        global f
        f()
    call_global_f()      #calls the global f
    print f              #prints the local f

g('foo')

rawDescription: Python calling a function with the same name as named argument


code:
from django.template import Template, Context, loader
values = [1, 2, 10, 100]
c = Context({'values': values})
t = Template("""
{% for value in values %}
    {{ value }}, {{ value|stringformat:"02d" }}
{% endfor %}""")
print t.render(c)

rawDescription: Django template filter for numbers

description: Django template filter for numbers


code:
import wx
import threading
import time
import random
def make_choices():
    choices = []
    for _ in range(80):
        choices.append(str(random.randint(0,1000000)))
        time.sleep(0.1)
        print "Making choice List!"
    return choices

def make_choice_thread(wxChoice,choice_fn):
    wx.CallAfter(wxChoice.SetItems,choice_fn())
    wx.CallAfter(wxChoice.SetSelection,0)

a = wx.App(redirect=False)
fr = wx.Frame(None,-1,"A Big Choice...")
st = wx.StaticText(fr,-1,"For Some reason you must pick from a large list")
ch = wx.Choice(fr,-1,choices=["Loading...please wait!"],size=(200,-1),pos=(15,15))
ch.SetSelection(0)
t = threading.Thread(target=make_choice_thread,args=(ch,make_choices))
t.start()
fr.Show()
a.MainLoop()

rawDescription: Fastest way to populate wx.Choice?

description: Fastest way to populate wx.Choice


code:
class one:
    def funct1(self):
        print 'I am defined in class one'
    self.data1 = "one"

class two:
    def funct2(self):
        print 'I am defined in class two'
    self.data2 = "two"

class three(one, two):
    def funct3(self):
        print 'I am defined in class three'
    self.data3 = "three"

rawDescription: Simple python communication class error?

description: Simple python communication class error


code:
def is_prime(b):
    x = 0.0
    a = 0
    while x<b:
        x=x+1
        #this will check for divisors.
        if (b/x)-int(b/x) == 0.0:
            a=a+1
    if a==2:
        return True
    else:
        return False

b=1
d=0
#generates a list of numbers.
while b<100:
    b=b+1
    if is_prime(b):
        d=d+b
print d

rawDescription: python sum of primes

description: Python sum of primes


code:
def check_line(gen, char='|'):
    correct_count = None
    injected = None

    while True:
        i, line = gen.next(injected)
        line_count = line.count(char)

        if not correct_count:
           correct_count = line_count

        if line_count != correct_count:
           print """Line %d contains %d %s, should have %d""" % (
                 i, line_count, char, correct_count)

        injected = yield i, line

with open('file.txt', 'rb') as f:
     checker = check_line(enumerate(f))
     for i, line in checker:
         print line

rawDescription: Pythonic way to check generator values using its own elements


code:
import os

def Count_files_in_subd():
    for root, dirs, files in os.walk("/Path/to/directory"):
        print "{} in {}".format(len(files), root)

Count_files_in_subd()

rawDescription: How to iterate through subdirectories in a directory and count the files in the subdirectories in python

description: Iterate through subdirectories in a directory and count the files in the subdirectories in python


rawDescription: Matching a real number key in a Python dictionary


code:
from subprocess import Popen, PIPE

p = Popen(cmd, stdout=PIPE, bufsize=1)
for line in iter(p.stdout.readline, ''):
    print line,
p.stdout.close()
if p.wait() != 0:
   raise RuntimeError("%r failed, exit status: %d" % (cmd, p.returncode))

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
import os

def get_abs_directory(path):

    if not isinstance(path, str):
        print "You gave us the wrong type, you big meany!"
        return None

    if os.path.isdir(path):
        return path
    else:
        return os.path.split(os.path.abspath(path))[0]

if __name__ == '__main__':
    get_abs_directory(1)

rawDescription: Parameter validation, Best practices in Python


code:
dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

rawDescription: How to convert a date string to different format

description: Convert a date string to different format


code:
import pygame

pygame.init()

screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
flash = 0
grow = True
color = pygame.color.Color('Black')

E_OUTSIDE = pygame.USEREVENT  + 1
E_MOUSE   = pygame.USEREVENT  + 2

conditions = [ # blink if player is outside screen
              (lambda: not s_r.contains(player), pygame.event.Event(E_OUTSIDE)),
               # if mouse if over player then grow and shrink player
              (lambda: player.collidepoint(pygame.mouse.get_pos()), pygame.event.Event(E_MOUSE))]

while True:
    # generate events from conditions
    map(pygame.event.post, [e for (c, e) in conditions if c()])

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise
        elif event.type == E_OUTSIDE and not flash:
            flash = 5
        elif event.type == E_MOUSE:
            if grow:
                player.inflate_ip(4, 4)
                grow = player.width < 75
            else:
                player.inflate_ip(-4, -4)
                grow = player.width < 50

    flash = max(flash - 1, 0)
    if flash % 2:
        color = pygame.color.Color('White')

    pressed = pygame.key.get_pressed()
    l, r, u, d = map(lambda x: x*4, [pressed[k] for k in pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s])
    player.move_ip((-l + r, -u + d))

    screen.fill(color)
    color = pygame.color.Color('Black')

    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

    pygame.display.flip()
    timer.tick(25)

rawDescription: PyGame Custom Event

description: PyGame Custom Event


code:
from bs4 import BeautifulSoup
import bs4

html='''

  E-mail address:

 useremail@yahoo.com

'''

def print_if_email(s):
    if '@' in s: print s

soup = BeautifulSoup(html)

# Iterate over all divs, you could narrow this down if you had more information
for div in soup.findAll('div'):
    # Iterate over the children of each matching div
    for c in div.children:
        # If it wasn't parsed as a tag, it may be a NavigableString
        if isinstance(c, bs4.element.NavigableString):
            # Some heuristic to identify email addresses if other non-tags exist
            print_if_email(c.strip())

rawDescription: Scrape text not contained in any element


code:
from BeautifulSoup import BeautifulSoup
import urllib2

page = urllib2.urlopen('http://www.worldgolf.com/courses/usa/massachusetts/')
soup = BeautifulSoup(page)
s = soup.findAll('h2')

print len(s)
for t in s:
    print t.text

rawDescription: Why does HTMLParser miss some tags?

description: Why does HTMLParser miss some tags


code:
import csv, StringIO

text = "('s1', 's2', 's3', 's4')"
print next(csv.reader(StringIO.StringIO(text.strip("()")), skipinitialspace=True, quotechar="'"))[1]

rawDescription: Matching substring in pattern in Python

description: Matching substring in pattern in Python


code:
import security
for line in security.secure(): exec line in globals()

rawDescription: How can credentials be securely distributed in a cloud computing environment?


code:
from Tkinter import *

root = Tk()

def go():
   wdw = Toplevel()
   wdw.geometry('+400+400')
   e = Entry(wdw)
   e.pack()
   e.focus_set()
   #wdw.transient(root)
   #wdw.grab_set()
   root.wait_window(wdw)
   print 'done!'

Button(root, text='Go', command=go).pack()
Button(root, text='Quit', command=root.destroy).pack()

root.mainloop()

rawDescription: Hiding Tkinter root window while showing modal window


code:
def my_numpy_func(name_addrs):
    names = name_addrs.ctypes.data_as(ctypes.POINTER(ctypes.c_char_p))
    for i in range(len(name_addrs)):
        print names[i]

rawDescription: Create PyString from c character array without copying


code:
class B(object):
  pass

print B()
# <__main__.B object at 0xb7e4082c>

def B_init(self):
  self.answer = 42
def B_str(self):
  return "<The answer is %s.>" % self.answer
# notice these functions require no knowledge of the actual class
# how hard are they to read and realize that "members" are used?

B.__init__ = B_init
B.__str__ = B_str

print B()
# <The answer is 42.>

rawDescription: Python: How to avoid explicit  'self'?

description: Python: How to avoid explicit  'self'


code: print yaml.dump(A())

rawDescription: How can I suppress 'None' output from yaml.dump, in Python?

description: Suppress 'None' output from yaml.dump, in Python


code:
import json
class FakeDict(dict):
    def __init__(self, items):
        # need to have something in the dictionary
        self['something'] = 'something'
        self.items = items

    def __getitem__(self, key):
        return self.last_val

    def __iter__(self):
        subiter = iter(self.items)
        def generator():
            for key, value in self.items:
                self.last_val = value
                yield key

        return generator()

print json.dumps(FakeDict([('a', 5), ('a', 6)]), sort_keys=False)

rawDescription: Adding duplicate keys to JSON with python


rawDescription: Iterate a format string over a list

description: Iterate a format string over a list


code:
from lxml import etree as ET

data = """<?xml version="1.0" encoding="UTF-8" ?>
<uimap>
    <page name="login">
        <uielement name="username">
             <locator>//input[@type='text']</locator>
        </uielement>
        <uielement name="password">
            <locator>//input[@type='password']</locator>
        </uielement>
    </page>
</uimap>
"""

tree = ET.fromstring(data)
page = 'login'
element = 'username'

print tree.findtext('.//page[@name="{page}"]/uielement[@name="{element}"]/locator'.format(page=page, element=element))

rawDescription: Python function for getting locator values


code:
from collections import Counter
from string import ascii_lowercase

l = ['a','z','y','y','z','y','b','b']

c = Counter(l)

sorted_items = sorted(c.items(), key=lambda x: x[0])

# get result when you need ordinal number of lowcase
print [ (ascii_lowercase.index(k)+1, k, v) for k, v in sorted_items]
# [(1, 'a', 1), (2, 'b', 2), (25, 'y', 3), (26, 'z', 2)]

rawDescription: Make tuples of a list include alphabet ordered number, alphabet, counts


code:
cross_refs = tree.xpath('//cross-ref[following-sibling::node()[1][self::cross-ref]]')
for c in cross_refs:
    print c.text

rawDescription: Detect whether is the immediate sibling of an element is text or another element in lxml


code:
import pandas as pd
from datetime import datetime

df = pd.read_csv('lmt.csv')

# get rid of the format issue
df.rename(columns={df.columns[0]: 'Date' }, inplace=True)

# define your format in the Date column
date_format = '%d-%b-%y'

# select the first date
date1 = datetime.strptime(df['Date'][0], date_format)

# select the second date
date2 = datetime.strptime(df['Date'][10], date_format)

# calculate the difference between the dates
diffDates = date1 - date2

# print results in days
print 'The difference are ' + str(diffDates.days) + ' days.'

rawDescription: How to calculate the number of days between two given dates

description: Calculate the number of days between two given dates


rawDescription: I want to rank document and store them in a list in python


code:
input_ = {'data': [{'data': [{'data': 'gen1', 'name': 'objectID'},
                   {'data': 'familyX', 'name': 'family'}],
          'name': 'An-instance-of-A'},
         {'data': [{'data': 'gen2', 'name': 'objectID'},
                   {'data': 'familyY', 'name': 'family'},
                   {'data': [{'data': [{'data': '21',
                                        'name': 'objectID'},
                                       {'data': 'name-for-21',
                                        'name': 'name'},
                                       {'data': 'no-name', 'name': None}],
                              'name': 'An-instance-of-X:'},
                             {'data': [{'data': '22',
                                        'name': 'objectID'}],
                              'name': 'An-instance-of-X:'}],
                    'name': 'List-of-2-X-elements:'}],
          'name': 'An-instance-of-A'}],
'name': 'main'}

def parse_dict(d, predecessors, output):
    """Recurse into dict and fill list of path-value-pairs"""
    data = d["data"]
    name = d["name"]
    name = name.strip(":") if type(name) is str else name
    if type(data) is list:
        for d_ in data:
            parse_dict(d_, predecessors + [name], output)
    else:
        output.append(("_".join(map(str,predecessors+[name])), data))

result = []

parse_dict(input_, [], result)

print "\n".join(map(lambda x: "%s=%s"%(x[0],x[1]),result))

rawDescription: Getting a python dict.keys trail for each item


code:
# Instead of os.wait():
for p in ps:
    p.wait()
    print 'A process returned:', p.returncode

rawDescription: python parallel Popen

description: Python parallel Popen


code:
def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)
print f.func_defaults
f.func_defaults = (['foo'],) # Don't do this!
print f(4)

rawDescription: What is the scope of a defaulted parameter in Python?


code: for i, j in sorted(d.items(), key=lambda x: x[0].lower()): print i, j

rawDescription: How to iterate over case insensitive sorted dictionary items?

description: Iterate over case insensitive sorted dictionary items


code:
s2=""
L=s.split(" ")
for x in L:
   i=x.find("|")
   s2+=x[:i]+" "
print s2

rawDescription: Denormalize tab-delimited text file

description: Denormalize tab-delimited text file


code:
list1, list2 = [1, 2, 3], [1, 4, 3]
print [index for index, (e1, e2) in enumerate(zip(list1, list2)) if e1 == e2]

rawDescription: list index comparison in python

description: List index comparison in python


code:
import os

import win32file
import win32event
import win32con

path_to_watch = os.path.abspath (".")

#
# FindFirstChangeNotification sets up a handle for watching
#  file changes. The first parameter is the path to be
#  watched; the second is a boolean indicating whether the
#  directories underneath the one specified are to be watched;
#  the third is a list of flags as to what kind of changes to
#  watch for. We're just looking at file additions / deletions.
#
change_handle = win32file.FindFirstChangeNotification (
  path_to_watch,
  0,
  win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)

#
# Loop forever, listing any file changes. The WaitFor... will
#  time out every half a second allowing for keyboard interrupts
#  to terminate the loop.
#
try:

  old_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
  while 1:
    result = win32event.WaitForSingleObject (change_handle, 500)

    #
    # If the WaitFor... returned because of a notification (as
    #  opposed to timing out or some error) then look for the
    #  changes in the directory contents.
    #
    if result == win32con.WAIT_OBJECT_0:
      new_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
      added = [f for f in new_path_contents if not f in old_path_contents]
      deleted = [f for f in old_path_contents if not f in new_path_contents]
      if added: print "Added: ", ", ".join (added)
      if deleted: print "Deleted: ", ", ".join (deleted)

      old_path_contents = new_path_contents
      win32file.FindNextChangeNotification (change_handle)

finally:
  win32file.FindCloseChangeNotification (change_handle)

rawDescription: Python: Waiting for a file to reach a size limit in a CPU friendly manner


code:
c1, c2, c3 = input("Provide 3 Celsius temps. separated with a comma: ")
print "The temperatures are",
for i in range(c1, c2, c3):
    fahrenheit = (9.0 / 5.0) * i + 32
    print fahrenheit,
print "degrees Fahrenheit."

rawDescription: basic input and the for loop

description: Basic input and the for loop


code: print ' '.join(letter for letter, count in hand.iteritems() for i in range(count))

rawDescription: going through a dictionary and printing its values in sequence

description: Going through a dictionary and printing its values in sequence


code:
class A:
    def __init__(self, data):
        self.values_to_counts = {}
        for val in data:
            if val in self.values_to_counts:
                self.values_to_counts[val] += 1
            else:
                self.values_to_counts[val] = 1
    @classmethod
    def from_values_to_counts(cls, values_to_counts):
        self = cls([])
        self.values_to_counts = values_to_counts
        return self

class B(A):
    def __init__(self, data, parameter):
        super(B, self).__init__(data)
        self.parameter = parameter
    def print_parameter(self):
        print self.parameter
    @classmethod
    def from_values_to_counts(cls, values_to_counts):
        self = super(B, cls).from_values_to_counts(values_to_counts)
        do_more_initialization(self)
        return self

rawDescription: Inheritance of from_<type> in Python

description: Inheritance of from_<type> in Python


code:
from xml.etree import ElementTree as ET

XML = """<?xml version="1.0" ?>
    <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2010-11-01">
      <OperationRequest>
        <HTTPHeaders>
            <Header Name="UserAgent" Value="TSN (Language=Python)"></Header>
        </HTTPHeaders>
        <RequestId>96ef9bc3-68a8-4bf3-a2c7-c98b8aeae00f</RequestId>
        <Arguments>
            <Argument Name="Operation" Value="ItemLookup"></Argument>
            <Argument Name="Service" Value="AWSECommerceService"></Argument>
            <Argument Name="Signature" Value="gjc4wRNum3YT82app1d06vMIDM7v44fOmZTP8Uh3LqE="></Argument>
            <Argument Name="AssociateTag" Value="sneakick-20"></Argument>
            <Argument Name="Version" Value="2010-11-01"></Argument>
            <Argument Name="ItemId" Value="810056013349,810056013264"></Argument>
            <Argument Name="IdType" Value="UPC"></Argument>
            <Argument Name="AWSAccessKeyId" Value="AKIAIFMUMJLJOOINRVRA"></Argument>
            <Argument Name="Timestamp" Value="2012-01-03T21:26:39Z"></Argument>
            <Argument Name="ResponseGroup" Value="ItemIds"></Argument>
            <Argument Name="SearchIndex" Value="Apparel"></Argument>
        </Arguments>
       <RequestProcessingTime>0.0595830000000000</RequestProcessingTime>
      </OperationRequest>
      <Items>
          <Request>
              <IsValid>True</IsValid>
              <ItemLookupRequest>
                  <IdType>UPC</IdType>
                  <ItemId>810056013349</ItemId>
                  <ItemId>810056013264</ItemId>
                  <ResponseGroup>ItemIds</ResponseGroup>
                  <SearchIndex>Apparel</SearchIndex>
                  <VariationPage>All</VariationPage>
              </ItemLookupRequest>
          </Request>
          <Item>
              <ASIN>B000XR4K6U</ASIN>
          </Item>
          <Item>
              <ASIN>B000XR2UU8</ASIN>
          </Item>
       </Items>
    </ItemLookupResponse>"""

NS = "{http://webservices.amazon.com/AWSECommerceService/2010-11-01}"

doc = ET.fromstring(XML)
Item_elems = doc.findall(".//" + NS + "Item")  # All Item elements in document

print Item_elems

rawDescription: Parsing xml with etree

description: Parsing xml with etree


code:
import re
data = [[u'text'], [u'element'], [u'text00']]
patterns = [u'text', u'EL', u'00']
results = []
for pattern in patterns:
    results.append([x[0] for x in data if re.search(pattern, x[0], flags=re.I)])
print  results

rawDescription: Python search regex from variable inside a list


code:
import time

for k in range(10):
    num = 10**(10**k)

    start = time.time()
    total = num * num
    finish = time.time()
    elapsed = finish - start

    print k, elapsed

rawDescription: Measuring Big O of multiplication in Python


code:
#!/usr/bin/python

import logging
import sys
import time

logging.basicConfig(level=logging.INFO)

sys.stdout = sys.stderr

i = 0
while 1:
    i += 1
    logging.info('i: {0}'.format(i))
    print i
    time.sleep(0.2)

rawDescription: How to get subprocess output during its running?

description: Get subprocess output during its running


code:
from Tkinter import * # Tkinter -> tkinter in Python 3

root = Tk()

def hello():
    print "hello!"

# create a popup menu
menu = Menu(root, tearoff=0)
menu.add_command(label="Undo", command=hello)
menu.add_command(label="Redo", command=hello)

# create a frame
frame = Frame(root, width=512, height=512)
frame.pack()

def popup(event):
    menu.post(event.x_root, event.y_root)

# attach popup to frame
frame.bind("<Button-3>", popup)

root.mainloop()

rawDescription: Python tkinter app adding a right click context menu?


code:
def print_url_pattern_names(patterns):
    """Print a list of urlpattern and their names"""
    for pat in patterns:
        if pat.__class__.__name__ == 'RegexURLResolver':            # load patterns from this RegexURLResolver
            print_url_pattern_names(pat.url_patterns)
        elif pat.__class__.__name__ == 'RegexURLPattern':           # load name from this RegexURLPattern
            if pat.name is not None:
                print '[API-URL] {} \t\t\t-> {}'.format(pat.name, pat.regex.pattern)

rawDescription: Add a HyperLink in django-rest-framework to a ModelViewSet


code:
r = soup.findAll('span', attrs={"class":"title"})
for span in r:
    print span.text

rawDescription: problems scraping web page using python

description: Problems scraping web page using python


code:
#!/usr/bin/env python

import csv
from scipy import sparse

rows, columns = 10, 100
matrix = sparse.lil_matrix( (rows, columns) )

csvreader = csv.reader(open('1938894-simplified.csv'))
for line in csvreader:
    row, column = map(int, line)
    matrix.data[row].append(column)

print matrix.data

rawDescription: csv to sparse matrix in python

description: Csv to sparse matrix in python


code:
import collections

result = ['a', ['b', ['c', ['d', []]]], 'z', []]

def get_result() :
    for r in result :
        yield r

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el

def remove_z(l) :
    for i in l :
        if i != 'z' :
            yield i

print [ l for l in remove_z(flatten(get_result()))]

rawDescription: Recursive functions

description: Recursive functions


code:
print list[::3] # print it
newlist = list[::3] # copy it

rawDescription: How can I print only every third index in Perl or Python?

description: Print only every third index in Perl or Python


code:
import csv

with open('points.txt', 'r') as f_input:
    points = list(csv.reader(f_input, delimiter='\t'))

# To convert to floats
points = [map(float, x) for x in points]

print points

rawDescription: How to read from a text file in python line by line

description: Read from a text file in python line by line


code: print [data[i:i+2] for i in xrange(0, len(data), 2)]

rawDescription: Best way to regroup a string into a list of 2-character string

description: Regroup a string into a list of 2-character string


code:
import webbrowser
import json
from pprint import pprint
from operator import itemgetter
class MusicLink():
    """
    This class stores a list of songs.
    """
    #
    def __init__(self, lst = None):
        print "Karaoke"
        # you did not use any instance-variables in your class although this is the whole sense of writing a class:
        # store data in a structured way and use methods to deal with those data
        # that's the way to store an instance variable: self.instance_variable = value
        self._songlist = lst or []
        """
        a = lst or []
        # same like means
        if lst is None: # short and more general: if not lst:
            a = []
        else:
            a = lst
        """
        #
    def loadData(self,dataFile):
        # you watched the video, so have heard about with... advantage: you don't have to close the file
        with open(dataFile) as json_data:
            # the json-data are stored in the class variable
            self._songlist = json.load(json_data)["LinkCollection"]
        #
    def searchSong(self,search):
        """
        The following code-line is a list-comprehension. (http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)
        try to read it like a sentence
        Create a list of song(s) by taking every song in musicObject["LinkCollection"]
        but only if the lowercase search-string is within the song 's lowercase title
        """
        return MusicLink([song for song in self._songlist if search.lower() in song["title"].lower() ])
        # instead of returning a list, I return a MusicLink-Object, so I can use all the other method on it
        #
    def sortByTitle(self):
        # instead of deliver the foundMedia it sorts the data in the instance-variable
        return MusicLink(sorted(self._songlist, key=itemgetter('title')))
        # sorted returns a list and that is what MusicLink needs to create a new, sorted instance
        #
    def sortByArtist(self):
        #pprint(foundMedia)
        # ^- I uncommented this line, because it is not good, if two similar functions like sortByTitle and sortByArtist differ in printing behaviour
        sortedByArtistList = sorted(self._songlist, key=itemgetter('artist'), reverse=True)
        return  MusicLink(sortedByArtistList)
        #
    def chooseSong(self):
        print "CHOOSE SONG BY NUMBER"
        pprint(dict(enumerate(self._songlist)))
        #
        while True:
            try:
                entered = int(raw_input('Enter your song number (not id):'))
                chosen_song = self._songlist[entered]
            except:
                # this happens, if var entered isnot int or if it is out of range of songlist
                print " -> Not found!"
            else:
                print " -> Play song..."
                break
        webbrowser.open_new_tab(chosen_song['link'])

rawDescription: How should I write my method to get the 'link' value from the result I get after searching through JSON?


code:
import pygame
import pygame.locals

pygame.init()

screen = pygame.display.set_mode((300,200))

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

            elif event.key == pygame.K_a:

                mods = pygame.key.get_mods()

                if mods & pygame.KMOD_CTRL and mods & pygame.KMOD_SHIFT and mods & pygame.KMOD_ALT:
                    print "pressed: CTRL+SHIFT+ALT + A"
                elif mods & pygame.KMOD_CTRL and mods & pygame.KMOD_SHIFT:
                    print "pressed: CTRL+SHIFT + A"
                elif mods & pygame.KMOD_CTRL and mods & pygame.KMOD_ALT:
                    print "pressed: CTRL+ALT + A"
                elif mods & pygame.KMOD_SHIFT and mods & pygame.KMOD_ALT:
                    print "pressed: SHIFT+ALT + A"
                elif mods & pygame.KMOD_SHIFT:
                    print "pressed: SHIFT + A"
                elif mods & pygame.KMOD_CTRL:
                    print "pressed: CTRL + A"
                elif mods & pygame.KMOD_ALT:
                    print "pressed: ALT + A"
                else:
                    print "pressed: A"

pygame.quit()

rawDescription: Python keydown combinations (ctrl + key or shift + key)


code:
from random import randrange, choice

# this part is to create an exemple file with newline being :;:
alphabet = 'abcdefghijklmnopqrstuvwxyz '
ch = ':;:'.join(''.join(choice(alphabet) for nc in xrange(randrange(0,40)))
                for i in xrange(50))
with open('fofo.txt','wb') as g:
    g.write(ch)

# this generator function is an iterator for a file
# if nl receives an argument whose bool is True,
# the newlines :;: are returned in the lines

def liner(filename,eol,lenchunk,nl=0):
    # nl = 0 or 1 acts as 0 or 1 in splitlines()
    L = len(eol)
    NL = len(eol) if nl else 0
    with open(filename,'rb') as f:
        chunk = f.read(lenchunk)
        tail = ''
        while chunk:
            last = chunk.rfind(eol)
            if last==-1:
                kept = chunk
                newtail = ''
            else:
                kept = chunk[0:last+L]   # here: L
                newtail = chunk[last+L:] # here: L
            chunk = tail + kept
            tail = newtail
            x = y = 0
            while y+1:
                y = chunk.find(eol,x)
                if y+1: yield chunk[x:y+NL] # here: NL
                else: break
                x = y+L # here: L
            chunk = f.read(lenchunk)
        yield tail

for line in liner('fofo.txt',':;:'):
    print line

rawDescription: Special End-line characters/string from lines read from text file, using Python


code:
def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

rawDescription: Function overloading in Python: Missing

description: Function overloading in Python: Missing


code:
click = (120,480)
print "Click ",click," transforms into:"
print ax1.transData.inverted().transform(click)," for axes 1"
print ax2.transData.inverted().transform(click)," for axes 2"

rawDescription: Matplotlib: Centroid of Scatter Plot Circles


rawDescription: Combine two lists into a single dictionary or Print them (shortest way)


code: print MyClass().__dict__

rawDescription: Python Class. key exists as self.key, but doesn't exists in self.__dict__


code:
import MySQLdb
import csv
import pprint
import time
import pickle

MAX_CACHE_AGE = 60*20  # 20 Minutes
CACHE_FILENAME = 'results.cache'

regen = False
try:
    with open(CACHE_FILENAME, 'r') as cache:
        cached = pickle.load(cache)

    if(time.time() > cached['timestamp'] + MAX_CACHE_AGE):
        print("Cache too old: regenerating cache")
        regen = True
    else:
        print("Cached data is fresh enough: loading results from cache")

except IOError:
    print("Error opening %s: regenerating cache" % CACHE_FILENAME)
    regen = True

if(regen):
    # Cache too old, run query
    db = MySQLdb.connect(host="localhost", # The Host
                     user="username", # username
                     passwd="password", # password
                     db="dbname") # name of the data base

    cursor = db.cursor()
    cursor.execute("SELECT name, id, city, storeid FROM Products;")
    StudentsData = cursor.fetchall()
    cursor.close()

    # Update cache file
    data = {'results': StudentsData, 'timestamp':time.time()}
    with open(CACHE_FILENAME, 'w') as cache:
        pickle.dump(data, cache)

else:
    # Cached data is fresh enough, use that
    StudentsData = cached['results']

print StudentsData

rawDescription: caching mysql query returned by Python script

description: Caching mysql query returned by Python script


code:
f = open("mdata.txt")

data_dict = {}
section = None
data_for_section = ""
for line in f:
    line = line.strip() #remove whitespace at start and end

    if section != None and (line[0] == "*" or line == "///"):
        # if we've just finished a section, put whatever we got into the data dict
        data_dict[section] = [bit for bit in data_for_section.split(",") if bit != ""]

    if line[0] == "*":
        # "*" denotes the start of a new section, probably, so remember the name
        section = line [2:]
        data_for_section = ""
        continue
    data_for_section += line

f.close()
#got the data, now for some output
print "loaded file. Found headings: %s"%(", ".join(data_dict.keys()))

for key in data_dict.keys():
    if len(data_dict[key])>5:
        print key, ": array of %i entries"%len(data_dict[key])
    else:
        print key, ": ", data_dict[key]

rawDescription: Read Block Data in Python?

description: Read Block Data in Python


code:
import struct
import Image
import scipy
import scipy.misc
import scipy.cluster

NUM_CLUSTERS = 5

print 'reading image'
im = Image.open('image.jpg')
im = im.resize((150, 150))      # optional, to reduce time
ar = scipy.misc.fromimage(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2])

print 'finding clusters'
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
print 'cluster centres:\n', codes

vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences

index_max = scipy.argmax(counts)                    # find most frequent
peak = codes[index_max]
colour = ''.join(chr(c) for c in peak).encode('hex')
print 'most frequent is %s (#%s)' % (peak, colour)

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


code:
message = rsa.decrypt(crypto, bob_priv)
print message

rawDescription: Decripting RSA in python

description: Decripting RSA in python


code:
def get_moves(a, b):
    ind = range(len(a))
    eq = set()
    moves = []
    for (i,j) in zip(ind[:-1], ind[1:]):
        if b[i] != b[j]:
            e = a[j] - a[i] if not eq else a[max(eq)] - a[min(eq)]
            eq.clear()
        else:
            e = 0
            eq.update([i,j])
        moves.append(e)
    return moves

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

xmove = get_moves(m,n)
ymove = get_moves(n,m)

print xmove, xmove == [1, 1, 0, 0, 2, 1]
print ymove, ymove == [1, 1, 0, 0, 5, 1]

rawDescription: Manipulating two lists

description: Manipulating two lists


code:
soup = BeautifulSoup('

')

for elem in soup.findAll(typeof=['po:MusicSegment', 'po:SpeechSegment']):
    print elem['typeof']

rawDescription: Trouble accessing attribute after using BeautifulSoup's findAll


code:
order = ['name', 'email', 'phone', 'zip']
data = [("email", "<object>"), ('zip', "<object>"), ('name', "<object>"), ('phone', "<object>")]

print sorted(data,key=lambda x:order.index(x[0]))
[('name', '<object>'), ('email', '<object>'), ('phone', '<object>'), ('zip', '<object>')]

rawDescription: Order list of tuples based on a list of strings


code: print BTWcalculator()

rawDescription: Python function struggles

description: Python function struggles


code:
myPattern = u"[\u3041-\u309f\u30a0-\u30ff]*"
print re.sub(myPattern, "", u"Eliminate ひらがな non-alphabetic カタカナ characters")

rawDescription: Why does this Python RegEx pipe not pick out both unicode ranges?


code:
from PyQt4 import QtGui
import PyQt4.uic
import sys

class TestController(QtGui.QWidget):

    def __init__(self):
        super(TestController, self).__init__()

        # load a view from an external template
        uifile = '/path/to/some/widget.ui'
        self.ui = PyQt4.uic.loadUi(uifile, self)

        # create connections (assuming there is a widget called 'btn' that is loaded)
        self.ui.btn.clicked.connect(self.buttonClicked)

    def buttonClicked(self):
        print 'clicked'

def main():
    app = QtGui.QApplication(sys.argv)
    view = TestController()
    view.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: How to connect a signal from the controller in PyQt4? (iOS like MVC structure in PyQt4)

description: Connect a signal from the controller in PyQt4? (iOS like MVC structure in PyQt4)


code:
import matplotlib.pyplot as plt
from matplotlib.backend_bases import NavigationToolbar2, Event

home = NavigationToolbar2.home

def new_home(self, *args, **kwargs):
    s = 'home_event'
    event = Event(s, self)
    event.foo = 100
    self.canvas.callbacks.process(s, event)
    home(self, *args, **kwargs)

NavigationToolbar2.home = new_home

def handle_home(evt):
    print 'new home'
    print evt.foo

fig = plt.figure()
fig.canvas.mpl_connect('home_event', handle_home)
plt.text(0.35, 0.5, 'Hello world!', dict(size=30))
plt.show()

rawDescription: matplotlib hooking in to home/back/forward button events

description: Matplotlib hooking in to home/back/forward button events


code:
lista_set = set(lista)
for item in listb:
    if item[0] in lista_set:
        print item

rawDescription: Compare list w/ sublist

description: Compare list w/ sublist


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

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

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


code:
import os
import re
def meminfo():

    with os.popen('free -m') as f:
        output = f.read()

    fields = re.search(r'Mem\:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)',
            output,re.M).group
    return dict(total=fields(1),used=fields(2),free=fields(3),
            shared=fields(4),buffers=fields(5),cached=fields(6))

print meminfo()

rawDescription: Python system resources enumeration

description: Python system resources enumeration


code:
import itertools
from datetime import datetime, timedelta

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

for (day,name) in itertools.izip((day for day in (datetime.today()+timedelta(n) for n in itertools.count()) if day.weekday() not in (5,6)), (itertools.cycle(names))):
    if days == 0:
        break

    print "| %s | %s | %s |" % (day.strftime("%d-%m-%Y"), name, extns[name])
    days-= 1

rawDescription: Incrementing date whilst ignoring weekends


code:
import inspect
import functools

class _Default(object):
    def __init__(self, repr):
        self._repr = repr
    def __repr__(self):
        return self._repr

def _buildFacade(name, spec, docstring):
    """Build a facade function, matching the decorated method in signature.

    Note that defaults are replaced by instances of _Default, and _curried
    will reconstruct these to preserve mutable defaults.

    """
    args = inspect.formatargspec(
        formatvalue=lambda v: '=_Default({0!r})'.format(repr(v)), *spec)
    callargs = inspect.formatargspec(formatvalue=lambda v: '', *spec)
    return 'def {0}{1}:\n    """{2}"""\n    return _curried{3}'.format(
        name, args, docstring, callargs)

def add_docs(tool):
    spec = inspect.getargspec(tool)
    args, defaults = spec[0], spec[3]

    arglen = len(args)
    if defaults is not None:
        defaults = zip(args[arglen - len(defaults):], defaults)
        arglen -= len(defaults)

    def _curried(*args, **kw):
        # Reconstruct keyword arguments
        if defaults is not None:
            args, kwparams = args[:arglen], args[arglen:]
            for positional, (key, default) in zip(kwparams, defaults):
                if isinstance(positional, _Default):
                    kw[key] = default
                else:
                    kw[key] = positional

        return tool(*args, **kw)

    name = tool.__name__
    doc = 'Showing help for {0}()'.format(name)
    facade_globs = dict(_curried=_curried, _Default=_Default)
    exec _buildFacade(name, spec, doc) in facade_globs

    wrapped = facade_globs[name]
    wrapped = functools.update_wrapper(wrapped, tool,
        assigned=filter(lambda w: w != '__doc__', functools.WRAPPER_ASSIGNMENTS))

    return facade_globs[name]

rawDescription: Python dynamic help and autocomplete generation


rawDescription: How can i print list of dict values, one value in list for each key

description: Print list of dict values, one value in list for each key


code:
import re

with open('input.txt', 'r') as f_input:
    data = f_input.read()
    print re.findall(r'(mutant\s.*?\scauses.*?GS)', data, re.S)

rawDescription: Searching for specific phrase pattern within lines. python


rawDescription: Search specific format in specific order for a text file data


code: print "This should be reprinted only ten times\n"*10

rawDescription: Limiting loop repetition in python

description: Limiting loop repetition in python


rawDescription: Removing array in matrix if specific value shows up


code:
a = 257
b = 257
print a is b

rawDescription: Python3 multiple assignment and memory address


code:
def p4(base_num):
    numrefs = ['nums/89/202089/4', 'nums/39/205739/2', 'nums/94/195594/6']
    num_ignore = [150362, 147117, 147441, 143446, 200914]

    with open('./num_ids.txt', 'rb') as f:
        for line in f:
            text = line.strip()  # Trim trailing whitespace and newline
            num = int(text)
            if (num > base_num
                    and num not in num_ignore
                    # Check for any substring in list of strings
                    and any(text in numref for numref in numrefs)):
                print text

rawDescription: Matching line variable with numrefs list


code:
import pandas as pd
a = pd.read_csv('./test', header=None, skiprows = 2)
print a

rawDescription: How to setup string to float converters for numpy genfromtxt

description: Setup string to float converters for numpy genfromtxt


code:
for c in JobStatus.__table__.columns:
    print c

for c in JobStatus.__table__.foreign_keys:
    print c

rawDescription: method of iterating over sqlalchemy model's defined columns?

description: Method of iterating over sqlalchemy model's defined columns


code:
for _ in range(3):
    print 'Roll the first row one place, modifying the original'
    independent_roll_inplace(grid, 0, 1)
    print grid

rawDescription: Numpy: how to roll 1 "row" in an array of arrays


code:
def resource_wrapper(resource_class):
    def decorate(cls):
        for attr in dir(cls):
            if callable(getattr(cls, attr)) and not attr.startswith('_'):
                setattr(cls, attr, _function_wrapper(cls, getattr(cls, attr)))
        return cls
    return decorate(resource_class)

def _function_wrapper(cls, fn):
    from functools import wraps

    @wraps(fn)
    def wrapper(*args, **kwargs):
        self = cls
        arg = kwargs.pop('test', False)

        print arg  # See output further down

        return fn(*args, **kwargs)

    return wrapper

rawDescription: Decorate all class methods without redecorating each time


code:
from itertools import product
print list(product(range(2), repeat = 3))

rawDescription: Generating permutations

description: Generating permutations


code:
myList = ['a', 'b', 'c']
dict_var=dict()
for key in myList:
    dict_var[key]=list()
print dict_var

rawDescription: Pythonic ways to create independent lists from a list?


code:
import nltk
from nltk.tokenize import word_tokenize

lin = "A frequency distribution for the outcomes of an experiment. A frequency distribution records the number of times each outcome of an experiment has occurred. For example, a frequency distribution could be used to record the frequency of each word type in a document. Formally, a frequency distribution can be defined as a function mapping from each sample to the number of times that sample occurred as an outcome."

fdist = nltk.FreqDist()

for word in word_tokenize(lin):
    fdist.inc(word)

for f in fdist:
    print f, fdist[f]

rawDescription: FreqDist Python ... at the end issue

description: FreqDist Python ... at the end issue


code:
import requests
from bs4 import BeautifulSoup

research_later = "hiya"
goog_search = "https://www.google.co.uk/search?sclient=psy-ab&client=ubuntu&hs=k5b&channel=fs&biw=1366&bih=648&noj=1&q=" + research_later

r = requests.get(goog_search)

soup = BeautifulSoup(r.text, "html.parser")
print soup.find('cite').text

rawDescription: How can I scrape the first link of a google search with beautiful soup

description: Scrape the first link of a google search with beautiful soup


code:
if e.modifiers() & Qt.ShiftModifier:
    print 'The Shift key is pressed'

if e.modifiers() & Qt.ControlModifier:
    print 'The control key is pressed'

if e.modifiers() & Qt.ShiftModifier and e.modifiers() & Qt.ControlModifier:
    print 'Ctrl+Shift was pressed'

rawDescription: How to handle keyboard shortcuts using keyPressEvent()? And should it be used for it?

description: Handle keyboard shortcuts using keyPressEvent()? And should it be used for it


code:
#! /usr/bin/python

import sys

def read_input_from(file):
    print file.read(),

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # filename supplied, so read input from that
        filename = sys.argv[1]
        file = open(filename)
    else:
        # no filename supplied, so read from stdin
        file = sys.stdin
    read_input_from(file)

rawDescription: Pythonic equivalent of ./foo.py < bar.png


code:
from math import log10
def rev(num):
    if num < 10:
        return num
    else:
        ones = num % 10
        rest = num // 10
        #print ones, rest, int(log10(rest) + 1), ones * 10 ** int(log10(rest) + 1)
        return ones * 10 ** int(log10(rest) + 1) + rev(rest)
print rev(9000), rev(1234), rev(1234567890123456789)

rawDescription: Python reverse integer using recursion

description: Python reverse integer using recursion


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

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

def main():
    p = Person('Joe')            # Instantiate `Person` class (calls constructor)
    p.sayHello()                 # Call an "instance method" on Person object

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

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


code:
# Keys that are in old_bills, but not new_bills
print set(old_bills.keys()) - set(new_bills.keys())

# Keys that are in new_bills, but not old_bills
print set(new_bills.keys()) - set(old_bills.keys())

# Compare columns for same billing records
# Will print True or False
print old_bills['2']['CustomerName'] == new_bills['2']['CustomerName']
print old_bills['2']['IsActive'] == new_bills['2']['IsActive']

rawDescription: Compare 2 .csv files with Python then output results


code: print "Hi, my name is %s." % name

rawDescription: Python 2.7: % string format vs. calling variable outside string?


code:
def invert_dict(inverted_dict):
    elements = inverted_dict.iteritems()
    for flag_value, flag_names in elements:
        for flag_name in flag_names:
            yield flag_name, flag_value

flags = {True: ["a", "b", "c"], False: ["d", "e"]}
flags = dict(invert_dict(flags))
print flags

rawDescription: More elegant way of declaring multiple variables at the same time


code:
for simplex in alphashape:
    print [v for v in simplex.vertices]

rawDescription: How can I find the alpha shape (concave hull) of a 2d point cloud?

description: Find the alpha shape (concave hull) of a 2d point cloud


code:
a = ['a', 'b', 'a', 'c', 'b']
from collections import defaultdict
result = defaultdict(list)
for idx, item in enumerate(a):
    result[item].append(idx)
print result

rawDescription: Covert this list in python in the following format


code:
def balance2 (p, apr, mo):
    mpr =  ((1+apr/100.0)**(1/12.0)-1)
    for month in range(int(mo)):
        p= p+p*mpr
    return p

print
for i in range(1,13):
    print balance2(1000,10,i)

rawDescription: How can I find the credit card balance regarding my code?

description: Find the credit card balance regarding my code


code:
var = struct.pack('2s2b', 'ME', 0, 0)
print repr(var)

rawDescription: How can you pack an array of 2 chars + 2 null characters with python's struct?

description: Pack an array of 2 chars + 2 null characters with python's struct


code: print '\n'.join('{}. {}'.format(i, v) for (i,v) in enumerate(d.itervalues(), 1))

rawDescription: How to print current loop number in an iteration over a dictionary in Python?

description: Print current loop number in an iteration over a dictionary in Python


code:
# really, it's variable-tester-factory
def variable_tester(target):
    def deco(function):
        def inner(self, *args, **kwargs):
            if getattr(self, target) is not None:
                return function(self, *args, **kwargs)
        return inner
    return deco

class my_class(object):
    def __init__(self):
        self.var = None

    @variable_tester('var')
    def printout(self):
        print self.var

rawDescription: How to pass a class variable to a decorator inside class definition?

description: Pass a class variable to a decorator inside class definition


code:
data = [['COMPANY:', [('U S News & World Report Inc', 63)]],
 ['ORGANIZATION:',
  [('Ashoka', 0),
   ('Innovators For The Public', 91),
   ('Us Environmental  Protection Agency', 55)]]]

results = []

for name, rest in data:
    name = name.replace(":","").capitalize()
    for orgs, percent in rest:
        results.append( [name, orgs, percent] )

import pandas as pd

df = pd.DataFrame( results, columns=['NAME', 'ORGS', 'PERCENT'])

print df

rawDescription: Turning a list of tuples with variable lengths into a dataframe


code:
#!/usr/bin/env python

snippet = """

Football

Team A
Team B

Baseball

Team C
Team D

"""

import lxml.html

html = lxml.html.fromstring(snippet)
body = html[1]

results = []

for e in body.xpath('./a'):
    results.append(dict(
        category=e.xpath('preceding-sibling::div/a')[-1].text,
        title=e.text))

print results

rawDescription: lxml: split at attribute?

description: Lxml: split at attribute


code:
with open("file.txt", 'r') as f:
    lines = f.readlines()
    current_line_index = 0
    next_line = lines[current_line_index + 1]
    print next_line

rawDescription: Checking next Line to then implement where the line should go to


rawDescription: Accessing values in a list of nested dictionaries


code:
class X(object):

    def __init__(self):
        self.settings = {'result_dir':'dir'}
        self.args = {'run_id':'id'}

    def some_method(self):
        print re.sub(r'\$(\w+)(\.(\w+))?', lambda m: getattr(self, m.group(1))[m.group(3)], '$settings.result_dir + $args.run_id')

X().some_method()

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

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


code:
import time
import re

rec1 = re.compile('(?P<head>\[\[foo[^\[]*)abc')
rec2 = re.compile('(?=\[\[foo[^\[]*)abc')

total1, total2 = 0.0, 0.0

def timeRE(ver):
    x = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" * 100)
    t1 = time.time()
    if ver is 1:
        rec1.sub("def", x)
    else:
        rec2.sub("def", x)
    return (time.time() - t1)

for x in xrange(50000):
    total1 += timeRE(1)

for x in xrange(50000):
    total2 += timeRE(2)

print total1
print total2

rawDescription: Which regex is more efficient?

description: Which regex is more efficient


rawDescription: Split list python

description: Split list python


code:
from functools import wraps

import schedule

def do_once(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        func(*args, **kwargs)
        return schedule.CancelJob
    return wrapped

@do_once
def some_one_off_job():
    # Do some work
    # No need to return schedule.CancelJob
    print 5

@do_once
def some_other_one_off_job():
    # hooray, decorators!
    pass

schedule.every().day().at('14:38').do(some_one_off_job)
schedule.every().day().at('14:38').do(some_other_one_off_job)

rawDescription: Fire a python script at a specific time

description: Fire a python script at a specific time


code:
animal_list = numpy.array(['cat', 'elephant'])
your_list = numpy.array(['dog', 'horse', 'cat', 'shark', 'cancer', 'elephant'])
mask = np.in1d(your_list, animal_list)
print mask[1]

rawDescription: List of Elements to Boolean Array

description: List of Elements to Boolean Array


rawDescription: Generating recurring dates using python?

description: Generating recurring dates using python


code:
class User():
    def __init__(self, company_name='unknown', title='unknown'):
        self.company_name = company_name
        self.title = title

data_db_form = {'company_name': 'Google', 'title': 'headline'}

user = User(**data_db_form)

print user.company_name # prints Google
print user.title        # prints headline

rawDescription: Save dictionary to model object

description: Save dictionary to model object


code:
import re
s1 = "1) car collisions effect 3 right lanes"
s2 = "2) 3 car collisions effect right lanes"
print re.findall("(\d+)(?=(?:\s+\w+){,2}\s+right lanes)", s1)
print re.findall("(\d+)(?=(?:\s+\w+){,2}\s+right lanes)", s2)

rawDescription: python regex word repeat time

description: Python regex word repeat time


code:
def test_netcat_subprocess_async(net, duration):

    file_dir = "/home/mininet/sf_mininet_vm/data/MVI_0406_split"
    files = os.listdir(file_dir)

    start_time = time.time()
    end_time = start_time + duration

    # Transfer for the desired duration
    while time.time() < end_time:
        # Choose a pair of hosts
        host_pair = random.sample(net.hosts, 2)

        test_send_one_file_netcat(file_dir, host_pair, files)

        interval = random.uniform(0.01, 0.1)
        print "Initialized transfer; waiting %f seconds..." % interval
        time.sleep(interval)

rawDescription: Sending "random" traffic through Mininet network


code:
from collections import OrderedDict
import csv
def func():
    list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
    with open('example.txt') as f:
        spamreader = csv.reader(f, delimiter=',')
        return [OrderedDict(zip(list_of_keys,row)) for row in spamreader]

print func()
[OrderedDict([('S_Length', '2.1'), ('S_Width', '3.5'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Iris')]), OrderedDict([('S_Length', '4.9'), ('S_Width', '3.0'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Ilia')]), OrderedDict([('S_Length', '3.7'), ('S_Width', '3.2'), ('P_Length', '1.3'), ('P_Width', '0.2'), ('Predicate', 'Iridium')])]

rawDescription: Make a list of dynamic dictionary python


code:
for vertex in g.vertices():
    print pos[vertex]

rawDescription: How to get the coordinates of a graph drawn by specific layout algorithm in graph-tool?

description: Get the coordinates of a graph drawn by specific layout algorithm in graph-tool


code:
import addressbook_pb2 as addressbook

typeDict = {"1":"CGFloat", "2":"CGFloat", "3":"NSInteger", "4":"NSUinteger", "5":"NSInteger", "8":"BOOL", "9":"NSString", "13":"NSUinteger", "17":"NSInteger", "18":"NSInteger"}

attrDict = {"CGFloat":"assign", "NSInteger":"assign", "NSUinteger":"assign", "BOOL":"assign", "NSString":"copy"}

p = addressbook.Person()
all_fields = p.DESCRIPTOR.fields_by_name
field_keys = all_fields.keys()
for key in field_keys:
    one_field = all_fields[key]
    typeNumStr = str(one_field.type)
    className = typeDict.get(typeNumStr, "NSObject")
    attrStr = attrDict.get(className, "retain")
    propertyStr = "@property (nonatomic, %s) %s *%s" %(attrStr, className, key)
    print propertyStr

rawDescription: How to get the type of a variable defined in a protobuf message?

description: Get the type of a variable defined in a protobuf message


code:
def pingIP(self, ip):
    proc = subprocess.Popen("ping %s" % ip, shell=True,
                            stdout=subprocess.PIPE)
    print
    while True:
        line = proc.stdout.readline()
        wx.Yield()
        if line.strip() == "":
            pass
        else:
            print line.strip()
        if not line: break
    proc.wait()

rawDescription: Printing Scapy output to wxPython Text Controller


rawDescription: How to iteratively count in Pandas Dataframe

description: Iteratively count in Pandas Dataframe


code:
for i in range(start_pos, len(my_string)):
   print my_string[i]

rawDescription: Iterate through python string starting at index


code:
amount_of_numbers = {}
for key, value in some_dictionary.items():
    amount_of_numbers[key] = len ([string for string in value if all(char.isdigit() for char in string) ])
print amount_of_numbers
{'SECOND': 1, 'THIRD': 2, 'FIRST': 2}

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

description: Count the numbers in values in a dictionary


code:
import threading

class MiThread(threading.Thread):
      def __init__(self, num):
          threading.Thread.__init__(self)
          self.num = num

      def run(self):
          while true:
             print "Soy el hilo", self.num

print "Soy el hilo principal"

for i in range(0, 10):
    t = MiThread(i)
    t.start()

rawDescription: Take control of interpreter in multithreaded program


code:
import foo
import inspect

for a,b in inspect.getmembers(foo, inspect.isclass):
    print a
    print len(inspect.getmembers(b, inspect.ismethod))

rawDescription: get number of functions within a class in python?

description: Get number of functions within a class in python


code: print nodes[-1]

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

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


code:
words.sort(key=len)
for word in words:
    print word

rawDescription: Find words from a sequence of random letters?


code:
#!/usr/bin/env python
from lxml import html

doc = html.fromstring('''
    <meta name="Description">
    <meta name="description">
    <META name="description">
    <meta NAME="description">
''')
for meta in doc.xpath('//meta[re:test(@name, "^description$", "i")]',
                      namespaces={"re": "http://exslt.org/regular-expressions"}):
    print html.tostring(meta, pretty_print=True),

rawDescription: Is it possible for lxml to work in a case-insensitive manner?


code:
d = "2015-09-01"
print df.index == pd.to_datetime(d).to_period('M')
[False]

d = "2015-11-01"
print df.index == pd.to_datetime(d).to_period('M')
[True]

rawDescription: Check if a pandas.Timestamp is in a pandas.Period


code:
class Test:
    var = 3
    def __init__(self):
        pass

a = Test()
print "a " +  str(a.var)
Test.var = 5
b = Test()
print "b " + str(b.var)
print "a " + str(a.var)

rawDescription: Create Shared Member Variable between instances (static)


rawDescription: Python Regex matching string between \n and |


code:
from itertools import product

print sum(1 for combo in product('13579', repeat=4))

rawDescription: How to check if all the digits of a number are odd in python?

description: Check if all the digits of a number are odd in python


code:
def greet(who):
    print "Hello %s" % who

greet_command = lambda: greet("World")
# pass the callable around, and invoke it later
greet_command()

rawDescription: General Command pattern and Command Dispatch pattern in Python


code:
from selenium import webdriver

driver = webdriver.Chrome()

# set the viewport size to 800 x 600
set_viewport_size(driver, 800, 600)

# display the viewport size
print driver.execute_script("return [window.innerWidth, window.innerHeight];")

rawDescription: How to set browser viewport size

description: Set browser viewport size


code:
import re
from bs4 import BeautifulSoup

data = """

Title 1

Some text

Some other text

Title 2

Some text

Some text2

Title 3

Some text

Some other text

"""

soup = BeautifulSoup(data)

for h1 in soup.find_all('h1', text=re.compile('Title \d+')):
    for p in h1.find_next_siblings('p', limit=2):
        print p.text.strip()

rawDescription: Parse HTML using BeautifulSoup depending on previous tag


code:
class Article(object):
    def __init__(self, id, author):
        self.id = id
        self.__author = None

    def lookup_author(self):
        return "John Doe"

    def __str__(self):
        return "<Author: {}>".format(self.author)

    @property
    def author(self):
        if self.__author is None:
            self.__author = self.lookup_author()
        return self.__author

    @author.setter
    def author(self,name):
        self.__author = name

article1 = Article(1, 'John Doe')
print "\n", article1.author
print article1

article1.author = 'bob'
print "\n", article1.author
print article1

rawDescription: Delaying / Calling Class Attributes Set Equal to Methods


code:
class Node(object):
    def __init__(self, key, weight):
        """Constructor for """
        self.key = key
        self.weight = weight

    def __cmp__(self, other):
        return cmp(self.key, other.key)

    def __str__(self):
        return "".join(['Node(key=', str(self.key), ',weight=', str(self.weight), ")"])

    def __hash__(self):
        return ord(self.key)

__dict = {}
a1 = Node('A', 1)
a2 = Node('A', 2)
__dict[a1] = a1
print a1 == a2 # True
print a1 is a2 # False
print(__dict.get(a1)) # Node(key=A,weight=1)
print(__dict.get(a2)) # Node(key=A,weight=1)

rawDescription: is Dict.get in Python use is to compare keys in dict?

description: Is Dict.get in Python use is to compare keys in dict


code:
def highestNumber(l):
    myMax = l[0]
    for num in l:
        if myMax < num:
            myMax = num
    return myMax

print highestNumber ([77,48,19,17,93,90])

rawDescription: Python: Function returning highest value in list without max()?


code:
import socket, json

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

if __name__ == '__main__':
    listen_sock = socket.socket()
    try:
        listen_sock.bind(('', 3005))
        listen_sock.listen(10)
        client_sock, client_addr = listen_sock.accept()
    finally:
        listen_sock.close()

    try:
        client_sock = socket_to_file(client_sock)
        request = json.loads(client_sock.readline())
        print 'Request: %s' % (request,)
        response = 'My smart response.'
        print 'Response: %s' % (response,)
        client_sock.write(json.dumps(response))
        client_sock.write('\n')
        client_sock.flush()
    finally:
        client_sock.close()

rawDescription: Python working with sockets the method recv


code:
from itertools import groupby

L = [2, 2, 3, 4, 4, 10]

L.sort()
for key, iterator in groupby(L):
    print key, list(iterator)

rawDescription: How to sort like values in Python

description: Sort like values in Python


code:
fig = pylab.gcf()
ax = pylab.gca()
print fig.bbox.bounds
print ax.bbox.bounds
ylabel = ax.yaxis.label
print ylabel.get_transform().transform(l.get_position())

print ylabel.get_window_extent()

rawDescription: Align a matplotlib figure to the text in LaTeX


code:
import numpy

#http://stackoverflow.com/questions/9062387/ifft-of-symmetric-spectrum/9062837#9062837

# test
waveform = [1,2,3,4,5,6]
print( waveform )

fullSpectrum = list( numpy.fft.fft( foo ) )
for w in fullSpectrum:
    print w

# In my practical application, I would be receiving frequencies DC through Nyquist,
#  i.e. the half of the spectrum containing the positive frequencies, and I would
#  need to reconstitute the negative frequencies using symmetry:
#
DC_to_Nyquist = list( numpy.fft.fft( foo ) )[0:4]

# RESTORE FULL SPECTRUM BY SYMMETRY
DC      = DC_to_Nyquist[0].real + 0j
nyquist = DC_to_Nyquist[-1].real + 0j

# discard DC and Nyquist from list
Z = DC_to_Nyquist[1:-1]

Z_reverse = Z[::-1]
Z_conj_reverse = [ w.conjugate() for w in Z_reverse ]

spectrum = [DC] + Z + [nyquist] + Z_conj_reverse

print( "\nSpectrum" )
for w in spectrum:
    print( w )

# INVERSE FFT
timedomain = list( numpy.fft.ifft( spectrum ) )

#ir = [s.real for s in timedomain]

print( "\nTimedomain" )
for w in timedomain:
    print w

rawDescription: Python: convert frequency response to impulse response


code:
from itertools import chain
l2 = numpy.array(list2)
print chain(*[l2+i for i in list1])

rawDescription: Element to Element addition of two lists in python


code:
chain = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]

new_chain = []

for _ in chain:
    if _ == "fourteen":
        new_chain.append("forty")
    elif str.endswith(_,"een"):
        new_chain.append(_[:-3]+"y")
print new_chain

rawDescription: How to replace each letters in multiple words

description: Replace each letters in multiple words


code:
from itertools import groupby, imap

list1 = ["abc.1", "abc.2", "abc.3", "abc.7", "xyz.1", "xyz.3", "xyz.11", "ghj.1", "thj.1"]

def break_up(s):
    a, b = s.split(".")
    return a, int(b)

def prefix(broken_up): return broken_up[0]
def suffix(broken_up): return broken_up[1]

result = []
for key, sub in groupby(imap(break_up, list1), prefix):
    result.append((key, tuple(imap(suffix, sub))))

print result

rawDescription: Python:reduce list but keep details

description: Python:reduce list but keep details


code:
data = {'NOMSEXITInterview__INTTYPE_2': u'2',
 'NOMSEXITInterview__INTDUR_2': u'3',
 'NOMSEXITInterview__GENDER_2': u'3',
 'NOMSEXITInterview__EMPLOY_2': u'6',
 'Referral__referral_type': u'food',
 'Referral__ok_to_mail': u'False',
 'Referral__okay_to_call': u'False',
 'Referral__okay_to_leave_message': u'True',
 'data_model_name': ['NOMSEXITInterview', 'Referral']}

result = {}
for k, v in data.items():
    parts = k.split("__")
    if len(parts) == 2:
        result.setdefault(parts[0], {})[parts[1]] = v
    else:
        result[k] = v
print result

rawDescription: how to handle two dimensional dict in python?

description: Handle two dimensional dict in python


code:
my_list = [True, 10.8, [1,2,3], False, True, "Hello", 12, "Sbioer", 2.5]

for i, item in enumerate(my_list):
    if isinstance(item, basestring):
        print i

rawDescription: Finding the index of the element contains string in a list