code:
import matplotlib.pyplot as plt
import numpy as np
import time

x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]

fig.show()

tstart = time.time()
for i in xrange(1, 20):
    for j, line in enumerate(lines, start=1):
        line.set_ydata(np.sin(j*x + i/10.0))
    fig.canvas.draw()

print 'FPS:' , 20/(time.time()-tstart)

rawDescription: why is plotting with Matplotlib so slow?

description: Why is plotting with Matplotlib so slow


rawDescription: asyncio's call_later raises 'generator' object is not callable with coroutine object

description: Asyncio's call_later raises 'generator' object is not callable with coroutine object


code:
#!/usr/bin/python
import re
reg4 = re.compile(r'''
        ^                 # Start of a line (due to re.MULTILINE, this may match at the start of any line)
        PMID-\s           # Literal "PMID-" followed by a space
        (?P<pmid>[0-9]+)  # Then a string of one or more digits, group as 'pmid'
        .*?               # Next part:
        TI\s{2}-\s        # "TI", two spaces, a hyphen and a space
        (?P<title>.*?)    # The title, a non greedy match that will capture everything up to...
        ^PG               # The characters PG at the start of a line
        .*?               # Next option
        AB\s{2}-\s        # "AB  - "
        (?P<abstract>.*?) # The abstract, a non greedy match that will capture everything up to...
        ^AD               # "AD" at the start of a line
        ''', re.MULTILINE | re.DOTALL | re.VERBOSE)
for i in reg4.finditer(data):
    print i.groupdict()

rawDescription: Match multiple patterns in a multiline string


code: print "insert into users values({0}, {1}, {2}, ...);".format(*arr)

rawDescription: Python print array in one print function


code:
from ast import literal_eval
import re

from bs4 import BeautifulSoup
import requests

url = "https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-month"
payload = {
    'opt_period': '0',
    'opt_Country': '12',  # 12 stands for DE here
    'opt_Month': '1',
    'opt_Year': '2014',
    'opt_Response': '1',
    'send': 'send',
    'opt_period': '0'
}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36'}

with requests.Session() as session:
    session.headers = headers
    session.get(url)

    response = session.post(url, data=payload)

    soup = BeautifulSoup(response.content)
    script = soup.find('script', text=re.compile(r'Ext.onReady')).text

    data = literal_eval(re.search(r"var myData = (.*?);", script, re.MULTILINE).group(1))
    for row in data:
        print row

rawDescription: Scraping data from a dynamic web database with Python


code:
if cv2.waitKey(33) == ord('a'):
   print "pressed a"

rawDescription: Using other keys for the waitKey() function of opencv


code: print event['start']['dateTime']

rawDescription: How to return ALL events in a Google Calendar without knowing whether it is a timed or all day event

description: Return ALL events in a Google Calendar without knowing whether it is a timed or all day event


code:
import json
import scrapy

class BuzzSpider(scrapy.Spider):
    name = 'buzzbuzzhome'
    allowed_domains = ['buzzbuzzhome.com']
    start_urls = ['https://www.buzzbuzzhome.com/uc/units/houses/sapphire']

    def parse(self, response):
        unit_id = response.xpath("//div[@id = 'unitDetails']/@data-unit-id").extract()[0]
        development_url = "uc"
        new_relic_id = response.xpath("//script[contains(., 'xpid')]").re(r'xpid:"(.*?)"')

        params = {"developmentUrl": development_url, "unitID": unit_id}
        yield scrapy.Request("https://www.buzzbuzzhome.com/bbhAjax/Development/UnitPriceHistory",
                             method="POST",
                             body=json.dumps(params),
                             callback=self.parse_history,
                             headers={
                                 "Accept": "*/*",
                                 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36",
                                 "X-Requested-With": "XMLHttpRequest",
                                 "X-NewRelic-ID": new_relic_id,
                                 "Origin": "https://www.buzzbuzzhome.com",
                                 "Host": "www.buzzbuzzhome.com",
                                 'Content-Type': 'application/json; charset=UTF-8'
                             })

    def parse_history(self, response):
        for row in response.css("div.row"):
            title = row.xpath(".//div[@class='content-title']/text()").extract()[0].strip()
            text = row.xpath(".//div[@class='content-text']/text()").extract()[0].strip()

            print title, text

rawDescription: scrapy unable to extract some data from website

description: Scrapy unable to extract some data from website


code:
class MultiOrderedDict(OrderedDict):
    def __setitem__(self, key, value):
        if isinstance(value, list) and key in self:
            self[key].extend(value)
        else:
            super(OrderedDict, self).__setitem__(key, value)

config = ConfigParser.RawConfigParser(dict_type=MultiOrderedDict)
config.read(['a.txt'])
print config.get("test",  "foo")
print config.get("test",  "xxx")

rawDescription: How to ConfigParse a file keeping multiple values for identical keys?


code: print sorted_x

rawDescription: compute tf-idf with corpus

description: Compute tf-idf with corpus


code:
#!/usr/bin/env python
import sys
print sys.argv

rawDescription: optparse does not save second whitespace into arg

description: Optparse does not save second whitespace into arg


code:
import theano
import theano.tensor as tt
import theano.ifelse

def step(x_t, s_tm1):
    return s_tm1 + x_t

def compile():
    K = tt.lscalar()
    t = tt.arange(1, K)
    zero = tt.constant(0, dtype='int64')
    outputs, _ = theano.scan(step, sequences=[t], outputs_info=[zero])
    output = theano.ifelse.ifelse(tt.gt(K, 1), outputs[-1], zero)
    return theano.function([K], outputs=[output])

def main():
    f = compile()
    print f(3)
    print f(2)
    print f(1)
    print f(0)
    print f(-1)

main()

rawDescription: How to handle empty sequence with theano.scan()?

description: Handle empty sequence with theano.scan()


code: print ret_dict.values()

rawDescription: Python - Convert JSON object data into a List


code:
s = """\
mytuple = [('Andrew','Andrew@gmail.com','20'),('Jim',"Jim@gmail.com",'12'),("Sarah","Sarah@gmail.com",'43'),("Jim","Jim@gmail.com",'15'),("Andrew","Andrew@gmail.com",'56')]
set([k[1] for k in mytuple])
"""
print timeit.timeit(stmt=s, number=100000)
0.0699651241302

rawDescription: Dropping values from a list of tuples

description: Dropping values from a list of tuples


code:
def get_num(msg, type_=int):
    while True:
        try:
            return type_(raw_input(msg))
        except ValueError:
            print "The value you entered isn't a valid number, please try again."

rawDescription: Changing global variables within a function


code:
from collections import Counter
print [item for items, c in Counter(a).most_common() for item in [items] * c]
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]

rawDescription: Sorting a List by frequency of occurrence in a list


rawDescription: Nested list with dictionary as content

description: Nested list with dictionary as content


rawDescription: Python: numpy/pandas change values on condition


code: print ''

rawDescription: Print a row of numbers and then have it make a new line and continue counting


code:
table = soup.find("table", class_="yfnc_tabledata1")
total_revenue_label = table.find(text=re.compile(r'Total Revenue'))
print total_revenue_label.parent.parent.next_sibling.get_text(strip=True)

rawDescription: Why is this tag empty when parsed with beautiful soup?


code:
for i in range(20):
    trainer.trainEpochs( 1 )
    trnresult = percentError( trainer.testOnClassData(),
                              trndata['class'] )
    tstresult = percentError( trainer.testOnClassData(
           dataset=tstdata ), tstdata['class'] )

    print "epoch: %4d" % trainer.totalepochs, \
          "  train error: %5.2f%%" % trnresult, \
          "  test error: %5.2f%%" % tstresult

    out = fnn.activateOnDataset(griddata)
    out = out.argmax(axis=1)  # the highest output activation gives the class
    out = out.reshape(X.shape)

    figure(1)
    ioff()  # interactive graphics off
    clf()   # clear the plot
    hold(True) # overplot on
    for c in range(n_klass):
        here, _ = where(tstdata['class']==c)
        plot(tstdata['input'][here,0],tstdata['input'][here,1],'o')
    if out.max()!=out.min():  # safety check against flat field
        contourf(X, Y, out)   # plot the contour
    ion()   # interactive graphics on
    draw()  # update the plot

rawDescription: Library in python for neural networks to plot ROC, AUC, DET


code:
l = [1,2,3,4,5,6]
for a,b in grouper(2, l):
    print a, b

rawDescription: Python equivalent of Ruby's each_slice(count)


code:
class Tracker(object):
    instances = list()
    def __init__(self):
        self.__class__.instances.append(self)
    @classmethod
    def projeny(cls):
        print "There are currently %d instances of Tracker" % len(cls.instances)
        for instance in cls.instances:
            print instance

t1 = Tracker()
t2 = Tracker()
Tracker.projeny()
t3 = Tracker()
Tracker.projeny()

rawDescription: Return all instances of one class

description: Return all instances of one class


rawDescription: Splitting a number pattern

description: Splitting a number pattern


code:
print "1: %s" % id(self.DefaultDomainName)
print "2: %s" % id(Manager.DefaultDomainName)

rawDescription: How do python classes work?

description: How do python classes work


code:
sleep = subprocess.Popen(['sleep', '60'])
sleep.wait()
print sleep.stdout  # sleep outputs nothing but...
print sleep.returncode  # you get the exit value

rawDescription: python execute shell command and continue without waiting and check if running before executing

description: Python execute shell command and continue without waiting and check if running before executing


code:
for word in words:
    for key,values in wordDict.items():
        if word in values:
            print key,word

rawDescription: understanding a selector from within a dict

description: Understanding a selector from within a dict


code:
row = df[df.apply(lambda x: (x == "date").any(), axis=1)].values[0] # will be an array
for i, val in enumerate(row):
    if val == "date":
        print row[i + 1]
        break

rawDescription: Python pandas an efficient way to see which column contains a value and use its coordinates as an offset


code:
class A(object):
  def __init__(self, flag):
    self.flag = flag

  def func(self):
    print self.flag

a = A(1)
b = A(2)

callback_a = a.func
callback_b = b.func

print "typeof(callback_a) = {0}".format(type(callback_a))
print "typeof(callback_b) = {0}".format(type(callback_b))

print "typeof(callback_a.__func__) = {0}".format(type(callback_a.__func__))
print "typeof(callback_b.__func__) = {0}".format(type(callback_b.__func__))

print "'callback_a.__func__ is callback_b.__func__'  is {0}".format(callback_a.__func__ is callback_b.__func__)

callback_a()
callback_b()

rawDescription: How does Python distinguish callback function which is a member of a class?


code:
passed = totals = 0

for strings in grade.stripped_strings:
    if "/" in strings:
        print strings
        pass_, total = map(float, strings.split('/'))
        passed += pass_
        totals += total

print "The average is: {:.1%}".format(passed / totals)

rawDescription: Analyzing cumbersome information

description: Analyzing cumbersome information


rawDescription: Python regular expression to print out sections of a string


code:
class A(B): # Inherits Class B
    def __init__(self,master):
        """Some work here"""
    def do_this(self):
        print self.do_that()[1] # This is assuming the do_that() function returns that tuple

rawDescription: using a variable from a method of another class in python

description: Using a variable from a method of another class in python


code:
for line in soup.find_all('ol'):
    result = []
    for descendant in line.li.descendants:
        if isinstance(descendant, NavigableString):
            result.append(unicode(descendant).strip())
        elif descendant.name == 'dl':
            break
    print u' '.join(result)

rawDescription: Python/BeautifulSoup - How can I extract text between <li> and <dl> tags


code:
import numpy as np
from sklearn import preprocessing
X = np.array(['cat', 'dog', 'cow', 'cat', 'cow', 'dog'])
binar = preprocessing.LabelBinarizer()
X_bin = binar.fit_transform(X)
print X_bin

rawDescription: Transforming text data in sklearn pipeline


code:
# Words with 8 distinct POS
word_with_eight_pos = filter(lambda x: len(word_tags[x]) == 8, word_tags.keys())

for i in word_with_eight_pos:
    print i, word_tags[i]
print

# Words with 9 distinct POS
word_with_nine_pos = filter(lambda x: len(word_tags[x]) == 9, word_tags.keys())

for i in word_with_nine_pos:
    print i, word_tags[i]

rawDescription: NLTK Brown Corpus Tags

description: NLTK Brown Corpus Tags


rawDescription: wx.TextCtrl is blank for very long strings

description: Wx.TextCtrl is blank for very long strings


code:
json_file = open('data.json')
dct = json.load(json_file)
print dct['data'].keys()

rawDescription: Getting limited information from JSON with Python


code:
import sys

follow = dict(line.strip().split() for line in sys.stdin)
x = set(follow).difference(follow.itervalues()).pop()
while x:
    print x
    x = follow.get(x)

rawDescription: Finding the correct path in O(n) time

description: Finding the correct path in O(n) time


code:
print d['nameb'], "met", d['nameg']
print "they met at", d['place']

rawDescription: Python- Simple random selector

description: Python- Simple random selector


code:
from itertools import chain, combinations
# powerset recipe taken from itertools documentation
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def traversals(tree):
    left, mid, right = tree.lefts[0].name, tree.name, tree.rights[0].name
    nodes = list(inorder(tree))
    l_i, m_i, r_i = [nodes.index(x) for x in (left, mid, right)]
    parts = nodes[:l_i], nodes[l_i+1:m_i], nodes[m_i+1:r_i], nodes[r_i+1:]
    psets = [powerset(x) for x in parts]
    for p1, p2, p3, p4 in product(*psets):
        yield ''.join(chain(p1, left, p2, mid, p3, right, p4))

print list(traversals(tree))
# ['bde', 'bdfe', 'bdge', 'bdfge', 'bcde', 'bcdfe',
#  'bcdge', 'bcdfge', 'abde', 'abdfe', 'abdge', 'abdfge',
#  'abcde', 'abcdfe', 'abcdge', 'abcdfge']

rawDescription: How to iterate this tree/graph

description: Iterate this tree/graph


code:
def move():
    print "disco party!"

class dance(object):
    dance_move = staticmethod(move)

d = dance()
d.dance_move()
d.break_it_down = move
d.break_it_down()

rawDescription: Assigning functions as attributes of an object, then calling without the implied 'self' arguement?


code:
import subprocess
process = subprocess.Popen('cmd /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir") #passing command
stdOutput,stdError = process.communicate()
print stdOutput
process.stdin.close()

rawDescription: how to open a cmd shell in windows and issue commands to that shell using python

description: Open a cmd shell in windows and issue commands to that shell using python


rawDescription: How to test each specific digit or character

description: Test each specific digit or character


code:
import multiprocessing as mp
import time

def multby4_wq(x):
    print "Starting!"
    time.sleep(5.0/x)
    a = x*4
    return a

if __name__ == '__main__':
    pool = mp.Pool(4)
    for result in pool.map(multby4_wq, range(1, 5)):
        print result

rawDescription: Obtain results from processes using python multiprocessing


code:
def f(x):
    var = random.randint(1, 10)
    # First version
    if var in [2, 5, 9]:
      print "First: 2, 5 or 9"

    # Second version
    if var == 2 or number == 5 or number == 9:
      print "Second: 2, 5 or 9"

import dis
dis.dis(f)

rawDescription: What version of this Python code is faster?


code:
#! /usr/bin/env python

''' A resumable implementation of SHA-256 using ctypes with the OpenSSL crypto library

    Written by PM 2Ring 2014.11.13
'''

from ctypes import *

SHA_LBLOCK = 16
SHA256_DIGEST_LENGTH = 32

class SHA256_CTX(Structure):
    _fields_ = [
        ("h", c_long * 8),
        ("Nl", c_long),
        ("Nh", c_long),
        ("data", c_long * SHA_LBLOCK),
        ("num", c_uint),
        ("md_len", c_uint)
    ]

HashBuffType = c_ubyte * SHA256_DIGEST_LENGTH

#crypto = cdll.LoadLibrary("libcrypto.so")
crypto = cdll.LoadLibrary("libeay32.dll" if os.name == "nt" else "libssl.so")

class sha256(object):
    digest_size = SHA256_DIGEST_LENGTH

    def __init__(self, datastr=None):
        self.ctx = SHA256_CTX()
        crypto.SHA256_Init(byref(self.ctx))
        if datastr:
            self.update(datastr)

    def update(self, datastr):
        crypto.SHA256_Update(byref(self.ctx), datastr, c_int(len(datastr)))

    #Clone the current context
    def _copy_ctx(self):
        ctx = SHA256_CTX()
        pointer(ctx)[0] = self.ctx
        return ctx

    def copy(self):
        other = sha256()
        other.ctx = self._copy_ctx()
        return other

    def digest(self):
        #Preserve context in case we get called before hashing is
        # really finished, since SHA256_Final() clears the SHA256_CTX
        ctx = self._copy_ctx()
        hashbuff = HashBuffType()
        crypto.SHA256_Final(hashbuff, byref(self.ctx))
        self.ctx = ctx
        return str(bytearray(hashbuff))

    def hexdigest(self):
        return self.digest().encode('hex')

#Tests
def main():
    import cPickle
    import hashlib

    data = ("Nobody expects ", "the spammish ", "imposition!")

    print "rehash\n"

    shaA = sha256(''.join(data))
    print shaA.hexdigest()
    print repr(shaA.digest())
    print "digest size =", shaA.digest_size
    print

    shaB = sha256()
    shaB.update(data[0])
    print shaB.hexdigest()

    #Test pickling
    sha_pickle = cPickle.dumps(shaB, -1)
    print "Pickle length:", len(sha_pickle)
    shaC = cPickle.loads(sha_pickle)

    shaC.update(data[1])
    print shaC.hexdigest()

    #Test copying. Note that copy can be pickled
    shaD = shaC.copy()

    shaC.update(data[2])
    print shaC.hexdigest()

    #Verify against hashlib.sha256()
    print "\nhashlib\n"

    shaD = hashlib.sha256(''.join(data))
    print shaD.hexdigest()
    print repr(shaD.digest())
    print "digest size =", shaD.digest_size
    print

    shaE = hashlib.sha256(data[0])
    print shaE.hexdigest()

    shaE.update(data[1])
    print shaE.hexdigest()

    #Test copying. Note that hashlib copy can NOT be pickled
    shaF = shaE.copy()
    shaF.update(data[2])
    print shaF.hexdigest()

if __name__ == '__main__':
    main()

rawDescription: Persisting sha256 hash objects?

description: Persisting sha256 hash objects


code:
#!/usr/bin/env python

import struct
from socket import socket, AF_UNIX, SOCK_STREAM, SOL_SOCKET

SO_PEERCRED = 17 # Pulled from /usr/include/asm-generic/socket.h

s = socket(AF_UNIX, SOCK_STREAM)

s.bind('/tmp/pass_cred')
s.listen(1)

conn, addr = s.accept()

creds = conn.getsockopt(SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i'))

pid, uid, gid = struct.unpack('3i',creds)

print 'pid: %d, uid: %d, gid %d' % (pid, uid, gid)

rawDescription: Unix socket credential passing in Python


code:
def RandomSelect(knum, rand=None):
    ''' (int, func) -> list

    Reservoir Sampling implementation
    '''
    selection = None
    k_elems_list = []
    count = 0
    if rand is None:
        rand = Random()

    while True:
        try:
            item = yield selection
        except GeneratorExit:
            break
        if len(k_elems_list) < knum:
            k_elems_list.append(item)
        else:
            # Randomly replace elements in the reservoir with a decreasing probability
            r = rand.randint(0, count)
            if r < knum:
                k_elems_list[r] = item
        count += 1
    print k_elems_list

myList = [1,2,3,4,5,6,7,8]
cr = RandomSelect(3)
cr.next() # advance to the yield statement, otherwise I can't call send
for val in myList:
    cr.send(val)
cr.close()
del cr

rawDescription: Is there better way to swallow StopIteration exception generated by yield in python?


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

sys.stdout = sys.stderr
val = raw_input("enter val: ")
sys.stdout = sys.__stdout__
print val

rawDescription: Python - how can I read stdin from shell, and send stdout to shell and file


code:
brands = ['val1', 'val2', 'val3']
infoBrands = {brand: {'nbOffers': 0, 'nbBestOffers': 0, 'higherPrice': []}
                for brand in brands}

infoBrands['val1']['nbOffers'] += 1
print infoBrands

rawDescription: Does dict.fromkeys assign the same reference over and over?


code:
lst=[{'applicationName': "ATM Monitoring",
                     'roamingDrop': "",
                     'noOfCustomer': None,
                     'ipAddress': "192.168.1.1",
                      'url': "www.google.co.in",},
         {'applicationName': None,
                     'roamingDrop': "",
                     'noOfCustomer': None,
                     'ipAddress': "192.168.1.1",
                      'url': "www.google.co.in",}]

print [{key: val if val else "" for key, val in dct.items()} for dct in lst]

rawDescription: python one liner code for two nested for loop

description: Python one liner code for two nested for loop


code:
import heapq

def print_top(filename):
    word_count = word_dictionary(filename)
    items = heapq.nlargest(word_count.items(), key=get_count)
    for item in sorted(items[:20]):
        print item[0], item[1]

rawDescription: Python trying to sort a list alphabetically after it has been sorted numerically


code:
value = "addr = &myvariable;\naddr = &myvariable;\nfuncCall( &myvariable )\nfuncCall2( &myvariable, &myvariablelongername )"
oldVarName = "myvariable"
newVarName = "mynewvariable"
m = re.sub("(\\&){0}(?![A-Za-z0-9_])".format(oldVarName), r"\1"+newVarName, value)
print m
# prints:
# addr = &mynewvariable;
# addr = &mynewvariable;
# funcCall( &mynewvariable )
# funcCall2( &mynewvariable, &myvariablelongername )

rawDescription: Regex for finding variable references in a C file using Python


code:
from pandas import DataFrame

df = DataFrame({'a': [2,4], 'b': [3,2], 'c': [2,6]})
print df

list1 = df.irow(0).values.tolist()
list2 = df.irow(1).values.tolist()

rawDescription: python datapanda: getting values from rows into list

description: Python datapanda: getting values from rows into list


code:
def parseips():
    with open("126logs.txt",'r') as f:
        for line in f:
            ip = line.split()[3]
            if ip.startswith('192.168.'):
                print "%s\n" %ip,

rawDescription: python working with files as they are written

description: Python working with files as they are written


rawDescription: How can I sum an interval of elements on an array in python / numpy?

description: Sum an interval of elements on an array in python / numpy


code:
def chosen_pokemon():
    while True: # repeat forever unless it reaches "break" or "return"
        print "What's your favourite type of pokemon?"
        fav_type = raw_input()
        if "fire" in fav_type:
             print "So you like fire types? I'll give you a chimchar!"
        elif "water" in fav_type:
             print "So you like water types? I'll give you a piplup!"
        elif "grass" in fav_type:
             print "So you like grass types? I'll give you a turtwig!"
        else:
             print "sorry, you can only choose grass, water or fire"
             continue # jumps back to the "while True:" line
        return # finished; exit the function.

chosen_pokemon()

rawDescription: looping back to specific point in code

description: Looping back to specific point in code


code:
def computeCritics(mode, cleaned_sales_input="data/cleaned_sales.csv"):
    if mode == 1:
        filename = 'customer.critics.recommendations'
        path = os.path.join("data/customer", filename)
        ID = getCustomerSet(cleaned_sales_input)
        sales_dict = pickle.load(
            open("data/customer/books.dict.recommendations", "r"))
        key_idx, other_idx = 2, 6
    else:
        filename = 'books.critics.recommendations'
        path = os.path.join("data/books", filename)
        ID = getBookSet(cleaned_sales_input)
        sales_dict = pickle.load(
            open("data/books/users.dict.recommendations", "r"))
        key_idx, other_idx = 6, 2

    print "creating {}".format(filename)
    ID = {int(item) for item in ID}
    critics = {i:sales_dict.copy() for i in ID}
    with open(path, "wb") as critics_output:
        # make critics dict and pickle it
        with open(cleaned_sales_input, 'rb') as sales_input:
            sales = csv.reader(sales_input)  # read new
            for j in sales:
                key = int(j[key_idx])
                if key in ID:
                    other_key = int(j[other_idx])
                    critics[key][other_key] = 1
                critics[key] = sales_dict
        pickle.dump(dict(critics), critics_output)
        print "done"

rawDescription: re reading a csv file in python without loading it again

description: Re reading a csv file in python without loading it again


code:
binary1, binary2 = raw_input().split(' ')
N = int(binary1, 2)
M = int(binary2, 2)
print '{}|{} makes {:b}'.format(binary1, binary2, N|M)

rawDescription: Taking a binary input from the user in python for bitwise operations


rawDescription: Python string in pure hex form

description: Python string in pure hex form


rawDescription: JSON GET Request with Python

description: JSON GET Request with Python


code:
for i,j in enumerate(tup):
 print a[:i]+[tuple(a[j[0]-1:j[1]])]+a[i+2:]

rawDescription: Combine a list of tuples and list, removing the tuple elements from the list


code:
for entry in data:
    for inning in entry['innings']:
        print inning['wickets']

rawDescription: Decoding nested JSON with multiple 'for' loops


code:
data = '''Language    Trustworthy
           en   0
           du   0
           li   0
           tm   0
           en   1
           en   0
           en   0
           en   1
           fr   0
           en   1'''

import pandas as pd
from StringIO import StringIO

df = pd.DataFrame.from_csv( StringIO(data), index_col=None, sep='\s+')

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

print df.groupby('Trustworthy').size()

'''
Trustworthy
0              7
1              3
dtype: int64
'''

rawDescription: Pandas Modify Dataset to Have Equal Values from both Classifications


code:
x = lambda x: None
def y(): pass
print y.__name__
# y
print x.__name__
# <lambda>

rawDescription: How to check that variable is a lambda function

description: Check that variable is a lambda function


code:
import email.parser
parser = email.parser.FeedParser()

email = '''\
From: Steve <steve@steve.steve>
To: Someone <someone@foo.com>
Subject: Hey what's up

This is a dummy email, no server involved.
'''

parser.feed(email)
msg = parser.close()

print "To:", msg['to']
print "From:", msg['from']
print "Subject:", msg['subject']
print "Body:", repr(msg.get_payload())

rawDescription: Python email.parser in development

description: Python email.parser in development


code:
import pandas as pd
import numpy as np
import itertools

a = pd.Series([1, 2, 3, np.nan, 4, np.nan, np.nan, np.nan, 5, np.nan, np.nan])
len_holes = [len(list(g)) for k, g in itertools.groupby(a, lambda x: np.isnan(x)) if k]
print len_holes

rawDescription: Pandas: run length of NaN holes

description: Pandas: run length of NaN holes


rawDescription: Convert string saved in hex format to its previous form in python


code:
def fast_iter(context, func, *args, **kwargs):
    # http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
    # Author: Liza Daly
    for event, elem in context:
        func(elem, *args, **kwargs)
        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

def parseXml(element,attribList,elemList):
    for child in element:
       if child.tag in elemList:
           print len(child) #for a given child,the len should be constant
           #do things

context=etree.iterparse(filehandle, events=('end',), tag=mainElement)
fast_iter(context, parseXml, attribList, elemList)

rawDescription: lxml iterparse mising child nodes

description: Lxml iterparse mising child nodes


code:
import random

def get_shuffled_list(length):
    output = range(1, length+1)
    i = 0
    sanity = 0

    while i < length and sanity == 0:
        random.shuffle(output)
        for i in range(1, length):
            sanity = length - i + 1

            while abs(output[i-1] - output[i]) <= 15 and sanity:
                output.append(output[i])
                del output[i]
                sanity -= 1

            if sanity == 0:
                break

    return output

print get_shuffled_list(50)

rawDescription: Make a list of 50 random numbers in the range 1-50, such that adjacent numbers are not within 15 of each other


code: print ax.xaxis.label.set_size.__doc__

rawDescription: How to learn Matplotlib without searching Google or Stackoverflow?

description: Learn Matplotlib without searching Google or Stackoverflow


code:
import os

path = "/home/luai/Desktop/python/test"
dirs = os.listdir( path )

print "Here is a list of all files: "

for filenumber in range(len(dirs)):
    print filenumber, dirs[filenumber]

filenumber = raw_input ("Number of file which to update: ")
filenumber = int(filenumber)

if dirs[filenumber] in dirs:
    inputFile = open(os.path.join(path, dirs[filenumber]))
    inputFile.close() #this line was at a weird place?
else:
    print "no match found"
    sys.exit()

rawDescription: Add list of files into a dictionary using python


code:
@intfactory.callback
def notify(num):
    print "notify:", num

def increment(num):
    return num+1

intfactory += increment
intfactory += lambda num: num * 2

print intfactory(3)   # outputs 8

rawDescription: What's the preferred way to implement a hook or callback in Python?


code:
import numpy as np
import pandas as pd

f = np.arange(0, 40, 5)
g = np.arange(0, 40, 10)
events = [12, 13, 27, 37]

df = pd.concat([pd.Series(f, f), pd.Series(g, g), pd.Series(events, events)], axis=1)
df.columns = "f", "g", "event"
df[["f", "g"]] = df[["f", "g"]].bfill()
df2 = df.dropna()
print df2

rawDescription: Simulating event system using pandas

description: Simulating event system using pandas


code:
source
EXAMPLE = '''
type        : FILE_CONTENT_CHECK
description : "This is a description"
info        : "Info!"
info        : ""
info        : "References:"
info            : "book1, book 2, etc"
file        : "blahblah.txt"
'''

do_print = False
for line in EXAMPLE.split('\n'):
    if ':' not in line:
        continue
    key,value = line.split(':',1)
    key = key.strip()
    value = value.strip()

    if key in ('description', 'info'):
        print value
        do_print = True
        continue
    if do_print:
        print value
        do_print = False

rawDescription: How to extract data from a file using python and output to another file

description: Extract data from a file using python and output to another file


code:
for k, v in output_dicts.iteritems():
    print k
    print v
    print

rawDescription: how to group new dictionaries by using common strings from my dictionary

description: Group new dictionaries by using common strings from my dictionary


code:
str = "Peer 10.11.6.224 is currently trusted in the white list, but it is now using a new trusted certificate. Consider removing its likely outdated white list entry."
m = compiled.match(str)
print m.groupdict()

rawDescription: How to extract a word from text in Python

description: Extract a word from text in Python


code:
import sys

def f1(): print "1"
def f2(): print "2"
def f3(): print "3"

for fname in sys.argv[1:]:
    globals()[fname]()

rawDescription: Using arguments to to run functions

description: Using arguments to to run functions


code:
import csv
with open('csv.csv') as text:
    table = list(csv.reader(text))

# get all dates (skipping first and last column)
dates = table[0][1:-1]

# get all shows (skipping first and last column and empty rows)
shows =  filter(''.join, (t[1:-1] for t in table[1:]))

# join dates and shows back together and do some formatting
for line in [zip(dates, s) for s in shows]:
    print ', '.join('{}, "{}"'.format(*t) for t in line)

rawDescription: Python regex on csv file

description: Python regex on csv file


code: print trial.prod

rawDescription: How to create a simple function within a class in Python?

description: Create a simple function within a class in Python


code:
last_row = 0
while True:
    if cell_value is not None:  # replace cell_value with however
                                # xlwings accesses a cell's value
       last_row += 1
    else:
        break

print last_row

rawDescription: Count rows in excel sheet in Python with xlwings


code:
for v in Vendor.objects.raw('SELECT ... ', [category]): # query as above
    print 'Vendor {0} has rating {1}'.format(v.name, v.rating)

rawDescription: Django filter with annotate

description: Django filter with annotate


code:
def open_spider(self, spider):
    print spider.user_id

rawDescription: Using arguments in scrapy pipeline on __init__


code:
for k, v in d.iteritems():
    print "{} {}".format(k,v)

rawDescription: Python List To Dictionary - Without Value Overwrite


code:
import os
import re

root = 'c:\users'
pattern = re.compile("((keyword1)|(keyword2))\.((txt)|(jpg))")

for path, subdirs, files in os.walk(root):
    for name in files:
        if re.match(pattern, name):
            print os.path.join(name)

rawDescription: Python file searching trouble

description: Python file searching trouble


code:
def palette_pseudocolor(val, minval, maxval, palette):
    max_index = len(palette)-1
    # convert val in range minval...maxval to range 0..max_index
    v = (float(val-minval) / (maxval-minval)) * max_index
    # split result into integer and fractional parts
    i = int(v); f = v-i
    # interpolate between two colors in the palette
    c0, c1 = palette[i], palette[min(i+1, max_index)]
    d = c1[0]-c0[0], c1[1]-c0[1], c1[2]-c0[2]
    return c0[0]+f*d[0], c0[1]+f*d[1], c0[2]+f*d[2]

if __name__ == '__main__':
    numsteps = 10
    palette = [(1,0,0), (0,1,0), (0,0,1)] # [RED, GREEN, BLUE]
    print 'val       R      G      B'
    for val in xrange(0, 100+numsteps, numsteps):
        print ('%3d -> (%.3f, %.3f, %.3f)' %
               ((val,) + palette_pseudocolor(val, 0, 100, palette)))

rawDescription: Mandelbrot-algorithm - Background color

description: Mandelbrot-algorithm - Background color


rawDescription: Perform simple math on regular expression output? (Python)


code:
a = 1
b = 2
c = a + b

print "test %d" %c

rawDescription: Python Script on Kali Linux

description: Python Script on Kali Linux


code:
print common
len(common)

rawDescription: Python - Comparing two lists of sets

description: Python - Comparing two lists of sets


code:
import re

results = []
for element in dir(re):
    m = re.match("(find\w+)", element)
    if m:
        results.append(m.group(1))

print sorted(results)

rawDescription: learnpython.org modules exercise

description: Learnpython.org modules exercise


code:
class myBase(object):
    def __init__(self, name, iteratedValue):
        self.name = name
        iteratedValue = iteratedValue
    def __str__(self):
        return self.name

class myIterator(object):
    def __init__(self):
        self.k = 0
    def __call__(self, s):
        self.k += 1
        name = 'myData' + str(self.k)
        self.name = myBase(name, s)
        print '%s name is %s for k = %i' % (self.name, self.name.iteratedValue, self.k)

        # return object named myData1 type of myBase
        return self.name

rawDescription: assigning an object's name taken from expression

description: Assigning an object's name taken from expression


rawDescription: Python, reading lines from a file one by one


code:
hasE = False
for letter in word:
    if letter == 'e':
        hasE = True
        break
if not hasE: print word

rawDescription: has_no_e() exercise from Think Python

description: Has_no_e() exercise from Think Python


code:
l = "hello, hello, what's all this shouting? We'll have no trouble here"
for tok in tokenizer(l):
    print tok

rawDescription: Python Tokenization

description: Python Tokenization


code:
nu = app('Numbers')
for sheet in nu.documents.first.sheets():
  for table in sheet.tables():
    if table.selection_range():
       print table.name()

rawDescription: Getting the Current Table in Numbers (Python/Appscript)


code:
from collections import Counter

letters = ['v','r','o','o','m','a','b','c','d']
words = 'cardboard boom booom'.split()
letterscount = Counter(letters)

for word in words:
    wordcount = Counter(word)
    print word, all(letterscount[c] >= wordcount[c] for c in wordcount)

rawDescription: Python- Possible English one-word anagrams given input letters


code: print "".join([str(i) for i in range(1,int(raw_input())+1)])

rawDescription: Single line statement to print range of numbers on a single line


code:
for i, j in zip(bounding_time, v):
    print i[0] + '    ' + j[0]

rawDescription: Python list in list formatting the output


code:
print 'AAA' if True else 'BBB' + 'CCC' if True else 'DDD'
print 'AAA' if False else 'BBB' + 'CCC' if True else 'DDD'
print ('AAA' if True else 'BBB') + ('CCC' if True else 'DDD')

rawDescription: A issue of concatenating two strings with if...else statement


code:
def list_duplicates(seq):
    seen = set()
    seen_add = seen.add
    return [idx for idx,item in enumerate(seq) if item in seen or seen_add(item)]

print list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5])
# [3, 4, 7, 8, 9]

rawDescription: List indexes of duplicate values in a list with Python


code:
import re

my_macs = ['00:14:5e:6b:4b:ea','00:14:5e:6b:4b:eb','00:14:5e:6b:4b:ec']
mac = ''

strToFind = re.compile(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', re.I)

for line in output.split('\n'):
    results = re.search(strToFind, line)
    if results:
        mac = results.group()
    if mac not in my_macs:
        print mac

rawDescription: Python mac adress matching and processing


rawDescription: Python Elementtree access children through attribute value


code:
import urllib2
from xml.etree import cElementTree as ET
conn = urllib2.urlopen("http://www.codespot.blogspot.in/atom.xml?redirect=false&start-index=1&max-results=500")
myins=ET.parse(conn)
for elem in myins.findall('{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title'):
    print elem.text

rawDescription: Error while parsing xml in Python

description: Error while parsing xml in Python


code:
class myParent( object ):
    def __init__( self, parentId ):
        self.id = parentId
        self.children = []

    def createChild( self, name ):
        self.children.append( myChild( name, self ) )

    def getChildren( self ):
        return self.children

class myChild( object ):
    def __init__( self, childId, parent ):
        self.id = childId
        self.parent = parent

    def getParentId( self ):
        return self.parent.id

p = myParent( 'parent01' )
p.createChild( 'child01' )
print p.getChildren()[0].getParentId()

rawDescription: Python: Getting baseclass values from derived class


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

    Text with whitespace

No whitespace

''')
for p in soup.find_all('p'):
    if p.string:
        p.string.replace_with(p.string.strip())

print str(soup)

rawDescription: Remove empty spaces inside <p> tags using BeautifulSoup


code:
import re

names = ['Chris', 'Jack', 'Kim']
target = ['Chris Smith', 'I hijacked this thread', 'Kim','Christmas is here', 'CHRIS']

regex_string = '|'.join(r"(?:\b"+re.escape(x)+r"\b)" for x in names)
print regex_string
regex = re.compile(regex_string,re.I)
print [t for t in target if regex.search(t)]

rawDescription: What's a more efficient way of looping with regex?


code:
def getSignedNumber(number, bitLength):
    mask = (2 ** bitLength) - 1
    if number & (1 << (bitLength - 1)):
        return number | ~mask
    else:
        return number & mask

print iv, '->', getSignedNumber(iv, 32)

rawDescription: How to create or interpret custom data type (4bit signed)

description: Create or interpret custom data type (4bit signed)


code:
x = np.arange(4)
y = np.arange(10, 14)
d = [[0,0],[0,1],[1,1],[1,0]]  # define order to go around rectangle here

for ix in range(len(x) - 1):
    for iy in range(len(y) - 1):
        print [(x[ix + dx], y[iy + dy]) for dx, dy in d]

rawDescription: Gridding a numpy array

description: Gridding a numpy array


code:
# The raw_data DF
df1 = pd.DataFrame({'raw_data': ['Lorem', 'ipsum', 'dolor', 'sit', 'amet,',
                                 'consectetur', 'adipiscing', 'elit']})
print 'Original:'
print df1

# The replacement patterns DF
df2 = pd.DataFrame({'replacethis': ['ipsum', 'it'], 'withthis': ['doggy', 'THAT']})
pattern_dict = df2.set_index('replacethis')['withthis'].to_dict()

df1_replaced = df1.replace(pattern_dict, regex=True)
print '\nAfter Replacement:'
print df1_replaced

rawDescription: Replace dataframe entries with another dataframe (series?) entry? vectorize? compression?


rawDescription: Python - Homework - Converting Any Base to Any Base


code:
Counts = dict(x=5, y=10)

def func1():
    Counts['x'] += 1
    Counts['y'] += 1
    print Counts['x'], Counts['y']

def func2():
    while True:
        func1()

func2()

rawDescription: python run code that is in a function once

description: Python run code that is in a function once


code:
from BeautifulSoup import BeautifulSoup
def get_tags_set(source):
    soup = BeautifulSoup(source)
    all_tags = soup.findAll(True)
    return set([tag.name for tag in all_tags])

def verify(tags_source_orig, tags_source_to_verify):
    return tags_source_orig == set.intersection(tags_source_orig, tags_source_to_verify)

source= 'What\'s your nameWhat\'s your nameHello'
source_to_verify= 'HelloWhat\'s your nameWhat\'s your name'
print verify(get_tags_set(source),get_tags_set(source_to_verify))

rawDescription: Match HTML tags in two strings using regex in Python


code:
iwant=s.rsplit("-",1)
if iwant[-1].isdigit():
  print iwant[0]

rawDescription: Remove final slash and number in a string in Python


code:
width = 6
height = 4
xs = range(1,25)
w = 3
h = 2

def subrect(x,y):
    pos = y*h*width+x*w
    return [xs[(pos+row*width):(pos+row*width+w)] for row in range(h)]

print [subrect(x,y) for y in range(height / h) for x in range(width / w)]

rawDescription: Slicing python lists

description: Slicing python lists


code:
from copy import deepcopy
b = deepcopy(a)
b[0][2] = 'change a'
print a

rawDescription: Create a copy of the list not referencing the contained objects


code:
raw_data = [c for c in 'abcdaebfc']

seen = set()
def some_function(s):
    seen.add(s)
    return s

print [ some_function(s) for s in raw_data if s not in seen ]
# ['a', 'b', 'c', 'd', 'e', 'f']

rawDescription: LIst Comprehensions: References to the Components


code:
class Calc:
    def __init__(self):
        print self.__class__
    def add(self,a,b):
        return a + b

class Client:
    def __init__(self):
        self.calc = Calc()
    def add(self,a,b):
        return self.calc.add(a,b)

rawDescription: mock.patch does not work properly

description: Mock.patch does not work properly


code:
bad_chars = {u"\n": u" ", u"\b": u" ", u"\f": u" ", u"\r": u" ", u"\t": u" ", u"\v": u" ", u"\x00": u" "}
bad_chars_table = dict((ord(k), v) for k, v in bad_chars.iteritems())
translator = lambda s: s.translate(bad_chars_table)
print translator(u"here\nwe\tgo")

rawDescription: implementing multiple string replace() using lambda function

description: Implementing multiple string replace() using lambda function


code:
import re
with open('abc') as f:
    for line in f:
        if line.startswith('Key'):
            keys = re.search(r'Key\s+(.*)',line).group(1).split("\t")
        elif line.startswith(('Word','Letter')):
            vals = re.search(r'(Word|Letter)\s+(.*)',line).group(2).split("\t")

    print dict(zip(keys,vals))

rawDescription: Reading data from specially formatted text file


code:
#!/usr/bin/python
""" Prototype code for the infusion pump
code has to be updated """

""" Imports """
import sys
from PyQt4 import QtGui, QtCore
import sys, time
from PyQt4.QtCore import QSize, SIGNAL, pyqtSignal

""" Globals """
global topTxt, midTxt, endTxt
global powerOpt, AlrmSil, bootC
global btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9
global btn0,btnDot,btnBK,btnClr,btnMain,btnChg,btnOpt,btnClrTot,btnPWR,btnAlrm,btnStrt,btnStop
global highVal, lowVal

highVal = 55
lowVal = 10
""" Globals Initialization"""
powerOpt = 0
AlrmSil = 0
class Infusion(QtGui.QMainWindow):
    sigTextButtonClicked = pyqtSignal(QtCore.QString)

    def __init__(self):
        """ Constructor """
        super(Infusion, self).__init__()
        self.initKey()
        self.initText()
        self.showUI()

    def initKey(self):
        """   This function initializes the buttons in the UI """
        global btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9
        global btn0,btnDot,btnBK,btnClr,btnMain,btnChg,btnOpt,btnClrTot,btnPWR,btnAlrm,btnStrt,btnStop
        btn1 = QtGui.QPushButton("1", self)
        btn1.setFixedWidth(30)
        btn1.move(650, 50)
        btn1.setEnabled(False)

        btn2 = QtGui.QPushButton("2", self)
        btn2.setFixedWidth(30)
        btn2.move(690, 50)
        btn2.setEnabled(False)

        btn3 = QtGui.QPushButton("3", self)
        btn3.setFixedWidth(30)
        btn3.move(730, 50)

        btn4 = QtGui.QPushButton("4", self)
        btn4.setFixedWidth(30)
        btn4.move(650, 100)

        btn5 = QtGui.QPushButton("5", self)
        btn5.setFixedWidth(30)
        btn5.move(690, 100)

        btn6 = QtGui.QPushButton("6", self)
        btn6.setFixedWidth(30)
        btn6.move(730, 100)

        btn7 = QtGui.QPushButton("7", self)
        btn7.setFixedWidth(30)
        btn7.move(650, 150)

        btn8 = QtGui.QPushButton("8", self)
        btn8.setFixedWidth(30)
        btn8.move(690, 150)

        btn9 = QtGui.QPushButton("9", self)
        btn9.setFixedWidth(30)
        btn9.move(730, 150)

        btnBK = QtGui.QPushButton("Back", self)
        btnBK.setFixedWidth(40)
        btnBK.move(650, 200)

        btn0 = QtGui.QPushButton("0", self)
        btn0.setFixedWidth(30)
        btn0.move(690, 200)

        btnDot = QtGui.QPushButton(".", self)
        btnDot.setFixedWidth(30)
        btnDot.move(730, 200)

        btnMain = QtGui.QPushButton("", self)
        btnMain.setFixedWidth(70)
        btnMain.move(60, 230)

        btn3.clicked.connect(self.digitClicked)
        btn4.clicked.connect(self.digitClicked)
        btn5.clicked.connect(self.digitClicked)
        btn6.clicked.connect(self.digitClicked)
        btn7.clicked.connect(self.digitClicked)
        btn8.clicked.connect(self.digitClicked)
        btn9.clicked.connect(self.digitClicked)
        btn0.clicked.connect(self.digitClicked)

        btnDot.clicked.connect(self.digitClicked)
        btnBK.clicked.connect(self.digitClicked)
        # btnClr.clicked.connect(self.digitClicked)

        btnMain.clicked.connect(self.mainMenuClk)

        self.update()
    def initText(self):
        """ This portion initializes the Display of the UI, which is in black and green color """
        global topTxt, midTxt, endTxt

        midTxt = QtGui.QTextEdit("", self)
        midTxt.setFixedWidth(550)
        midTxt.setFixedHeight(100)
        midTxt.setReadOnly(True)
        midTxt.setStyleSheet('QTextEdit {background-color: #00FF00; color: black;}')
        midTxt.move(50, 80)
        midTxt.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

    def showUI(self):
        """ everything initialized , now just show it """
        self.statusBar()
        self.setGeometry(300, 300, 800, 300)
        self.setWindowTitle('InfusionUI')
        self.show()

    def digitClicked(self):
        sender = self.sender()
        self.sigTextButtonClicked.emit(sender.text())
        print sender.text()

    def alignSecScreen(self,scrn, numScreen):
        global topTxt, midTxt, endTxt, btn1
        if numScreen == 2:
            midCsr = scrn.textCursor()
            midCsr.movePosition(QtGui.QTextCursor.End)
            self.midTxtInsert( 4 * ("\t"),8, "")

        elif numScreen == 3:
            midCsr = scrn.textCursor()
            midCsr.movePosition(QtGui.QTextCursor.End)
            self.midTxtInsert( 3 * ("\t"),8, "")

        elif numScreen == 4:
            midCsr = scrn.textCursor()
            midCsr.movePosition(QtGui.QTextCursor.End)
            self.midTxtInsert( 2 * ("\t"),8, "")
        else:
            pass

    def mainMenuClk(self):
        """ Option 1 selection handler """
        global topTxt, midTxt, endTxt, btn1
        # topTxt.clear()
        midTxt.clear()
        # endTxt.clear()
        selection = 1
        self.midTxtInsert("\nMax:", 10, "")
        self.alignSecScreen(midTxt,2)
        self.midTxtInsert("59\n", 10, "")

        self.midTxtInsert("High:", 10, "")
        self.alignSecScreen(midTxt,2)
        self.midTxtInsert("%s\n"%highVal, 10, "")

        self.midTxtInsert("Low:\n", 10, "")

        self.midTxtInsert("Min:\n", 10, "")

        if(selection):
            sender = self.sender()
            selectionTxt = QtGui.QTextEdit("", self)
            selectionTxt.setFixedWidth(50)
            selectionTxt.setFixedHeight(30)
            # selectionTxt.setReadOnly(True)
            selectionTxt.setStyleSheet('QTextEdit {background-color: #000000; color: green;}')
            selectionTxt.move(500, 125)
            selectionTxt.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
            selectionTxt.show()
            selectionTxt.setAlignment(QtCore.Qt.AlignCenter)

            cursor = selectionTxt.textCursor()
            textSelected = cursor.selectedText()
            # s = textSelected.upper()
            print textSelected
            selectionTxt.setText(textSelected)

            self.sigTextButtonClicked.connect(selectionTxt.setText)
            selectionTxt.update()
            self.update()

    def midTxtInsert(self, txt,font, algmt):
        """ UI is split to three region, this is mid part which is in green """
        global topTxt, midTxt, endTxt
        midTxt.setFontPointSize(font)
        if algmt.upper() == "C":
            midTxt.setAlignment(QtCore.Qt.AlignCenter)
        elif algmt.upper() == "R":
            midTxt.setAlignment(QtCore.Qt.AlignRight)
        else:
            midTxt.setAlignment(QtCore.Qt.AlignLeft)
        midTxt.insertPlainText(txt)
        self.update()

def main():
    """ Function main """
    app = QtGui.QApplication(sys.argv)
    ex = Infusion()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How to show the number pressed on a virtual keyboard in a QTextEdit box PYQT

description: Show the number pressed on a virtual keyboard in a QTextEdit box PYQT


code:
from BeautifulSoup import BeautifulSoup

s = urllib2.urlopen('http://stackoverflow.com/questions/10614974/how-to-get-post-and-get-parameters-from-web-page-in-python').read()
soup = BeautifulSoup(s)

forms = soup.findall('form')
for form in forms:
  print 'form action: %s (%s)' % (form['action'], form['method'])
  inputs = form.findAll('input')
  for input in inputs:
    print "  -> %s" % (input.attrs)

rawDescription: How to get POST and GET parameters from Web Page in python

description: Get POST and GET parameters from Web Page in python


code:
from itertools import izip_longest, chain, combinations
for a, b, c, d in izip_longest(*[chain(*combinations(range(4), 2))]*4):
    print a, b, c, d

rawDescription: How to use a bundling/packetizing generator in Python?

description: Use a bundling/packetizing generator in Python


code:
files_read = cfgparserobj.read(['/etc/config1.ini',
                                os.path.expanduser('~/.config1.ini')])
for fname in files_read:
    print "Reading config from", fname

rawDescription: Packaging Python applications with configuration files


code:
#!/usr/bin/env python2

class ParentMeta(type):
    def __new__(meta, name, bases, dct):
        dct['store'] = dict()
        return super(ParentMeta, meta).__new__(meta, name, bases, dct)

class Parent(object):
    __metaclass__ = ParentMeta

class ChildA(Parent):
    pass

class ChildB(Parent):
   pass

ChildA.store['key1'] = 'val'
ChildB.store['key2'] = 'val'

print ChildB.store['key1'] == ChildA.store['key2']

rawDescription: Python inherited type variables

description: Python inherited type variables


code:
regex = re.compile(regexstring)
dir1 = "path_to_dir/file.dat"
dir2 =   "path_to_dir2/file.dat"
import fileinput
import os

for line in  fileinput.input([dir1,dir2]): # pass all files to check
    if regex.search(line):
        params = line.split()
        dalt = int(params[1])
        break # found it so leave the loop
    print(dalt)
else: # if we get here no file had what we want
    print "Not found, giving"

rawDescription: Searching multiple files to define variable


code: print max(d, key=d.get)

rawDescription: Print the key of the max value in a dictionary the pythonic way


rawDescription: Formatting numbers consistently in Python


code:
def solve(d, target, total, keys, avoid):
  if total <= target:     # omit this check if values can be negative
    if keys:
      k = keys[0]
      for v in d[k]:
        if not (v in avoid):
          for s in solve(d, target, total+v, keys[1:], avoid.union([v]) ):
            yield s + [(k,v)]
    elif target == total:
      yield []

def test1():
  d = {'a':(1,2,3), 'b':(4,5), 'c':(1,3,5) }
  for s in solve(d, 10, 0, "abc", set([])):
    print s

def test2():
  d = {'a':(1,2,3), 'b':(1,2,3), 'c':(1,2,3) }
  for s in solve(d, 6, 0, "abc", set([])):
    print s

rawDescription: Calculate permutations

description: Calculate permutations


code: print struct.unpack("<llll",f.read(16))

rawDescription: Start at offset from beginning of file and unpack 4 byte word


code:
if i.startswith("'") and i.endswith("'") and len(i) > 1:
    print "found"

rawDescription: Python find string enclosed in single quotes


code:
import contextlib
import timeit

def work_pass():
    pass

def work_fail():
    1/0

def simple_catch(fn):
    try:
        fn()
    except Exception:
        pass

@contextlib.contextmanager
def catch_context():
    try:
        yield
    except Exception:
        pass

def with_catch(fn):
    with catch_context():
        fn()

class ManualCatchContext(object):
    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        return True

def manual_with_catch(fn):
    with ManualCatchContext():
        fn()

preinstantiated_manual_catch_context = ManualCatchContext()
def manual_with_catch_cache(fn):
    with preinstantiated_manual_catch_context:
        fn()

setup = 'from __main__ import simple_catch, work_pass, work_fail, with_catch, manual_with_catch, manual_with_catch_cache'
commands = [
    'simple_catch(work_pass)',
    'simple_catch(work_fail)',
    'with_catch(work_pass)',
    'with_catch(work_fail)',
    'manual_with_catch(work_pass)',
    'manual_with_catch(work_fail)',
    'manual_with_catch_cache(work_pass)',
    'manual_with_catch_cache(work_fail)',
    ]
for c in commands:
    print c, ': ', timeit.timeit(c, setup)

rawDescription: Why the staggering overhead [50X] of contextlib and the With statement in Python and what to do about it


code:
class test:
    def quicktest(params):
         pprint(params)

if __name__ == '__main__':
    if sys.argv[1] == "quicktest":
        testObj = test()
        testObj.quicktest(sys.argv)
    else:
        print "Wrong call."

rawDescription: Access function from within scripts and from commandline


code:
import re

def get_matcher(word, minchars):
    reg = '|'.join([word[0:i] for i in range(len(word), minchars - 1, -1)])
    return re.compile('(%s)$' % (reg))

matcher = get_matcher('potato', 4)
for s in ["this is a sentence about a potato", "this is a sentence about a potat", "this is another sentence about a pota"]:
    print matcher.search(s).groups()

rawDescription: Regex? Match part of or whole word

description: Regex? Match part of or whole word


code:
#!/usr/bin/python
print "Content-type: text/html\r\n\r\n"
print ""
print "<title>CGI Test</title>"
print ""
print "
Test page using Python
"
print ""

rawDescription: Web Python Question

description: Web Python Question


code:
import numpy as np

def f(k):
    return(np.log(k**2))

N=8
k = np.array(range(1, N+1))
print np.sum(f(k))

rawDescription: Filling a numpy array using an arbitrary function


code:
var1 = 256  # A plain integer
var2 = 4294967296L # Bigger than 2**31, it has to be prefixed with an L

rawDescription: U8,U16,U32 representation in python

description: U8,U16,U32 representation in python


code:
import re

# the regular expression treats newlines as a regular character, so the
# multiline entries are okay. It's non-greedy, so it gets individual entries.
pat = re.compile(r'&CRB(.+?)&END',  re.DOTALL)

s = ''' &CRB  A='test1'   B=123,345, 678   &END
Misc text potentially between entries ...
&CRB  A='test2'
             B=788, 345, 3424   &END
&CRB  A='test3'
             B=788, 345, 3424   &END
&CRB  A='test4' B=788, 345, 3424   &END'''

for entry in pat.findall(s):
   # do something with each entry
   print entry

rawDescription: Best way to iterate through entries delimited by two keywords?

description: Iterate through entries delimited by two keywords


code:
INTP = ctypes.POINTER(ctypes.c_int)
num = ctypes.c_int(42)
addr = ctypes.addressof(num)
print 'address:', addr, type(addr)
ptr = ctypes.cast(addr, INTP)
print 'pointer:', ptr
print 'value:', ptr[0]

rawDescription: ctypes: construct pointer from arbitrary integer

description: Ctypes: construct pointer from arbitrary integer


code:
filename = 'data.txt'
lines = [line.strip() for line in open(filename)]
for row in lines:
    columns = row.split(',')
    print ' '.join(columns)

rawDescription: How to split string into collumn

description: Split string into collumn


code:
def identify_events(seq):
    result = []
    for i in range(len(seq)-1):
        current = seq[i]
        next = seq[i+1]
        if abs(current - next) > 20:
            result.append(1)
        else:
            result.append(0)
    return result

d = {
    'pikachu':[200,50,40,60,70] ,
    'raichu':[40 ,30,20,10,140]
}

output = {key: identify_events(value) for key, value in d.iteritems()}

print output

rawDescription: List within a Dictionary as Value in <Key-Value> Pair


code:
allzeniths, allazimuths = zip(*itertools.product(zeniths, azimuths))

print allzeniths
# (1, 1, 2, 2, 3, 3)
print allazimuths
# (6, 7, 6, 7, 6, 7)

rawDescription: Parallelise nested for-loop in IPython

description: Parallelise nested for-loop in IPython


code:
import random
def a():
    print "a"
def b():
    print "b"
random.choice([a,b])()
random.choice([a,b])()

rawDescription: Execute a function randomly

description: Execute a function randomly


code:
import sys, operator

def tokenize(s, glen):
  g2 = set()
  for i in xrange(len(s)-(glen-1)):
    g2.add(s[i:i+glen])
  return g2

def dice_grams(g1, g2): return (2.0*len(g1 & g2)) / (len(g1)+len(g2))

def dice(n, s1, s2): return dice_grams(tokenize(s1, n), tokenize(s2, n))

def main():
  GRAM_LEN = 4
  scores = {}
  for i in xrange(1,len(sys.argv)):
    for j in xrange(i+1, len(sys.argv)):
      s1 = sys.argv[i]
      s2 = sys.argv[j]
      score = dice(GRAM_LEN, s1, s2)
      scores[s1+":"+s2] = score
  for item in sorted(scores.iteritems(), key=operator.itemgetter(1)):
    print item

rawDescription: Grouping Similar Strings

description: Grouping Similar Strings


code:
if any(x for x in NL if x < sc.NLayer):
    print 'true'
else:
    print 'false'

rawDescription: else block never executes

description: Else block never executes


code:
# extracting_nested_tars.py

import os
import re
import tarfile

file_extensions = ('tar', 'tgz')
# Edit this according to the archive types you want to extract. Keep in
# mind that these should be extractable by the tarfile module.

def FileExtension(file_name):
    """Return the file extension of file

    'file' should be a string. It can be either the full path of
    the file or just its name (or any string as long it contains
    the file extension.)

    Examples:
    input (file) -->  'abc.tar'
    return value -->  'tar'

    """
    match = re.compile(r"^.*[.](?P<ext>\w+)$",
      re.VERBOSE|re.IGNORECASE).match(file_name)

    if match:           # if match != None:
        ext = match.group('ext')
        return ext
    else:
        return ''       # there is no file extension to file_name

def AppropriateFolderName(folder_name, parent_fullpath):
    """Return a folder name such that it can be safely created in
    parent_fullpath without replacing any existing folder in it.

    Check if a folder named folder_name exists in parent_fullpath. If no,
    return folder_name (without changing, because it can be safely created
    without replacing any already existing folder). If yes, append an
    appropriate number to the folder_name such that this new folder_name
    can be safely created in the folder parent_fullpath.

    Examples:
    folder_name = 'untitled folder'
    return value = 'untitled folder' (if no such folder already exists
                                      in parent_fullpath.)

    folder_name = 'untitled folder'
    return value = 'untitled folder 1' (if a folder named 'untitled folder'
                                        already exists but no folder named
                                        'untitled folder 1' exists in
                                        parent_fullpath.)

    folder_name = 'untitled folder'
    return value = 'untitled folder 2' (if folders named 'untitled folder'
                                        and 'untitled folder 1' both
                                        already exist but no folder named
                                        'untitled folder 2' exists in
                                        parent_fullpath.)

    """
    if os.path.exists(os.path.join(parent_fullpath,folder_name)):
        match = re.compile(r'^(?P<name>.*)[ ](?P<num>\d+)$').match(folder_name)
        if match:                           # if match != None:
            name = match.group('name')
            number = match.group('num')
            new_folder_name = '%s %d' %(name, int(number)+1)
            return AppropriateFolderName(new_folder_name,
                                         parent_fullpath)
            # Recursively call itself so that it can be check whether a
            # folder named new_folder_name already exists in parent_fullpath
            # or not.
        else:
            new_folder_name = '%s 1' %folder_name
            return AppropriateFolderName(new_folder_name, parent_fullpath)
            # Recursively call itself so that it can be check whether a
            # folder named new_folder_name already exists in parent_fullpath
            # or not.
    else:
        return folder_name

def Extract(tarfile_fullpath, delete_tar_file=True):
    """Extract the tarfile_fullpath to an appropriate* folder of the same
    name as the tar file (without an extension) and return the path
    of this folder.

    If delete_tar_file is True, it will delete the tar file after
    its extraction; if False, it won`t. Default value is True as you
    would normally want to delete the (nested) tar files after
    extraction. Pass a False, if you don`t want to delete the
    tar file (after its extraction) you are passing.

    """
    tarfile_name = os.path.basename(tarfile_fullpath)
    parent_dir = os.path.dirname(tarfile_fullpath)

    extract_folder_name = AppropriateFolderName(tarfile_name[:\
    -1*len(FileExtension(tarfile_name))-1], parent_dir)
    # (the slicing is to remove the extension (.tar) from the file name.)
    # Get a folder name (from the function AppropriateFolderName)
    # in which the contents of the tar file can be extracted,
    # so that it doesn't replace an already existing folder.
    extract_folder_fullpath = os.path.join(parent_dir,
    extract_folder_name)
    # The full path to this new folder.

    try:
        tar = tarfile.open(tarfile_fullpath)
        tar.extractall(extract_folder_fullpath)
        tar.close()
        if delete_tar_file:
            os.remove(tarfile_fullpath)
        return extract_folder_name
    except Exception as e:
        # Exceptions can occur while opening a damaged tar file.
        print 'Error occured while extracting %s\n'\
        'Reason: %s' %(tarfile_fullpath, e)
        return

def WalkTreeAndExtract(parent_dir):
    """Recursively descend the directory tree rooted at parent_dir
    and extract each tar file on the way down (recursively).
    """
    try:
        dir_contents = os.listdir(parent_dir)
    except OSError as e:
        # Exception can occur if trying to open some folder whose
        # permissions this program does not have.
        print 'Error occured. Could not open folder %s\n'\
        'Reason: %s' %(parent_dir, e)
        return

    for content in dir_contents:
        content_fullpath = os.path.join(parent_dir, content)
        if os.path.isdir(content_fullpath):
            # If content is a folder, walk it down completely.
            WalkTreeAndExtract(content_fullpath)
        elif os.path.isfile(content_fullpath):
            # If content is a file, check if it is a tar file.
            # If so, extract its contents to a new folder.
            if FileExtension(content_fullpath) in file_extensions:
                extract_folder_name = Extract(content_fullpath)
                if extract_folder_name:     # if extract_folder_name != None:
                    dir_contents.append(extract_folder_name)
                    # Append the newly extracted folder to dir_contents
                    # so that it can be later searched for more tar files
                    # to extract.
        else:
            # Unknown file type.
            print 'Skipping %s. <Neither file nor folder>' % content_fullpath

if __name__ == '__main__':
    tarfile_fullpath = 'fullpath_path_of_your_tarfile'    # pass the path of your tar file here.
    extract_folder_name = Extract(tarfile_fullpath, False)

    # tarfile_fullpath is extracted to extract_folder_name. Now descend
    # down its directory structure and extract all other tar files
    # (recursively).
    extract_folder_fullpath = os.path.join(os.path.dirname(tarfile_fullpath),
      extract_folder_name)
    WalkTreeAndExtract(extract_folder_fullpath)
    # If you want to extract all tar files in a dir, just execute the above
    # line and nothing else.

rawDescription: Extracting compressed files

description: Extracting compressed files


code:
def p(x): print x
drill(p, 3, 4)

rawDescription: Undetermined number of for loops depending on one parameter


rawDescription: Dynamically Build Dictionary From Different Lists


code:
print compose([(1,2,3)], True)
print compose([(1,2,3)], False)

rawDescription: Python: compose list from nested iterators


code:
searchstringsProblem = 'BIG Problem Line'
searchstringsGPSLoc = 'GPS INFO'
matches = []

with open("test.txt") as f:
    problem = False
    problem_line = ""

    for line in f:
        if not problem and searchstringsProblem in line:
            problem_line = line.strip()
            problem = True
        elif problem and searchstringsGPSLoc in line:
            matches.append((problem_line, line.strip()))
            problem = False

print matches

rawDescription: Using Python to run nested string searches


code:
Example
query = "tom OR jerry AND dan"
print query_in_string(query, "cartoon jerry")   # -> False no dan or tom
print query_in_string(query, "tom is happy")    # -> True tom
print query_in_string(query, "dan likes jerry") # -> True jerry and dan

rawDescription: Determining if a query is in a string

description: Determining if a query is in a string


code:
parser.add_argument('-w', action='store_true')
parser.add_argument('-c', action='store_true')
parser.add_argument('-l', action='store_true')
parser.add_argument('filename')
args = parser.parse_args()

if os.path.exists(args.filename):
    print word_count(args.filename), line_count(args.filename), character_count(args.filename)
else:
   print "There is no such file"

rawDescription: How to implement command line switches to my script?

description: Implement command line switches to my script


code: print '\n'.join(a[:3])

rawDescription: Python: loop through list item x times?

description: Python: loop through list item x times


code:
def add_and_print(x):
   print x
   return x + 1

fp_while(lambda x: x < 5, add_and_print, 1)

rawDescription: Functional programming - for and while loops


code:
from random import randrange

DIE_CHOICES = {4, 6, 12}

def roll(choices):
    while True:
        try:
            choice = int(input('Would you like to use a 4, 6 or 12 sided die?\n'))
        except ValueError:
            continue
        if roll in choices:
            return choice, 1 + randrange(choice)
        else:
            print 'Please pick a legal die size.\n'

print 'Your {} sided die rolled a {}.'.format(roll(DIE_CHOICES))

rawDescription: Not quite sure what's happening when using "or" in python


code:
wordlist = ['hello', 'bye']
hand = ""

while any(item.startswith(hand) for item in wordlist):
    hand += raw_input('enter letter: ')
print 'you loose'

rawDescription: Python lists and list item matches - can my code/reasoning be improved?


code:
from collections import Counter
print sorted(Counter('xli uymgo fvsar jsb'.replace(' ', '')).most_common())

rawDescription: How to count characters in a file and print them sorted alphanumerically

description: Count characters in a file and print them sorted alphanumerically


rawDescription: Error in displaying unicode and frequency


code:
# Import the required libraries
from urllib import urlencode
from urllib2 import Request, urlopen, URLError, ProxyHandler, build_opener, install_opener
import argparse

# Set up our argument parser
parser = argparse.ArgumentParser(description='Sends LaTeX string to web server and returns meta data used by LaTeX in Word project')
parser.add_argument('webAddr', type=str, help='Web address of LaTeX in Word server')
parser.add_argument('--formula', metavar='FRML', type=str, help='A LaTeX formula string')
parser.add_argument('--fontsize', metavar='SIZE', type=int, default=10, help='Integer representing font size (can be 10, 11, or 12. Default 10)')
parser.add_argument('--proxServ', metavar='SERV', type=str, help='Web address of proxy server, i.e. http://proxy.server.com:80')
parser.add_argument('--proxType', metavar='TYPE', type=str, default='http', help='Type of proxy server, i.e. http')

# Get the arguments from the parser
args = parser.parse_args()

# Define formula string if input
if args.formula:
    values = {'formula': str(args.fontsize) + '.' + args.formula}   # generate formula from args
else:
    values = {}

# Define proxy settings if proxy server is input.
if args.proxServ:       # set up the proxy server support
    proxySupport = ProxyHandler({args.proxType: args.proxServ})
    opener = build_opener(proxySupport)
    install_opener(opener)

# Set up the data object
data = urlencode(values)
data = data.encode('utf-8')

# Send request to the server and receive response, with error handling!
try:
    req = Request(args.webAddr, data)

    # Read the response and print to a file
    response = urlopen(req)
    print response.read()

except URLError, e:
    if hasattr(e, 'reason'):    # URL error case
        # a tuple containing error code and text error message
        print 'Error: Failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):    # HTTP error case
        # HTTP error code, see section 10 of RFC 2616 for details
        print 'Error: The server could not fulfill the request.'
        print 'Error code: ', e.code
        # print e.read()

rawDescription: Returning result of an external script to VBA


code:
soup = BeautifulSoup(page.read())
cities = soup.find_all('td', {'class' : 'details'})
counter = 0
while len(cities) > counter:
    sis = cities[counter].find_next_siblings('td')

    for s in sis:
        print s

    counter += 1

rawDescription: Picking up (next_siblings) texts

description: Picking up (next_siblings) texts


code:
def user_text(self):
    print "which door do you open:"
    print "left or right?"

    door = raw_input("> ")

    if door == "left":
        print "you have chosen the left door"
        return door
    elif door == "right":
        print "you have chosen the right door"
        return door
    else:
        print "you must choose a door"
        return self.user_text()  # don't forget to return in the recursion case

rawDescription: How do I make an imported function call a new function?

description: Make an imported function call a new function


code:
def chat(compliments=["nice", "happy", "good", "smart", "wonderful"]):
    input = raw_input("YOU: ")
    if input.startswith("You are a "):
        if any(input[10:].startswith(c) for c in compliments):
            print "TIM: Thank you"

rawDescription: Making multiple list items apply in python


code:
from django.utils.html import escape
print escape('
Q & A
')

rawDescription: Blocking HTML tags in a webpage

description: Blocking HTML tags in a webpage


code:
import textwrap
print textwrap.wrap(data[2:], 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:
from datetime import datetime

def convertTime(s):
    print datetime.strptime(s, '%H%M').strftime('%I:%M%p').lower()

rawDescription: 24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python


code:
import pygame
import pygame.locals

pygame.init()

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

running = True

while running:

    #
    # events
    #

    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

    #
    # others
    #

    all_keys = pygame.key.get_pressed()

    #print 'shift:', all_keys[pygame.K_LSHIFT], all_keys[pygame.K_RSHIFT]

    if all_keys[pygame.K_a] and (all_keys[pygame.K_LSHIFT] or all_keys[pygame.K_RSHIFT]):
        print "pressed: SHIFT + A"

pygame.quit()

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


code:
import pandas as pd

df = pd.read_csv("data.csv")
# Or you can use df = pd.DataFrame.from_dict({'Value': {0: 0, 1: 3, 2: 2, 3: 2, 4: 1, 5: 2, 6: 3, 7: 0, 8: 1, 9: 3, 10: 0, 11: 0, 12: 0, 13: 1, 14: 0, 15: 3, 16: 2, 17: 3, 18: 1, 19: 0}})
# --
# from http://stackoverflow.com/questions/24281936
# credits to @behzad.nouri
df['tag'] = df['Value'] > 0
fst = df.index[df['tag'] & ~ df['tag'].shift(1).fillna(False)]
lst = df.index[df['tag'] & ~ df['tag'].shift(-1).fillna(False)]
pr = [(i, j) for i, j in zip(fst, lst)]
# --

for i, j in pr:
    print df.loc[i:j, "Value"]

rawDescription: Quickly Find Non-Zero Intervals

description: Quickly Find Non-Zero Intervals


code:
collection = s.split(".")[0]
function_call = s.split(".")[-1].strip("()")
print getattr(db[collection],function_call)()

rawDescription: How do I construct a variable query with pymongo

description: Construct a variable query with pymongo


code:
from datetime import datetime, timedelta

# This structure will allow us to append to our dictionary without
# there needing to be a key first (comes in handy)
from collections import defaultdict

def days_in_range(start, end, daysDict):
    # Convert your start/end dates
    start_d = datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ')
    end_d = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ')

    # Now iterate over the days between those two dates, adding
    # an arbitrary value to the 'day' key of our dict
    for i in range((end_d - start_d).days + 1):
        day_name = '{0:%A}'.format(start_d + timedelta(days=i))
        daysDict[day_name].append(i)
    return daysDict

# Create your dictionary that will have a list as the default value
daysDict = defaultdict(list)

start = '2012-12-24T00:00:00Z'
end = '2012-12-30T23:59:59Z'

# I would probably reevaluate this part, but the reason for
# passing the dictionary itself to the function is so that
# it can better fit into situations where you have multiple events
# (although a class structure may be well-suited for this, but
# that may be overcomplicating things a bit :) )
daysDict = days_in_range(start, end, daysDict)

for day, value in daysDict.iteritems():
  print day, value

rawDescription: Find Out What Days an Event is On With Google Calendar?


rawDescription: Generating a probability from a pdf?

description: Generating a probability from a pdf


code:
print s.encode('ascii', errors='backslashreplace')
print s.encode('ascii', errors='xmlcharrefreplace')
print s.encode('unicode-escape')
print s.encode('punycode')

rawDescription: Python - Unicode to ASCII conversion

description: Python - Unicode to ASCII conversion


code:
path = '/Users/user/Desktop'
files = os.listdir(path)
print files

rawDescription: writing command line output to file

description: Writing command line output to file


code:
import Tkinter, Tkconstants, tkFileDialog
class TkFileDialogExample(Tkinter.Frame):

  def __init__(self, root):
    Tkinter.Frame.__init__(self, root)

    # define buttons
    Tkinter.Button(self, text='askopenfilename',
                   command=self.askopenfilename).pack()
    Tkinter.Button(self, text='askdirectory',
                   command=self.askdirectory).pack()

    self.file = '' # initialize attributes as empty strings
    self.path = '' #

    global outputValues

  def askopenfilename(self):
    self.file = tkFileDialog.askopenfilename() # set attribute
    outputValues['file'] = self.file           # set element of global variable
    print self.file

  def askdirectory(self):
    self.path = tkFileDialog.askdirectory()    # set attribute
    outputValues['path'] = self.path           # set element of global variable
    print self.path

if __name__=='__main__':
    root = Tkinter.Tk()
    TkFileDialogExample(root).pack()
    myFileDialog = TkFileDialogExample(root)
    outputValues = {}                          # define global variable
    myPath = myFileDialog.path
    root.mainloop()
    for key, val in outputValues.iteritems():  # the mainloop is over, but
        print key, val                         # the data you set is still
                                               # available

rawDescription: Use Tkinter in OOP approach

description: Use Tkinter in OOP approach


code:
rows = [line.split() for line in myfile]
maxlen = max(len(x) for x in rows)
for row in rows:
    print " ".join(row + ["0"] * (maxlen - len(row)))

rawDescription: zero fill empty spaces at specific locations

description: Zero fill empty spaces at specific locations


rawDescription: Web crawler to extract in between the list


code:
class D(A, B, C):
    def foo(self):
        print "foo from D"
        for cls in D.__bases__:
            cls().foo("D")

rawDescription: Python Call Parent Method Multiple Inheritance


code:
print exactMatch.findall("my blue cat")
print exactMatch.findall("my red car")
print exactMatch.findall("my red and blue monkey")
print exactMatch.findall("my yellow dog")

rawDescription: Python RegEx, match words in string and get count


code:
for animal in self.animals:
    for other_animal in set(self.animals).difference([animal]):
        if animal.pos == other_animal.pos:
            self.animals_to_die.add(animal)
            print other_animal
            print animal
            self.animals_to_die.add(other_animal)

rawDescription: Make a copy of a set and exclude one item


code:
def updateValue(self, event):
    w = event.widget
    if isinstance(w, tk.Scale):
        print repr(w)
        print w.get()
        print w.cget("label")

rawDescription: Python - Tkinter - Get the name and value of scale/slider


code:
from threading import Thread
import time
import prctl

def sleeper():
    prctl.set_name("sleeping tiger")
    while True:
        time.sleep(10)
        print "sleeping"

t = Thread(target=sleeper, name="Sleeper01")
t.start()
t.join()

rawDescription: Python thread name doesn't show up on ps or htop


code:
import sys
sys.my_exit = sys.exit
def func(status):
    if status:
       print "Fatal!"
    sys.my_exit(status)

sys.exit = func
sys.exit(1)

rawDescription: Make atexit registered function act according to exit status


code:
from sqlalchemy import inspect
mapper = inspect(JobStatus)
for column in mapper.attrs:
    print column.key

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

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


code:
import numpy as np

grid = np.array([['A', 'D', 'G'],
                 ['B', 'E', 'H'],
                 ['C', 'F', 'I']])

grid[0] = np.roll(grid[0], 1)
print grid

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


code: print sum(length_list)

rawDescription: Make a sum of sum of lists in Python 2.7?


code:
def decorate_logger(func):
    def inner(*args, **kwargs):
        print "Entering", func.func_name, "with Parameters :", args, kwargs
        temp = func(*args, **kwargs)
        print "Leaving ", func.func_name, "with :", temp, "for :", args, kwargs
        return temp
    return inner

@decorate_logger
def sum(a, b, c):
    return a + b + c

print sum(1, 2, 3)
print sum(1, 2, c = 3)

rawDescription: Printing a function and its parameters as a string


code:
import itertools as it

SEQUENCES = ['AGG', 'AGT', 'CCG', 'CGT', 'GAG', 'GGA', 'GGT', 'GTA', 'GTG', 'TAG', 'TGG']
LONGEST_SUPERSTRING = ''.join(SEQUENCES)

def find_shortest_superstring():
    current_shortest = LONGEST_SUPERSTRING
    trim = len(current_shortest)-1
    seen_prefixes = set()
    for perm in it.permutations(SEQUENCES):
        candidate_string = ''.join(perm)[:trim]
        if candidate_string in seen_prefixes:
            continue
        seen_prefixes.add(candidate_string)
        while is_superstring(candidate_string):
            current_shortest = candidate_string
            candidate_string = candidate_string[:-1]
            trim = len(current_shortest)-1
    return current_shortest

def is_superstring(s):
    return all(seq in s for seq in SEQUENCES)

def main():
    print 'Searching for shortest superstring containing all strings.'
    ss = find_shortest_superstring()
    print 'Found shortest superstring containing all strings:\n{}'.format(ss)

if __name__ == '__main__':
    main()

rawDescription: More efficient algorithm for shortest superstring search


code:
for j in range(2):
    i = random.randint(0, len(s) - 4)
    s = s[:i] + w + s[i:]
print s

rawDescription: create and insert randomly duplicates

description: Create and insert randomly duplicates


code:
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(10,30) and now_time <= time(16,30):
    print "yes, within the interval"

rawDescription: How do I determine if current time is within a specified range using Python's datetime module?

description: Determine if current time is within a specified range using Python's datetime module


code:
def my_breakpoint_handler (event):
  if (isinstance(event, gdb.BreakpointEvent)):
    print event.breakpoint.location
    if event.breakpoint.location == "b":
        gdb.write("Breakpoint in b()\n")
        gdb.execute("bt")
    elif event.breakpoint.location == "main.cpp:20":
        gdb.write("Breakpoint in main.cpp:20\n")
        gdb.execute("info frame")
    elif event.breakpoint.location == "main.21":
        gdb.write("Breakpoint in main.cpp:21\n")
        gdb.write("some info")
    else:
      pass

    gdb.execute("c")

gdb.events.stop.connect(my_breakpoint_handler)

rawDescription: How to identify specific GDB breakpoint in python code?

description: Identify specific GDB breakpoint in python code


code: print u' '.join((u'1S²',u'2S¹'))

rawDescription: Need help with tuples in python

description: Need help with tuples in python


code:
class Grandparent(object):
    def my_method(self):
        print "Grandparent"

class Parent(Grandparent):
    def some_other_method(self):
        print "Parent"

class Child(Parent):
    def my_method(self):
        print "Hello Grandparent"
        super(Child, self).my_method()

rawDescription: Python 2.7 : how to call super super class method?


code:
from lxml import etree

s="""<root>
    <element>
        <name>XYZ</name>
        <value>789</value>
    </element>
    <element>
        <name>ABC</name>
        <value>123</value>
    </element>
</root>"""
tree = etree.fromstring(s)
data = [(i.xpath("./name//text()")[0],i.xpath("./value//text()")[0]) for i in tree.xpath("//element")]
print {k:v for k,v in data}

rawDescription: Creating Dictionaries from XML Data in Python (with xml.etree.ElementTree)


code:
def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

rawDescription: Python class method decorator w/ self arguments?


code:
from numpy import *
a = arange(4).reshape((2,2))
print a**2

rawDescription: What does matrix**2 mean in python/numpy?


code:
foo = True
if foo:
    print 'yes'
    #Gets called
if not foo:
    print 'no'
else:
    print 'yes' #Also gets called

rawDescription: Why is IF: not properly evaluating this variable?


code:
import sqlparse, re

def main():
    with open ('/path/to/file.txt') as ddl_file:
        sql = ddl_file.read()
        ddls = sqlparse.split(sql)
        tmp_tables_regex = re.compile("^CREATE TABLE.*_TMP.*\(")
        for ddl in ddls:
            tmp_table_match = tmp_tables_regex.match(ddl)
            if tmp_table_match:
                print "The following DDL is a TMP table:"
                print sqlparse.format(ddl, reindent=True, keyword_case='upper')

if __name__ == "__main__":
    main()

rawDescription: Parsing a ddl in Python with regex using re


code:
for img in soup.select('div.separator > a > img'):
    print img  # or img.parent.parent to get the "div"

rawDescription: Beautiful Soup: searching for a nested pattern?


code:
def return_example():
    return 1
    print "x"
    return 2

rawDescription: Questions about Python 'yield' keyword that I have not found answers elsewhere, and its specific use in a code I am working on


code:
grouped = itertools.groupby('aabbbccdddee')
group, items = next(grouped)
print group, items   # the "_grouper" object is an iterator of items in group "a"
next(grouped)   # we move to the next group
print list(items)   # oops, items vanished!

rawDescription: Regarding the correct usage of groupby(): Python 3


rawDescription: How to parse this string of data structure with pyparsing

description: Parse this string of data structure with pyparsing


code:
from collections import Counter

hp1RDD = "harry potter has a girlfriend who's name is hermione granger and a friend called ron. harry has an uncle who's name is hagrid. hagrid is a big guy"
hp2RDD = "harry potter is the best movie I've ever saw. hermione is very beautfiful"

names = ['harry', 'hermione','ron','hagrid']
rdds = [hp1RDD, hp2RDD]
results = dict()

for name in names:
    tmp_list = list()

    for rdd in rdds:
        count = Counter(rdd.split())
        tmp_list.append(count[name])
    results[name] = tmp_list

print results

rawDescription: Storing the content from for loop in the list python


code:
import re

strings = ['Green Lantern #21',
    'Green Lantern #21 (Variant Cover Edition)',
    'Dejah Thoris & Green Men Of Mars #4 (of 8)',
    'Dejah Thoris & Green Men Of Mars #4 (of 8) (Variant Cover Edition)',
    'Macabre One Shot',
    'Detective Comics #21 Combo Pack']

for s in strings:
    print re.match(r'([^#]*[^#\s])\s*(?:#(\d+)\s*)?(?:\(of (\d+)\)\s*)?(.+)?', s).groups()

rawDescription: Optional regex groups for comic book titles (python)


code:
import time

lastResult = 100

def checkNextID(ID, lastResult = lastResult, diff = [8,18,7,17,6,16,5,15]):
    runs = 0
    SEEN = set()
    while True:
        if ID>lastResult:
            print ('\n=========================='
                   '\nID==%s'
                   '\n   ID>lastResult is %s : program STOPS')\
                  % (ID,ID>lastResult,)
            break
        runs += 1
        if runs % 10 == 0:  time.sleep(0.5)
        if ID in SEEN:
            print '-----------------\n%s\nID==%s  already seen, not examined' % (SEEN,ID)
            ID += 1
        else:
            curRes = isValid(ID)
            if curRes:
                print '--------------------------\n%s\nID==%s  vaaaalid'  % (SEEN,ID)
                while True:
                    for i in diff:
                        runs += 1
                        if runs % 10 == 0:  time.sleep(0.5)
                        curRes = isValid(ID+i)
                        print '   '+str(SEEN)
                        if i==diff[0]:
                            SEEN = set([ID+i])
                        else:
                            SEEN.add(ID+i)
                        if curRes:
                            print '   i==%2s   ID+i==%s   valid' % (i,ID+i)
                            ID += i
                            print '--------------------------\nID==%s' % str(ID)
                            break
                        else:
                            print '   i==%2s   ID+i==%s   not valid' % (i,ID+i)
                    else:
                        ID += 1
                        break
            else:
                print '--------------------------\n%s\nID==%s  not vaaaaalid' % (SEEN,ID)
                ID += 1

def isValid(ID, valid_ones = (1,9,17,25,30,50,52,60,83,97,98)):
    return ID in valid_ones

checkNextID(0)

rawDescription: Python Crawler - need help with my algorithm


code:
def test_var_args(farg, *args):
    print "formal arg:", farg
    for arg in args:
        print "another arg:", arg

test_var_args(1, "two", 3)

rawDescription: Having more than one parameter with def in python


code:
_sentinel = Ellipsis
class MyClass(object):
    def __new__(cls, name):
        if name is _sentinel:
            return object.__new__(cls)
        else:
            instance = type(name + cls.__name__, (MyClass,), {})(_sentinel)
            # Initialization goes here.
            return instance

print type(MyClass('name1'))
print type(MyClass('name2'))

rawDescription: Python: make every instance have a different superclass


code:
# use raw strings to ignore escapes:
s = r'\sgoogle\s'
print s, s.find(r'\s') != -1

# and with regex:
import re
print re.search(r'\\s', s)

rawDescription: Python testing if whitespace(\s) symbol is in string


code:
def call_clsinit(*args, **kwargs):
    cls = type(*args, **kwargs)
    cls._clsinit()
    return cls;

class MyClass(object):
    __metaclass__ = call_clsinit

    @classmethod
    def _clsinit(cls):
        print "MyClass._clsinit()"

rawDescription: Calling a class method upon creation of Python classes


code: print f.__name__

rawDescription: What does functools.wraps do?

description: What does functools.wraps do


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

def makelist(number):
  new_list = []
  for i in range(0, number):
    new_rand = random.randint(1, 100)
    new_list.append(new_rand)
  return new_list

def main():
  number = random.randint(6, 12)
  print "the number is %s" % str(number)
  populated_list = makelist(number)
  populated_list.sort()
  for i in populated_list:
    print(str(i)),

main()

rawDescription: Python random number generation

description: Python random number generation


code:
import matplotlib.pyplot as plt

def on_close(event):
    event.canvas.figure.axes[0].has_been_closed = True
    print 'Closed Figure'

fig = plt.figure()
ax = fig.add_subplot(111)
ax.has_been_closed = False
ax.plot(range(10))

fig.canvas.mpl_connect('close_event', on_close)

plt.show()

print ax.has_been_closed

rawDescription: How to detect that an axis belong to a window that has been closed in matplotlib

description: Detect that an axis belong to a window that has been closed in matplotlib


code:
import pandas as pd
import numpy as np
import calendar
import datetime
from pandas.tseries.offsets import *

d = {'DATE': {0: pd.Timestamp('2012-01-05 00:00:00'), 1: pd.Timestamp('2012-02-08 00:00:00'), 2: pd.Timestamp('2012-03-11 00:00:00'), 3: pd.Timestamp('2012-04-06 00:00:00'), 4: pd.Timestamp('2012-05-04 00:00:00'), 5: pd.Timestamp('2012-06-20 00:00:00'), 6: pd.Timestamp('2012-07-09 00:00:00')}}
df = pd.DataFrame(d)
print df

df =  pd.concat([df]*10000).reset_index(drop=True)
df1 = df.copy()
df2 = df.copy()
df3 = df.copy()
df4 = df.copy()

def one(df):
    df.DATE = df.DATE.apply(lambda x: x.replace(day=calendar.monthrange(x.year,x.month)[1]))
    return df

def two(df):
    df['DATE'] = df['DATE'].map(lambda x: datetime.datetime(x.year, x.month, calendar.monthrange(x.year,x.month)[1]))
    return df

def three(df):
    df['DATE'] = df['DATE'].map(lambda x: datetime.datetime(x.year, x.month, x.days_in_month))
    return df

def four(df):
    df['DATE'] = df['DATE'].values.astype('datetime64[M]') + np.array([1], dtype='timedelta64[M]') - np.array([1], dtype='timedelta64[D]')
    return df

def five(df):
    df['DATE'] = df['DATE'] + MonthEnd()
    return df

print one(df).head()
print two(df1).head()
print three(df2).head()
print four(df4).head()

rawDescription: Manipulate date field pandas

description: Manipulate date field pandas


code:
import os
import subprocess
import signal
import sys

def pref_fun():
    signal.signal(signal.SIGFPE,foo)

def foo(signal,frame):
    print "Caught signal!"
    sys.exit(0)

sub = subprocess.Popen(["./a.out"], preexec_fn=pref_fun)
sub.wait()
v = sub.returncode
print "value: ", v
print os.WIFSIGNALED(v)
print "signal:", os.WTERMSIG(v)
print "SIGFPE", signal.SIGFPE

rawDescription: How to handle child SIGFPE/SIGILL signals using subprocess and preexec_fn?

description: Handle child SIGFPE/SIGILL signals using subprocess and preexec_fn


rawDescription: Dumping memoization decorator cache to file


code:
posts = browser.find_elements_by_css_selector(".Parwrsp.Parwrsp-Ado")
for post in posts:
    print post.get_attribute('href')

rawDescription: Href values are not being returned

description: Href values are not being returned


code:
from __future__ import with_statement
import time
import re
from cStringIO import StringIO

def word_iter_std(filename):
    start = time.time()
    with open(filename) as f:
        for line in f:
            for word in line.split():
                yield word
    print 'iter_std took %0.6f seconds' % (time.time() - start)

def word_iter_re(filename):
    start = time.time()
    with open(filename) as f:
        txt = f.read()
    for word in re.finditer('\w+', txt):
        yield word
    print 'iter_re took %0.6f seconds' % (time.time() - start)

def word_iter_stringio(filename):
    start = time.time()
    with open(filename) as f:
        io = StringIO(f.read())
    for line in io:
        for word in line.split():
            yield word
    print 'iter_io took %0.6f seconds' % (time.time() - start)

woo = '/tmp/woo.txt'

for word in word_iter_std(woo): pass
for word in word_iter_re(woo): pass
for word in word_iter_stringio(woo): pass

rawDescription: Iterating through String word at a time in Python


code:
from time import strptime, mktime, localtime, asctime
from math import floor

def averageBusinessDay (dates):
    f = [mktime(strptime(x)) for x in dates]
    h = [x for x in f if localtime(x).tm_wday < 5]  # Get rid of weekend days
    bweek, cweek, dweek = 3600*24*5, 3600*24*7, 3600*24*2
    e = localtime(h[0])  # Get struct_time for first item
    # fm is first Monday in local time
    fm = mktime((e.tm_year, e.tm_mon, e.tm_mday-e.tm_wday, 0,0,0,0,0,0))
    i = [x-fm for x in h]  # Subtract leading Monday
    j = [x-floor(x/cweek)*dweek for x in i]  # Squeeze out weekends
    avx = sum(j)/len(j)
    avt = asctime(localtime(avx+floor(avx/bweek)*dweek+fm))
    return avt

def atest(dates):
    print dates
    print 'Average = ', averageBusinessDay (dates)

atest(['Fri Jan 13 12:00:00 2012', 'Mon Jan 16 11:00:00 2012'])
atest(['Fri Jan 13 12:00:00 2012', 'Mon Jan 16 13:00:00 2012'])
atest(['Fri Jan 13 14:17:58 2012', 'Sat Jan 14 1:2:3 2012', 'Sun Jan 15 4:5:6 2012', 'Mon Jan 16 11:03:29 2012', 'Wed Jan 18 14:27:17 2012', 'Mon Jan 23 10:02:12 2012', 'Mon Jan 30 10:02:12 2012'])
atest(['Fri Jan 14 14:17:58 2011', 'Mon Jan 17 11:03:29 2011', 'Wed Jan 19 14:27:17 2011', 'Mon Jan 24 10:02:12 2011'])

rawDescription: calculating the mean of a list of timestamps ignoring weekend days in python

description: Calculating the mean of a list of timestamps ignoring weekend days in python


code:
print unicode(tmp, 'latin1')
print unicode(tmp, 'utf-8')

rawDescription: Python unicode decode not working for outlook exported csv


code:
_str = _str.split()
new = [_str[i-1][len(_str[i-1])-4:len(_str[i-1])]+_str[i] if i > 0 else _str[i] for i in range(len(_str))]
print '\n'.join(new)

rawDescription: cut a string with duplicates

description: Cut a string with duplicates


code:
print "method(1 + 2):", len(set(nejsou.ASS.tolist()+nee)), "Unique ASS IDs"
# method(1 + 2): 4 Unique ASS IDs

print "method(1):",len(set(nejsou.ASS.tolist())), "Unique ASS IDs"
# method(1): 3 Unique ASS IDs

print "method(2):",len(set(nee)), "Unique ASS IDs"
# method(2): 2 Unique ASS IDs

rawDescription: Pandas boolean indexing vs comparision of two lists: Same (?) methods, different results