code:
#!/usr/bin/env python

import time

class Alpha(set):
    def __init__(self, name, s=()):
            super(Alpha, self).__init__(s)
            self.name = name
    def __repr__(self):
            return '%s(%r, set(%r))' % (self.__class__.__name__,
                                        self.name,
                                        list(self))

class Alpha2(set):
    def __init__(self, name, s=()):
            super(Alpha2, self).__init__(s)
            self.name = name
    def __repr__(self):
            return '%s(%r, set(%r))' % (self.__class__.__name__,
                                        self.name,
                                        set(self))

class Alpha3(set):
    def __init__(self, name, s=()):
            super(Alpha3, self).__init__(s)
            self.name = name
    def __repr__(self):
            rep = super(Alpha3, self).__repr__()
            rep = rep.replace(self.__class__.__name__, 'set', 1)
            return '%s(%r, %s)' % (self.__class__.__name__,
                                    self.name,
                                    rep)

def timeit(exp, repeat=10000):
    results = []
    for _ in xrange(repeat):
        start = time.time()
        exec(exp)
        end = time.time()-start
        results.append(end*1000)
    return sum(results) / len(results)

if __name__ == "__main__":
    print "Alpha():  ", timeit("a = Alpha('test', (1,2,3,4,5))")
    print "Alpha2(): ", timeit("a = Alpha2('test', (1,2,3,4,5))")
    print "Alpha3(): ", timeit("a = Alpha3('test', (1,2,3,4,5))")

rawDescription: Defining __repr__ when subclassing set in Python


code:
# Did the user actually toggle fullscreen, or was it
# a different window-state event (e.g. maximize)?
if event.changed_mask & gtk.gdk.WINDOW_STATE_FULLSCREEN:
    # What's the new state?
    print bool(event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN)

rawDescription: Detect fullscreen in pygtk

description: Detect fullscreen in pygtk


code:
ss="""
peanut butter1

peanut butter2

2.0 to 6.0 mg of 17β-estradiol and

0.020 mg of ethinylestradiol;

0.25 to 0.30 mg of drospirenone and
peanut butter3

peanut butter4
"""
import re
tags = re.compile (r".*?<([^/]\w*?) .*?>(.*?)</\1>") # find tag like
...

start = re.compile(r".*?<([^/]\w*?) .*?>(.*)") # find starting tags with attributes
end = re.compile(r"</.*?>")
r=[]
for s in ss.split("\n"):
    if not s.strip(): continue
    st = re.match(start,s)
    if st: # start tag exists
        m = re.match(tags,s)
        if m: # full terminated tag
            r.append(list(reversed(m.groups())))
            extra = s[m.end():].strip()
            if extra:
                r.append([extra,"no tag"])
        else: # half tag start
            r.append(list(reversed(st.groups())))
    else: # no start tag
        s = re.sub(end, "", s) # remove closing tags
        r.append([s.strip(),"no tag"])
print "\n".join([str(s) for s in r])

rawDescription: Use python regex to turn <ul> <li> and unbounded items into a list


code:
text = 'some spaces variable = 7 = ...'
if '=' in text:
    chunks = text.split('=')
    assignedval = chunks[1]#second value, 7
    print 'assigned value is', assignedval
else:
    print 'no assignment in line'

rawDescription: parsing a line of text to get a specific number

description: Parsing a line of text to get a specific number


code:
import httplib2

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# REPLACE WITH YOUR Project ID
PROJECT_NUMBER = 'XXXXXXXXXXX'
# REPLACE WITH THE SERVICE ACCOUNT EMAIL FROM GOOGLE DEV CONSOLE
SERVICE_ACCOUNT_EMAIL = 'XXXXX@developer.gserviceaccount.com'

# OBTAIN THE KEY FROM THE GOOGLE APIs CONSOLE
# More instructions here: http://goo.gl/w0YA0
f = file('key.p12', 'rb')
key = f.read()
f.close()

credentials = SignedJwtAssertionCredentials(
    SERVICE_ACCOUNT_EMAIL,
    key,
    scope='https://www.googleapis.com/auth/bigquery')

http = httplib2.Http()
http = credentials.authorize(http)

service = build('bigquery', 'v2')
datasets = service.datasets()
response = datasets.list(projectId=PROJECT_NUMBER).execute(http)

print 'Dataset list:'
for dataset in response['datasets']:
  print '%s' % dataset['datasetReference']['datasetId']

rawDescription: How to query BigQuery programmatically from Python without end-user interaction?

description: Query BigQuery programmatically from Python without end-user interaction


code:
import sys
import time
from multiprocessing import Process
from multiprocessing.queues import Queue
from threading import Thread
from Tkinter import *

# This function takes the text widget and a queue as inputs.
# It functions by waiting on new data entering the queue, when it
# finds new data it will insert it into the text widget
def text_catcher(text_widget,queue):
    while True:
        text_widget.insert(END, queue.get())

# This is a Queue that behaves like stdout
class StdoutQueue(Queue):
    def __init__(self,*args,**kwargs):
        Queue.__init__(self,*args,**kwargs)

    def write(self,msg):
        self.put(msg)

    def flush(self):
        sys.__stdout__.flush()

def test_child(q):
    # This line only redirects stdout inside the current process
    sys.stdout = q
    # or sys.stdout = sys.__stdout__ if you want to print the child to the terminal
    print 'child running'

def test_parent(q):
    # Again this only redirects inside the current (main) process
    # commenting this like out will cause only the child to write to the widget
    sys.stdout = q
    print 'parent running'
    time.sleep(0.5)
    Process(target=test_child,args=(q,)).start()

if __name__ == '__main__':
    gui_root = Tk()
    gui_txt = Text(gui_root)
    gui_txt.pack()
    q = StdoutQueue()
    gui_btn = Button(gui_root, text='Test', command=lambda:test_parent(q),)
    gui_btn.pack()

    # Instantiate and start the text monitor
    monitor = Thread(target=text_catcher,args=(gui_txt,q))
    monitor.daemon = True
    monitor.start()

    gui_root.mainloop()

rawDescription: Python multiprocessing redirect stdout of a child process to a Tkinter Text


code:
class MyClass:
    @classmethod
    def foo(cls):
        print "hi"

    @classmethod
    def bar(cls):
        cls.foo()

rawDescription: Python: possible to call static method from within class without qualifying the name


code:
class A(object):
    elems = [1, 2, 3]
    @classmethod
    def collated(cls):
      return sorted(cls.elems)

class B(A):
    pass

class C(B):
    elems = B.elems + [20, 100]

class D(B):
    elems = B.elems + [4, 5]

print "A.collated() == ", A.collated()
print "B.collated() == ", B.collated()
print "C.collated() == ", C.collated()
print "D.collated() == ", D.collated()

rawDescription: Can Python class attributes be additive?

description: Can Python class attributes be additive


code:
import lxml.html

htmltree = lxml.html.parse('http://www.google.com/intl/en/about/corporate/index.html')

print htmltree.xpath('//p/text()')

rawDescription: Parse paragraphs from HTML using lxml

description: Parse paragraphs from HTML using lxml


code:
#!/usr/bin/env python

import sys, time

while True:
  print "foo"
  sys.stdout.flush()
  time.sleep(2)

rawDescription: Stream child process output in flowing mode


code:
import pygame,time,sys

#pygame.init()
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
print "Mixer settings", pygame.mixer.get_init()
print "Mixer channels", pygame.mixer.get_num_channels()
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.load("2.mp3")
pygame.mixer.music.play()

clock = pygame.time.Clock()
while pygame.mixer.music.get_busy():
   # check if playback has finished
   clock.tick(30)

rawDescription: can not hear the sound from pygame

description: Can not hear the sound from pygame


code:
def evaluate(l, max_depth, cur_depth=0, counter=0):
    if cur_depth > max_depth:
        return counter

    for x in l:
        counter += 1
        l2 = [x * 2 for x in l]
        print cur_depth, l2, counter
        counter = evaluate(l2, max_depth, cur_depth + 1, counter)

    return counter

rawDescription: Checkers algorithm: how to reduce nested for loops


code:
with open(logfile) as fin:
    for line in fin:
        if var.lower() in line.lower():  # makes this case insensitive
            print 'found', line.rstrip() # You will be printing double new lines
                                         #  without rstrip here

rawDescription: How to search for a string case-insensitively without regular expressions?

description: Search for a string case-insensitively without regular expressions


rawDescription: how to perform a generalised eigendecomposition here?

description: Perform a generalised eigendecomposition here


code:
class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.challenger", "*.challenger"]

    def __init__(self, conn, *args, **kwargs):
        super(MyHandler, self).__init__(*args, **kwargs)
        self.conn_list = conn

    def process(self, event):
        time.sleep(5)
        print event.src_path, event.event_type  # print now only for degug

    def on_created(self, event):
        self.process(event)
        c = self.conn_list.pop()
        c.send('1')
        c.close()

s = socket.socket()         # Create a socket object
host = socket.gethostname()  # Get local machine name
port = 12346                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port
flag = '0'
s.listen(5)                 # Now wait for client connection.

from collections import deque
conn_list = deque()

if __name__ == '__main__':
    observer = Observer()
    observer.start()
    args = sys.argv[1:]
    observer.schedule(MyHandler(conn_list), path='/home/abcd/Maildir/new')
while True:
    try:
        c, addr = s.accept()     # Establish connection with client.
        print 'Got connection from', addr
        conn_list.append(c)

    except KeyboardInterrupt:
        observer.stop()
        while conn_list:
            conn_list.pop().close()
        print "Connections closed"
        break

observer.join()

rawDescription: Multithreaded socket programming in python


code:
def getMaxSubArrays(x):
    y=x-np.mean(x)
    z=y/y.max()
    maxSubArrays=[]
    subFound=False
    begin=0
    for i in range(len(z)):
        if z[i]>0.75 and subFound==False:
            subFound=True
            begin=i
        elif z[i]<=0.75 and subFound==True:
            subFound=False
            maxSubArrays.append((begin,i))
    for subarray in maxSubArrays:
        print "subarray found: index ",subarray[0]," to ",subarray[1], x[subarray[0]:subarray[1]]
    return maxSubArrays

rawDescription: How to find maximum interval in a graph?

description: Find maximum interval in a graph


code:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pyuca import Collator

metadata = MetaData()
Base = declarative_base(metadata=metadata)

class Item(Base):
    __tablename__ = 'Item'
    id = Column(Integer, primary_key=True)
    value = Column(String, nullable=False)

collator = Collator('allkeys.txt')

def collate_unicode(value1, value2):
    return cmp(collator.sort_key(value1), collator.sort_key(value2))

engine = create_engine('sqlite://')
engine.raw_connection().create_collation('unicode', collate_unicode)
metadata.create_all(engine)
session = sessionmaker(engine)()

for word in [u"ĉambr", u"ĉar", u"car'", u"carin'", u"ĉe", u"ĉef'",
             u"centjar'", u"centr'", u"cerb'", u"cert'", u"ĉes'", u"ceter'"]:
    item = Item(value=word)
    session.add(item)
    session.commit()

for item in session.query(Item).order_by(collate(Item.value, 'unicode')):
    print item.value

rawDescription: SQLAlchemy custom sorting algorithms when using SQL indexes


code:
hand = ["3D", "4D", "4C", "5D", "JS", "JC"]

from itertools import groupby

def generate_plays(hand):
    plays = []
    for rank,suit in groupby(hand, lambda f: f[0]):
        plays.append(list(suit))
    for card in hand:
        if [card] not in plays:       #redundant due to list nesting
            plays.append([card])       #problematic code in question
    return plays

print generate_plays(hand)

rawDescription: Preserving concatenated elements in a Python str to list conversion


code:
scene = QGraphicsScene();
scene.addEllipse( 100, 100, 50, 50 )
scene.addRect( 200, 12, 120, 50 )
scene.addLine( 50, 70, 100, 400 )

for item in scene.items():
    if item.type() == QGraphicsEllipseItem().type():
        print "Ellipse",  item.rect()
    elif item.type() == QGraphicsRectItem().type():
        print "Rectangle",  item.rect()
    elif item.type() == QGraphicsLineItem().type():
        print "Line", item.line().p1(), item.line().p2()

rawDescription: How to save Qt graphic scene items in file and open it again?

description: Save Qt graphic scene items in file and open it again


code:
def isprime(n):
    '''check if integer n is a prime'''
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2:
        return True
    # all other even numbers are not primes
    if not n & 1:
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

counter = 0
number = 0

while True:
    if isprime(number):
        counter+=1
    if counter == 10000:
        break
    number+=1

print number

rawDescription: Python output just shows blinking cursor


code:
l = [["('N', '', 'SHOWERS', '', 'RD', '11734', '11734', '', '')", "('61060', '61060')"], ['', '', 'NORA', '', 'RD', '10301', '10999', '10400', '10998', '61089', '61089']]

l2 = [['N', '', 'SHOWERS', '', 'RD', '11734', '11734', '', '', '61060', '61060'], ['', '', 'NORA', '', 'RD', '10301', '10999', '10400', '10998', '61089', '61089']]

import ast
from itertools import imap, chain

def is_tuple_string_row(L):
    """Return whether list L is a list of strings containing tuples"""
    return len(L)==2 and all(s.startswith("('") and s.endswith("')") for s in L)

def normalized_list(L):
    """Yield lists in sequence L as lists of strings

    Normalizes a list of strings of tuples down to a simple list of strings
    """
    for item in L:
        if is_tuple_string_row(item):
            yield list(chain.from_iterable(imap(ast.literal_eval, item)))
        else:
            yield item

# You can iterate efficiently
for item in normalized_list(l):
    print item

# or you can put the whole thing to a single new list
aslist = list(normalized_list(l))

# verify results
assert aslist == l2

rawDescription: Converting strings of tuples within list of lists to list items in Python


code:
teams_goals = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':2}
print teams_goals
test_teams = {'chelsea' : 1, 'man u' : 1,'Arsenal':1}
teams_goals_copy = teams_goals.copy()

for team in test_teams:
    for j in range(test_teams[team]):
        teams_goals_copy[team]= teams_goals_copy[team]- 1
        if teams_goals_copy[team] == 0:
            del(teams_goals_copy[team])
    print teams_goals_copy

rawDescription: Basic Python dictionary

description: Basic Python dictionary


code:
import urllib2
import sys

for i in range(1000000):
  try:
    pic = urllib2.urlopen("http://www.tjoernegaard.dk/Faelles/ElevFotos/"+str(i)+".jpg").read()
    with open(str(i).zfill(7)+".jpg") as f:
      f.write(pic)
    print "SUCCESS "+str(i)
  except KeyboardInterrupt:
    sys.exit(1)
  except urllib2.HTTPError, e:
    print "ERROR("+str(e.code)+") "+str(i)

rawDescription: Curl only save if not 404

description: Curl only save if not 404


code:
import matplotlib
print matplotlib.__file__

rawDescription: Pip installing latest version of matplotlib?


code:
import urllib

data = [
    ('c_id', '458'),
    ('state', 'live'),
    ('flash', 'False')
] + [ ('spec_ids[]',str(x)) for x in [1492, 1493, 1493] ]

print urllib.urlopen("http://stackoverflow.com/",urllib.urlencode(data)).read()

rawDescription: Populating "data" section of a post request with function


code:
import numpy as np
import cv2

i = 1
while(1):
  fgbg = cv2.BackgroundSubtractorMOG()
  while(i < 3):
    print 'img' + `i` + '.jpg'
    frame = cv2.imread('img' + `i` + '.jpg')

    fgmask = fgbg.apply(frame)

    cv2.imshow('frame', fgmask)
    i += 1

    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

  cv2.destroyAllWindows()

rawDescription: Extract foreground from individual frames using opencv for python


code:
"""Send a single GTalk message to myself"""

import xmpp
import time

_SERVER = 'talk.google.com', 5223
USERNAME = 'someuser@gmail.com'
PASSWORD = 'whatever'

def sendMessage(tojid, text, username=USERNAME, password=PASSWORD):
    jid = xmpp.protocol.JID(username)
    client = xmpp.Client(jid.getDomain(), debug=[])
    #self.client.RegisterHandler('message', self.message_cb)
    if not client:
      print 'Connection failed!'
      return
    con = client.connect(server=_SERVER)
    print 'connected with', con
    auth = client.auth(jid.getNode(), password, 'botty')
    if not auth:
      print 'Authentication failed!'
      return
    client.RegisterHandler('message', message_cb)
    roster = client.getRoster()
    client.sendInitPresence()
    if '/' in tojid:
        tail = tojid.split('/')[-1]
        t = time.time() + 1
        while time.time() < t:
            client.Process(1)
            time.sleep(0.1)
            if [ res for res in roster.getResources(tojid) if res.startswith(tail) ]:
                break
        for res in roster.getResources(tojid):
            if res.startswith(tail):
                tojid = tojid.split('/', 1)[0] + '/' + res

    print "sending to", tojid
    id = client.send(xmpp.protocol.Message(tojid, text))
    t = time.time() + 1
    while time.time() < t:
        client.Process(1)
        time.sleep(0.1)
    print "status", roster.getStatus(tojid)
    print "show", roster.getShow(tojid)
    print "resources", roster.getResources(tojid)
    client.disconnect()

def message_cb(session, message):
    print ">", message

sendMessage(USERNAME + '/Talk', "This is an automatically generated gtalk message: did you get it?")

rawDescription: How can I retrieve a Google Talk users Status Message

description: Retrieve a Google Talk users Status Message


code:
import time
import threading

def loop(n=10):
    while n>0:
        print n
        n -= 1
        time.sleep(1)

t = threading.Thread(target=loop)
print 'hello world'
t.start()

rawDescription: Python threading - Is this what I need?

description: Python threading - Is this what I need


code:
query_node=iq_node.getQueryChildren()
for node in query_node:
    print node.getAttr("name")

rawDescription: Python-XMPP - Iterate the IQ stanza items


code:
import re
from pprint import pprint

info = {}
records = []
with open('stats4.txt') as data:
    for line in data:
        gameid = [item.strip('[') for item in line.split(']')]
        del gameid[-1]
        gameidstr = ''.join(gameid)
        gameid = gameidstr
        line = line[7:]
        player, stats, outcome, date = [item.strip() for item in line.split('-', 3)]
        stats = dict(zip(('kills', 'deaths', 'assists'), map(int, stats.split('/'))))
        date = tuple(map(int, date.split('-')))
        info[player] = dict(zip(('gameid', 'player', 'stats', 'outcome', 'date'),
                                (gameid, player, stats, outcome, date)))
        records.append(tuple((gameid, info[player])))

#print "\n\n", info, "\n\n" #print the info dictionary just to see
pprint(info)
champ = raw_input("Champ's name: ") #get champion name
#print info[champ].get('stats').get('kills'), "\n\n"
#print "[%s] %s - %s/%s/%s - %s-%s-%s" % (
#       info[champ].get('gameid'), champ, info[champ].get('stats').get('kills'),
#       info[champ].get('stats').get('deaths'), info[champ].get('stats').get('assists'),
#       info[champ].get('date')[0], info[champ].get('date')[1],
#       info[champ].get('date')[2])
#print "\n\n"
#print info[champ].values()

i = 0
for item in records: #this prints out all records
    print "\n", "[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (
                 records[i][0], records[i][1]['player'], records[i][1]['stats']['kills'],
                 records[i][1]['stats']['deaths'], records[i][1]['stats']['assists'],
                 records[i][1]['outcome'], records[i][1]['date'][0],
                 records[i][1]['date'][1], records[i][1]['date'][2])
    i = i + 1

print "\n" + "*" * 50
i = 0
search = []
for item in records:
    if champ in records[i][1]['player']:
        search.append(records[i][1])
    i = i + 1
if not search:
    print "no match"
    exit()

s = 0
for item in search:
        print "\n[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (search[s]['gameid'],
              search[s]['player'], search[s]['stats']['kills'],
              search[s]['stats']['deaths'], search[s]['stats']['assists'],
              search[s]['outcome'], search[s]['date'][0], search[s]['date'][1],
              search[s]['date'][2])
        s = s + 1

rawDescription: Need to handle keyerror exception python


code:
import errno
import os
import urllib

def require_dir(path):
    try:
        os.makedirs(path)
    except OSError, exc:
        if exc.errno != errno.EEXIST:
            raise

directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
require_dir(directory)
filename = os.path.join(directory, "stackoverflow.html")

if not os.path.exists(filename):
    urllib.urlretrieve("http://stackoverflow.com", filename)

rawDescription: Downloading an image, want to save to folder, check if file exists


code:
def special_strings_count(strings):
    return len([x for x in strings if len(x) > 1 and x[0] == x[-1]])

strings = [] # your list of strings
print special_strings_count(strings)

rawDescription: how to Write a function that takes a list of strings as input, and returns the count of the number of strings


code:
L = []
input = [sys.stdin]

for i in range(4):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((host,port+i))
    server.listen(backlog)
    L.append(server)
    input.append(server)

running = 1
print len(L)
while running:
    inputready,outputready,exceptready = select.select(input,[],[])

    for s in inputready:
        if s in L:
            # handle the server socket
            print "opened"
            client, address = s.accept()
            input.append(client)
        elif s == sys.stdin:
            # handle standard input
            junk = sys.stdin.readline()
            running = 0
        else:
            # handle all other sockets
            data = s.recv(size)

rawDescription: Python socket dictionary with select

description: Python socket dictionary with select


code:
original_dict = {'foo':[1,2,3], 'bar':[4,5,6]}
keys_for_dict1 = ['foo']
dict1 = {}; dict2 = {}
for key in original_dict:
    if key in keys_for_dict1:
        dict1[key] = original_dict[key]
    else:
        dict2[key] = original_dict[key]

dict1['foo'][2]='a'
print dict1['foo']
print original_dict['foo']

rawDescription: split dictionary in two 'by reference', not copying values

description: Split dictionary in two 'by reference', not copying values


code:
from twisted.python.rebuild import rebuild, Sensitive
from twisted.python.filepath import FilePath

p = FilePath("mymodule.py")
def clearcache():
    bytecode = p.sibling("mymodule.pyc")
    if bytecode.exists():
        bytecode.remove()
clearcache()
p.setContent("def x(): return 1")
import mymodule
from mymodule import x
p.setContent("def x(): return 2")

class Something(Sensitive, object):
    def __init__(self):
        self.stuff = {"something": x}
    def invoke(self):
        if self.needRebuildUpdate():
            for key in list(self.stuff):
                self.stuff[key] = self.latestVersionOf(self.stuff[key])
            self.rebuildUpToDate()
        return self.stuff["something"]()

def test():
    print s.invoke()
    print x()

s = Something()
test()

clearcache()
rebuild(mymodule)

test()

rawDescription: Limitations of Twisted code reloading

description: Limitations of Twisted code reloading


code:
def search_entries():
    found = 0
    search = raw_input("Please enter the person's name: ")
    for line in open('addbook.txt', 'r').readlines():
        if search in line:
            found = 1
        if found >= 1:
            print line
            found = found + 1
            if found == 4: break

rawDescription: Print out a certain section of a file

description: Print out a certain section of a file


code:
import re
with open("input") as f:
    for line in f:
        line = line.strip()
        # chop a line into expressions of the form: str [OP NUMBER]
        exprs = re.split(r'(\w+\s*(?:[!<>=]=?\s*[\d.]*)?\s*,?\s*)', line)
        for expr in exprs:
            # chop each expression into tokens and get the str part
            tokens = re.findall(r'(\w+)\s*(?:[!<>=]=?\s*[\d.]*)?,?', expr)
            if tokens: print tokens

rawDescription: Python string split using regex

description: Python string split using regex


code:
for x, left in enumerate(all):
    for y, right in enumerate(all):
        common = len(set(left) & set(right))
        print "item%s has %s values in common with item%s"%(x, common, y)

rawDescription: how to compare one item in a list with all the other items in this list, python

description: Compare one item in a list with all the other items in this list, python


code:
import cv2
import numpy as np

print cv2.__version__

rMaskgray = cv2.imread('5evOn.jpg', 0)
(thresh, binRed) = cv2.threshold(rMaskgray, 50, 255, cv2.THRESH_BINARY)

_, Rcontours, hier_r = cv2.findContours(binRed,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
r_areas = [cv2.contourArea(c) for c in Rcontours]
max_rarea = np.max(r_areas)
CntExternalMask = np.ones(binRed.shape[:2], dtype="uint8") * 255

for c in Rcontours:
    if(( cv2.contourArea(c) > max_rarea * 0.70) and (cv2.contourArea(c)< max_rarea)):
        cv2.drawContours(CntExternalMask,[c],-1,0,1)

cv2.imwrite('contour1.jpg', CntExternalMask)

rawDescription: OpenCV how to smooth contour, reducing noise


code:
import os

dir_path = '/path/to/folders/folder{}'

x = 10

for i in range(0, x):
    formatted_path = dir_path.format(i)
    try:
        for f in os.listdir(formatted_path):
            filename = os.path.join(formatted_path, f)
            if os.path.isfile(filename):
                print filename

    except OSError:
        print "{} does not exist".format(formatted_path)

rawDescription: Walk through folders until specific ending number python


code:
d = Counter({'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4})
d.most_common()
for k, v in d.most_common(3):
    print '%s: %i' % (k, v)

rawDescription: top values from dictionary

description: Top values from dictionary


code:
import datetime

jobs = [
    (datetime.datetime(15, 7, 28, 8, 3), datetime.datetime(15, 7, 28, 8, 9)),
    (datetime.datetime(15, 7, 28, 8, 3), datetime.datetime(15, 7, 28, 8, 58)),
    (datetime.datetime(15, 7, 28, 8, 3), datetime.datetime(15, 7, 28, 10, 3)),
    (datetime.datetime(15, 7, 28, 8, 3), datetime.datetime(15, 7, 28, 9, 3)),
    (datetime.datetime(15, 7, 28, 10, 3), datetime.datetime(15, 7, 28, 8, 3)),
]
data = {'hours': [], 'active_jobs': []}
for hour in range(24):
    current__active_jobs = 0
    for job in jobs:
        if job[0].hour == hour:
            current__active_jobs += 1
        elif job[0].hour < hour and job[1].hour >= hour:
            current__active_jobs += 1
    data['hour'].append(hour)
    data['active_jobs'].append(current__active_jobs)

print DataFrame(data)

rawDescription: Count if: job is in a certain time interval


code:
import extractor
import sys
from ctypes import *
import struct

xtract = extractor.Extractor()

def print_k(xt, plugin, type, format, mime, data, datalen):
    mstr = cast (data, c_char_p)
# FIXME: this ignores 'datalen', not that great...
# (in general, depending on the mime type and format, only
# the first 'datalen' bytes in 'data' should be used).
    if (format == extractor.EXTRACTOR_METAFORMAT_UTF8):
        print "%s - %s" % (xtract.keywordTypes()[type],  mstr.value)
    return 0

for arg in sys.argv[1:]:
    print "Keywords from %s:" % arg
    xtract.extract(print_k, None, arg)

rawDescription: Example of use libextractor3 from python


code:
import re
regex = re.compile('(?:red,(?P<redfirst>\w+)|(?P<othercolorfirst>\w+),red)')
string = "blue,red   red,yellow   blue,yellow   red,green   purple red, ..."
for matches in regex.finditer(string):
    if matches.group('redfirst'):
        print matches.group('redfirst')

rawDescription: regex result filter in python

description: Regex result filter in python


rawDescription: Python: printing floats / modifying the output


code:
import requests

url = "http://www.....aspx?download=1"

file_name = "Data.csv"
u = requests.get(url)

file_size = int(u.headers['content-length'])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

with open(file_name, 'wb') as f:
    for chunk in u.iter_content(chunk_size=1024):
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)
            f.flush()
f.close()

rawDescription: Get a file from an ASPX webpage using Python


code:
queryset = MyModel.objects.all()
print queryset.query

rawDescription: Getting the SQL from a Django QuerySet

description: Getting the SQL from a Django QuerySet


code:
def __init__(self, arg_set = set()):
   print id(arg_set)
   self.my_set = arg_set

rawDescription: Unexpected python behavior related to default argument for mutable object


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

#### For those who are familiar with pandas
#### Correspondence:
####    value <-> Orange.data.Value
####        NaN <-> ["?", "~", "."] # Don't know, Don't care, Other
####    dtype <-> Orange.feature.Descriptor
####        category, int <-> Orange.feature.Discrete # category: > pandas 0.15
####        int, float <-> Orange.feature.Continuous # Continuous = core.FloatVariable
####                                                 # refer to feature/__init__.py
####        str <-> Orange.feature.String
####        object <-> Orange.feature.Python
####    DataFrame.dtypes <-> Orange.data.Domain
####    DataFrame.DataFrame <-> Orange.data.Table = Orange.orange.ExampleTable
####                              # You will need this if you are reading sources

def series2descriptor(d, discrete=False):
    if d.dtype is np.dtype("float"):
        return Orange.feature.Continuous(str(d.name))
    elif d.dtype is np.dtype("int"):
        return Orange.feature.Continuous(str(d.name), number_of_decimals=0)
    else:
        t = d.unique()
        if discrete or len(t) < len(d) / 2:
            t.sort()
            return Orange.feature.Discrete(str(d.name), values=list(t.astype("str")))
        else:
            return Orange.feature.String(str(d.name))

def df2domain(df):
    featurelist = [series2descriptor(df.icol(col)) for col in xrange(len(df.columns))]
    return Orange.data.Domain(featurelist)

def df2table(df):
    # It seems they are using native python object/lists internally for Orange.data types (?)
    # And I didn't find a constructor suitable for pandas.DataFrame since it may carry
    # multiple dtypes
    #  --> the best approximate is Orange.data.Table.__init__(domain, numpy.ndarray),
    #  --> but the dtype of numpy array can only be "int" and "float"
    #  -->  * refer to src/orange/lib_kernel.cpp 3059:
    #  -->  *    if (((*vi)->varType != TValue::INTVAR) && ((*vi)->varType != TValue::FLOATVAR))
    #  --> Documents never mentioned >_<
    # So we use numpy constructor for those int/float columns, python list constructor for other

    tdomain = df2domain(df)
    ttables = [series2table(df.icol(i), tdomain[i]) for i in xrange(len(df.columns))]
    return Orange.data.Table(ttables)

    # For performance concerns, here are my results
    # dtndarray = np.random.rand(100000, 100)
    # dtlist = list(dtndarray)
    # tdomain = Orange.data.Domain([Orange.feature.Continuous("var" + str(i)) for i in xrange(100)])
    # tinsts = [Orange.data.Instance(tdomain, list(dtlist[i]) )for i in xrange(len(dtlist))]
    # t = Orange.data.Table(tdomain, tinsts)
    #
    # timeit list(dtndarray)  # 45.6ms
    # timeit [Orange.data.Instance(tdomain, list(dtlist[i])) for i in xrange(len(dtlist))] # 3.28s
    # timeit Orange.data.Table(tdomain, tinsts) # 280ms

    # timeit Orange.data.Table(tdomain, dtndarray) # 380ms
    #
    # As illustrated above, utilizing constructor with ndarray can greatly improve performance
    # So one may conceive better converter based on these results

def series2table(series, variable):
    if series.dtype is np.dtype("int") or series.dtype is np.dtype("float"):
        # Use numpy
        # Table._init__(Domain, numpy.ndarray)
        return Orange.data.Table(Orange.data.Domain(variable), series.values[:, np.newaxis])
    else:
        # Build instance list
        # Table.__init__(Domain, list_of_instances)
        tdomain = Orange.data.Domain(variable)
        tinsts = [Orange.data.Instance(tdomain, [i]) for i in series]
        return Orange.data.Table(tdomain, tinsts)
        # 5x performance

def column2df(col):
    if type(col.domain[0]) is Orange.feature.Continuous:
        return (col.domain[0].name, pd.Series(col.to_numpy()[0].flatten()))
    else:
        tmp = pd.Series(np.array(list(col)).flatten())  # type(tmp) -> np.array( dtype=list (Orange.data.Value) )
        tmp = tmp.apply(lambda x: str(x[0]))
        return (col.domain[0].name, tmp)

def table2df(tab):
    # Orange.data.Table().to_numpy() cannot handle strings
    # So we must build the array column by column,
    # When it comes to strings, python list is used
    series = [column2df(tab.select(i)) for i in xrange(len(tab.domain))]
    series_name = [i[0] for i in series]  # To keep the order of variables unchanged
    series_data = dict(series)
    print series_data
    return pd.DataFrame(series_data, columns=series_name)

rawDescription: Converting Pandas DataFrame to Orange Table


code:
from scipy.stats import scoreatpercentile
import numpy as np

theList = np.log10(1+np.arange(.1, 100))
theMedian = np.median(theList)

oneSidedList = theList[:]               # copy original list
# fold over to the right all values left of the median
oneSidedList[theList < theMedian] = 2*theMedian - theList[theList < theMedian]

# find the 70th centile of the one-sided distribution
a = scoreatpercentile(oneSidedList, 70) - theMedian

#check how many elements fall into the range
sel = (theList > (theMedian - a)) * (theList < (theMedian + a))

print np.sum(sel) / float(len(theList))

rawDescription: Finding appropriate cut-off values

description: Finding appropriate cut-off values


code:
from collections import Counter
with open("filename.txt", "r") as f:
    count = Counter(f.read().split("\n"))
    print [x for x in count if count[x] == 1]

rawDescription: Select unique names within a list removing duplicate entries


code:
import multiprocessing

num_procs = 4
def do_work(message):
  print "work",message ,"completed"

def worker():
  for item in iter( q.get, None ):
    do_work(item)
    q.task_done()
  q.task_done()

q = multiprocessing.JoinableQueue()
procs = []
for i in range(num_procs):
  procs.append( multiprocessing.Process(target=worker) )
  procs[-1].daemon = True
  procs[-1].start()

source = ['hi','there','how','are','you','doing']
for item in source:
  q.put(item)

q.join()

for p in procs:
  q.put( None )

q.join()

for p in procs:
  p.join()

print "Finished everything...."
print "num active children:", multiprocessing.active_children()

rawDescription: Multiprocessing Queue in Python

description: Multiprocessing Queue in Python


code:
if all (k in foo for k in ("foo","bar")):
    print "They're there!"

rawDescription: python: How do I check that multiple keys are in a dict in one go?

description: Python: How do I check that multiple keys are in a dict in one go


code:
import heapq

def mult_comb(n):
    heap = []
    visited = {}
    visited[n*n] = True
    prod = n*n
    heapq.heappush(heap, (-prod, n, n))
    while prod > 1:
        (prod,x,y) = heapq.heappop(heap)
        yield -prod,x,y
        prod = -prod

        prod1 = (x-1)*y
        prod2 = x*(y-1)
        if not prod1 in visited:
            heapq.heappush(heap, (-prod1, x-1,y))
            visited[prod1] = True
        if not prod2 in visited:
            heapq.heappush(heap, (-prod2, x,y-1))
            visited[prod2] = True

def main():
    for tup in mult_comb(10):
        print tup

if __name__ == "__main__":
    main()

rawDescription: Multiplicative combination algorithm

description: Multiplicative combination algorithm


code:
for i in vpc.instances.all():
  for tag in i.tags:
    if tag['Key'] == 'Name':
      print tag['Value']

rawDescription: Displaying EC2 Instance name using Boto 3


code:
#!/usr/bin/env python

class A:
    x = []

    def add(self):
        self.x.append(1)

class B:
    def __init__(self):
        self.x = []

    def add(self):
        self.x.append(1)

x = A()
y = A()
x.add()
y.add()
print "A's x:",x.x

x = B()
y = B()
x.add()
y.add()
print "B's x:",x.x

rawDescription: Python - why use "self" in a class?

description: Python - why use "self" in a class


rawDescription: How to iterate over two lists - python

description: Iterate over two lists - python


code:
my_string = "this is my very first python program"
n = len(my_string.split(' '))
for i in range(n):
    my_string_split = [x.replace (" ", "+") for x in my_string.split(' ', n-i-1)]
    print my_string_split

rawDescription: Replacement of space to + in python

description: Replacement of space to + in python


code:
import os

for root, dirs, files in os.walk("/home"):
    for file in files:
        print(os.path.join(root, file))

while True:
    fpath = raw_input('Enter filepath to view '
                    '(leave empty to proceed without viewing another file):')

    if not fpath:
        break

    with open(fpath, 'r') as f:
        print f.read()

rawDescription: Python- How can I view os.walk file contents without printing the file paths each time?


code:
#!/usr/bin/python
# based on example at http://twistedmatrix.com/pipermail/twisted-python/2008-June/017836.html
from twisted.internet import protocol
from twisted.internet import reactor

class EchoProtocol(protocol.Protocol):
    def connectionMade(self):
        print "Client Connected Detected!"
        ### enable keepalive if supported
        try:
            self.transport.setTcpKeepAlive(1)
        except AttributeError: pass

    def connectionLost(self, reason):
        print "Client Connection Lost!"

    def dataReceived(self, data):
        self.transport.write(data)

factory = protocol.Factory()
factory.protocol = EchoProtocol
reactor.listenTCP(8000, factory)
reactor.run()

rawDescription: How to use TCP Keepalive with Endpoints in Twisted?

description: Use TCP Keepalive with Endpoints in Twisted


code:
total = 0
for line in infile:
    line = line.strip("\n")
    if line.startswith('>'):
        name = line
    else:
        pattern = line.count('P')
        total += pattern
        print '%s:%s' %(name,pattern)

#this goes outside the for loop
out.write('%s:%s\n' %(name,total))

rawDescription: Count letters in text

description: Count letters in text


code:
for sub_dict in pl.values():
    print sub_dict['keyA'], sub_dict['keyD'], sub_dict['keyG']

rawDescription: 'for loop' python 3 dictionaries inside dictionaries from .plist (or xml)


code:
import urllib2
url="http://www.test.com/page.html"
page=urllib2.urlopen(url)
data=page.read()
for item in data.split("</h3>"):
    if "<h3>" in item:
         print item.split("<h3>")[1]

rawDescription: python parsing url after string

description: Python parsing url after string


code:
def debug():
    import pdb
    import sys

    # set up the debugger
    debugger = pdb.Pdb()
    debugger.reset()

    # your custom stuff here
    debugger.do_where(None) # run the "where" command

    # invoke the interactive debugging prompt
    users_frame = sys._getframe().f_back # frame where the user invoked `debug()`
    debugger.interaction(users_frame, None)

if __name__ == '__main__':
    print 1
    debug()
    print 2

rawDescription: Python (pdb) - Queueing up commands to execute


code:
from urllib.request import Request, urlopen, HTTPSHandler, build_opener
from urllib.error import URLError, HTTPError
import http.client

class HTTPSClientAuthHandler(HTTPSHandler):

  def __init__(self, key, cert):
    HTTPSHandler.__init__(self)
    self.key = key
    self.cert = cert

  def https_open(self, req):
    return self.do_open(self.getConnection, req)

  def getConnection(self, host, timeout=300):
    return http.client.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)

opener = build_opener(HTTPSClientAuthHandler(private_key_file, public_key_file))
response = opener.open("https://example.com/index.htm")
print response.read()

rawDescription: Python3: get resource from https server with client certificate authentication


code:
import operator

def isAscending(strictly, *seq):
    cmp_op = operator.lt if stricly else operator.le
    seq = [e for e in seq if e is not None]
    return all(cmp_op(a, b) for a, b in zip(seq, seq[1:]))

a, b, c = 1, None, 2
print isAscending(True, a, b, c) # strictly ascending ?

rawDescription: Multiple inequality (a < b < c...) with potentially missing value


code:
from copy import copy

def rewriteGene(instr, annos):
    annotations = copy(annos)
    index = instr.find('-')
    while index > -1:
        for key, ls in annotations.items():
            if index in ls:
                ls.remove(index)
            annotations[key] = [e-1 if e > index else e for e in ls]
        instr = instr[:index] + instr[index+1:]
        index = instr.find('-')
    return instr, annotations

instr = "A--AT--T"
annos = {"range1":[0,1,2,3,4], "range2":[4,5,6,7]}

print rewriteGene(instr, annos)
# ('AATT', {'range2': [2, 3], 'range1': [0, 1, 2]})

rawDescription: Maintaining overlapping annotations while removing dashes from string


code:
import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))

rawDescription: Broadcast a UDP string with Python

description: Broadcast a UDP string with Python


code:
while True:
    user_data = raw_input('What do you want? ')
    if user_data == 'quit': break
    else:
        print 'I can\'t do "{}" yet.'.format(user_data)

rawDescription: Python - Recurring Questions

description: Python - Recurring Questions


code:
def numpy_array(data, peaks):
    processors=4
    pool = mp.Pool(processes=processors)
    chunk_size=len(data)/processors
    print range(processors)
    map_parameters = [] # new
    for i in range(processors):
        counter = i*chunk_size
        chunk=peaks[i*chunk_size:(i+1)*chunk_size-1]
        map_parameters.append((data,chunk,counter)) # new
    pool.map(decode, map_parameters) # new

def decode((data,chunk,counter)): # changed
    for x in chunk:
        peak_counter=0
        data_buff=base64.b64decode(x)
        buff_size=len(data_buff)/4
        unpack_format=">%dL" % buff_size
        index=0
        for y in struct.unpack(unpack_format,data_buff):
            buff1=struct.pack("I",y)
            buff2=struct.unpack("f",buff1)[0]
            if (index % 2 == 0):
                data[counter][1][peak_counter][0]=float(buff2)
            else:
                data[counter][1][peak_counter][1]=float(buff2)
                peak_counter+=1
            index+=1
        print data[counter][1][10][0]
        counter+=1

rawDescription: Python multi-processing

description: Python multi-processing


code:
#! /usr/bin/env python

def get_values(lst):
    sets=map(set,lst)
    common=reduce(lambda x,y:x.intersection(y),sets,set(lst[0]))
    for value in common:
        yield value
if __name__=='__main__':
    e = [[1,2,3,4],range(10000),[4,5,6,7]]
    for common_item in get_values(e):
        print common_item

rawDescription: optimizing conditions for speed

description: Optimizing conditions for speed


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

browser = webdriver.PhantomJS()
browser.set_window_size(1120, 550)
browser.get("http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html")

username = browser.find_element_by_id("navbar_username")
password = browser.find_element_by_name("vb_login_password_hint")

username.send_keys("username")
password.send_keys("password")

browser.find_element_by_class_name("loginbutton").click()

wait = WebDriverWait(browser, 10)
wait.until(EC.visibility_of_element_located((By.XPATH, '//h2[contains(., "Redirecting")]')))
wait.until(EC.title_contains('Kenyan & Tanzanian'))

print(browser.page_source)

print 'success!!'
browser.close()

rawDescription: Scraping with selenium 4

description: Scraping with selenium 4


code:
import numpy as np
from  matplotlib import pyplot
from scipy.optimize import curve_fit

def fn(x, a, b, c):
   return a * np.exp(-b * x) + c

d=np.random.rand(50,2)
M=d[:,0]
A=d[:,1]

fit_vals, fit_errors = curve_fit(fn,M,A)

print ' fit coefficients:\n', fit_vals
print ' Covariance matrix:\n', fit_errors

polynomial = np.poly1d(fit_vals)

xs = np.arange(0,1,0.01)
ys = polynomial(xs)

pyplot.semilogx(M, A,'o', label = "fit")
pyplot.semilogx(xs, ys, label = "fit")

pyplot.xlabel("Magnetic Field,A/m")
pyplot.ylabel("Absorption")
pyplot.title("Magnetic resonance")
pyplot.legend()

pyplot.show()

rawDescription: Lorentz fitting issue

description: Lorentz fitting issue


code:
#
# line segment intersection using vectors
# see Computer Graphics by F.S. Hill
#
from numpy import *
def perp( a ) :
    b = empty_like(a)
    b[0] = -a[1]
    b[1] = a[0]
    return b

# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
# return
def seg_intersect(a1,a2, b1,b2) :
    da = a2-a1
    db = b2-b1
    dp = a1-b1
    dap = perp(da)
    denom = dot( dap, db)
    num = dot( dap, dp )
    return (num / denom.astype(float))*db + b1

p1 = array( [0.0, 0.0] )
p2 = array( [1.0, 0.0] )

p3 = array( [4.0, -5.0] )
p4 = array( [4.0, 2.0] )

print seg_intersect( p1,p2, p3,p4)

p1 = array( [2.0, 2.0] )
p2 = array( [4.0, 3.0] )

p3 = array( [6.0, 0.0] )
p4 = array( [6.0, 3.0] )

print seg_intersect( p1,p2, p3,p4)

rawDescription: Numpy and line intersections

description: Numpy and line intersections


code:
json_object = json.loads(response.text)
for movie in json_object['movies']:
    print movie['movieTitle']

rawDescription: JSON Website response into Python dictionary


code:
import sys, tty, termios

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

key = ""
sys.stdout.write('Password :: ')
while True:
    ch = getch()
    if ch == '\r':
        break
    key += ch
    sys.stdout.write('*')
print
print key

rawDescription: Masking user input in python with asterisks


code:
for index, (value1, value2) in enumerate(zip(data1, data2)):
    print index, value1 + value2

rawDescription: Enumerate two python lists simultaneously?


code:
cn2_learner.target_class = 0 # you can change this to get other classes
cn2_classifier = Orange.classification.rules.RuleLearner.__call__(cn2_learner, train, 0)
#cn2_classifier = cn2_learner(train)

for r in cn2_classifier.rules:
    print Orange.classification.rules.rule_to_string(r)

rawDescription: Can I use Orange CN2 classifier to learn rules for one class only?

description: Use Orange CN2 classifier to learn rules for one class only


code:
import urls # or from app import urls
def print_urls(patterns, indent=0):
    for u in patterns:
        if u.callback:
            print '-'*indent, u.regex.pattern, u.callback
        else:
            print '='*(indent+1), u.regex.pattern
            print_urls(u.url_patterns, indent+3)

print_urls(urls.urlpatterns)

rawDescription: In Django, how do I introspect application urls?


code:
from pybtex.database.input import bibtex
from operator import itemgetter, attrgetter
import pprint
parser = bibtex.Parser()
bib_data = parser.parse_file('ref.bib')

def sort_by_year(y, x):
    return int(x[1].fields['year']) - int(y[1].fields['year'])

bib_sorted = sorted(bib_data.entries.items(), cmp=sort_by_year)

for key, value in bib_sorted:
    print key
    print value.fields['year']
    print value.fields['author']
    print value.fields['title']

rawDescription: converting bibtex files to html with python (maybe pybtex?)

description: Converting bibtex files to html with python (maybe pybtex?)


code:
limit = 10**19 # this change is important because otherwise you will loose 1 solution
# k > limit and exists such i that k - (1 << i) < limit

string = raw_input()
year1, year2 = string.split()
year1 = int(year1)
year2 = int(year2)
x = 1
count = 0
a = []
while True:
    k = 2**x - 1
    if k > limit:
        break

    for i in xrange(x - 1): # k has exactly x bits. So we have only x-1 chances to set zero bit
        if year1 <= k - (1 << i) <= year2:
            count += 1
    x += 1

print count

rawDescription: Why I am getting a one less count always


code:
import re

with open("filename.txt") as f:
    text = f.read()                     # read the whole file

for match in re.finditer(r"\d+", text): # find all strings of consecutive digits
    num = int(match.group())            # convert to integer
    if 1900 <= num <= 2013:             # test boundaries
        print num

rawDescription: Absolutely new to Python. Issue with extracting integers from a textfile


code:
# matrices.py
# This optional case study solves each of the following problems.  Each
# solution uses the solutions to the preceding problems.

# 1) Multiply two matrices
# 2) Invert a matrix
# 3) Solve a system of linear equations
# 4) Fit an exact polynomial to a list of points
# 5) Find the coefficients of the polynomial for a power sum

# This last problem needs a little explaining.  Consider this power sum:
# 1 + 2 + ... + n.  We know this equals n(n+1)/2.  We can represent this
# quadratic function by its coefficients alone, as [1/2, 1/2, 0] (ignoring
# integer division in this explanation).

# Now, the sum of the squares is: 1**2 + 2**2 + ... + n**2.  This is a cubic
# equation.  It happens to be [1/3, 1/2, 1/6, 0].  That is:
# 1**2 + ... + n**2 = (1/3)n**3 + (1/2)n**2 + (1/6)n

# In fact, for positive integer k, 1**k + ... + n**k is a (k+1)-degree
# polynomial.  The problem we are solving is to write a function which takes
# this number k, and returns the coefficients of that polynomial.

# Also, our approach for matrix multiplication needs some slight explaining.
# We basically use Gauss-Jordan Elimination to get reduced row echelon form
# while applying the same elementary row operations to an identity matrix -- in
# so doing, the identity matrix is transformed into the inverse of the original
# matrix.  Amazing!

import copy
from fractions import Fraction

def copyMatrix(m):
    return copy.deepcopy(m)

def makeIdentity(n):
    result = make2dList(n,n)
    for i in xrange(n):
        result[i][i] = Fraction(1, 1)
    return result

def testMakeIdentity():
    print "Testing makeIdentity...",
    i3 = [[1,0,0],[0,1,0],[0,0,1]]
    assert(i3 == makeIdentity(3))
    print "Passed!"

def multiplyMatrices(a, b):
    # confirm dimensions
    aRows = len(a)
    aCols = len(a[0])
    bRows = len(b)
    bCols = len(b[0])
    assert(aCols == bRows) # belongs in a contract
    rows = aRows
    cols = bCols
    # create the result matrix c = a*b
    c = make2dList(rows, cols)
    # now find each value in turn in the result matrix
    for row in xrange(rows):
        for col in xrange(cols):
            dotProduct = Fraction(0, 1)
            for i in xrange(aCols):
                dotProduct += a[row][i]*b[i][col]
            c[row][col] = dotProduct
    return c

def testMultiplyMatrices():
    print "Testing multiplyMatrices...",
    a = [ [ 1, 2, 3],
          [ 4, 5, 6 ] ]
    b = [ [ 0, 3],
          [ 1, 4],
          [ 2, 5] ]
    c = [ [ 8, 26],
          [17, 62 ] ]
    observedC = multiplyMatrices(a, b)
    assert(observedC == c)
    print "Passed!"

def multiplyRowOfSquareMatrix(m, row, k):
    n = len(m)
    rowOperator = makeIdentity(n)
    rowOperator[row][row] = k
    return multiplyMatrices(rowOperator, m)

def testMultiplyRowOfSquareMatrix():
    print "Testing multiplyRowOfSquareMatrix...",
    a = [ [ 1, 2 ],
          [ 4, 5  ] ]
    assert(multiplyRowOfSquareMatrix(a, 0, 5) == [[5, 10], [4, 5]])
    assert(multiplyRowOfSquareMatrix(a, 1, 6) == [[1, 2], [24, 30]])
    print "Passed!"

def addMultipleOfRowOfSquareMatrix(m, sourceRow, k, targetRow):
    # add k * sourceRow to targetRow of matrix m
    n = len(m)
    rowOperator = makeIdentity(n)
    rowOperator[targetRow][sourceRow] = k
    return multiplyMatrices(rowOperator, m)

def testAddMultipleOfRowOfSquareMatrix():
    print "Testing addMultipleOfRowOfSquareMatrix...",
    a = [ [ 1, 2 ],
          [ 4, 5  ] ]
    assert(addMultipleOfRowOfSquareMatrix(a, 0, 5, 1) == [[1, 2], [9, 15]])
    assert(addMultipleOfRowOfSquareMatrix(a, 1, 6, 0) == [[25, 32], [4, 5]])
    print "Passed!"

def invertMatrix(m):
    n = len(m)
    assert(len(m) == len(m[0]))
    inverse = makeIdentity(n) # this will BECOME the inverse eventually
    for col in xrange(n):
        # 1. make the diagonal contain a 1
        diagonalRow = col
        assert(m[diagonalRow][col] != 0) # @TODO: actually, we could swap rows
                                         # here, or if no other row has a 0 in
                                         # this column, then we have a singular
                                         # (non-invertible) matrix.  Let's not
                                         # worry about that for now.  :-)
        k = Fraction(1,m[diagonalRow][col])
        m = multiplyRowOfSquareMatrix(m, diagonalRow, k)
        inverse = multiplyRowOfSquareMatrix(inverse, diagonalRow, k)
        # 2. use the 1 on the diagonal to make everything else
        #    in this column a 0
        sourceRow = diagonalRow
        for targetRow in xrange(n):
            if (sourceRow != targetRow):
                k = -m[targetRow][col]
                m = addMultipleOfRowOfSquareMatrix(m, sourceRow, k, targetRow)
                inverse = addMultipleOfRowOfSquareMatrix(inverse, sourceRow,
                                                         k, targetRow)
    # that's it!
    return inverse

def testInvertMatrix():
    print "Testing invertMatrix...",
    a = [ [ 1, 2 ], [ 4, 5  ] ]
    aInverse = invertMatrix(a)
    identity = makeIdentity(len(a))
    assert (almostEqualMatrices(identity, multiplyMatrices(a, aInverse)))
    a = [ [ 1, 2, 3], [ 2, 5, 7 ], [3, 4, 8 ] ]
    aInverse = invertMatrix(a)
    identity = makeIdentity(len(a))
    assert (almostEqualMatrices(identity, multiplyMatrices(a, aInverse)))
    print "Passed!"

def solveSystemOfEquations(A, b):
    return multiplyMatrices(invertMatrix(A), b)

def testSolveSystemOfEquations():
    print "Testing solveSystemOfEquations...",
    # 3x + 2y - 2z = 10
    # 2x - 4y + 8z =  0
    # 4x + 4y - 7z = 13
    # x = 2, y = 3, z = 1
    A = [ [3,  2, -2],
          [2, -4,  8],
          [4,  4, -7] ]
    b = [ [ 10 ],
          [  0 ],
          [ 13 ] ]
    observedX = solveSystemOfEquations(A,b)
    expectedX = [ [ 2 ],
                  [ 3 ],
                  [ 1 ] ]
    assert(almostEqualMatrices(observedX, expectedX))
    print "Passed!"

def fitExactPolynomial(pointList):
    n = len(pointList)
    degree = n - 1
    # 1. make A
    A = make2dList(n,n)
    for row in xrange(n):
        for col in xrange(n):
            x = pointList[row][0]
            exponent = degree - col
            A[row][col] = x**exponent
    # 2. make b
    b = make2dList(n,1)
    for row in xrange(n):
        y = pointList[row][1]
        b[row][0] = y
    # use system solver to find solution
    return solveSystemOfEquations(A, b)

def testFitExactPolynomial():
    print "Testing fitPolynomialExactly...",
    def f(x): return 3*x**3 + 2*x**2 + 4*x + 1
    expected = [[3], [2], [4], [1]]
    pointList = [(1,f(1)), (2,f(2)), (5,f(5)), (-3,f(-3))]
    observed = fitExactPolynomial(pointList)
    assert(almostEqualMatrices(observed, expected))
    print "Passed!"

def findCoefficientsOfPowerSum(k):
    # Assume f(n) = 1**k + ... + n**k
    # We argued by handwaving-ish-calculusy-stuff that f(n) is
    # a polynomial of degree (k+1)
    # We need (k+2) points to fit just such a polynomial
    pointList = []
    y = 0
    for n in xrange(1,k+3):
        x = Fraction(n, 1)
        # y = 1**k + ... + n**k
        y += x**k
        pointList += [(x,y)]
    return fitExactPolynomial(pointList)

def testFindCoefficientsOfPowerSum():
    print "Testing findCoefficientsOfPowerSum..."
    # Not a formal test here, just printing the answers.
    # Check here for expected values:
    # http://mathworld.wolfram.com/PowerSum.html
    for k in xrange(10):
        print "k = %d:" % k,
        printMatrix(findCoefficientsOfPowerSum(k))
    print "Passed!"

def almostEqualMatrices(m1, m2):
    # verifies each element in the two matrices are almostEqual to each other
    # (and that the two matrices have the same dimensions).
    if (len(m1) != len(m2)): return False
    if (len(m1[0]) != len(m2[0])): return False
    for row in xrange(len(m1)):
        for col in xrange(len(m1[0])):
            if not almostEqual(m1[row][col], m2[row][col]):
                return False
    return True

def almostEqual(d1, d2):
    epsilon = 0.00001
    return abs(d1 - d2) < epsilon

def make2dList(rows, cols):
    a=[]
    for row in xrange(rows): a += [[0]*cols]
    return a

def printMatrix(a):
    def valueStr(value):
        if (isinstance(value, Fraction)):
            (num, den) = (value.numerator, value.denominator)
            if ((num == 0) or (den == 1)): return str(num)
            else: return str(num) + "/" + str(den)
        else:
            return str(value)
    def maxItemLength(a):
        maxLen = 0
        rows = len(a)
        cols = len(a[0])
        for row in xrange(rows):
            for col in xrange(cols):
                maxLen = max(maxLen, len(valueStr(a[row][col])))
        return maxLen
    if (a == []):
        # So we don't crash accessing a[0]
        print []
        return
    rows = len(a)
    cols = len(a[0])
    fieldWidth = maxItemLength(a)
    print "[",
    for row in xrange(rows):
        if (row > 0) and (len(a[row-1]) > 1): print "\n  ",
        print "[",
        for col in xrange(cols):
            if (col > 0): print ",",
            # The next 2 lines print a[row][col] with the given fieldWidth
            format = "%" + str(fieldWidth) + "s"
            print format % valueStr(a[row][col]),
        print "]",
    print "]"

def main():
    testMakeIdentity()
    testMultiplyMatrices()
    testMultiplyRowOfSquareMatrix()
    testAddMultipleOfRowOfSquareMatrix()
    testInvertMatrix()
    testSolveSystemOfEquations()
    testFitExactPolynomial()
    testFindCoefficientsOfPowerSum()

main()

rawDescription: Python multiplication

description: Python multiplication


code:
import math

def compute_lengths(d):
    l = []

    for i in xrange(len( d[ d.keys()[0] ] )):
        ## len is number of inner lists within an outer list

        sum = 0
        for v in d.values():
            sum += (v[i][-1]) ** 2

        l.append(math.sqrt(sum))

    return l

d = {
    'a': [ [0, 3], [1, 3] ],
    'b': [ [0, 4], [1, 2] ]
}

l = compute_lengths(d)
print l

[5.0, 3.605551275463989]

rawDescription: Accessing list of lists within a dictionary in python


code:
class Test:
    def method_one(self):
        print "Called method_one"
    @staticmethod
    def method_two():
        print "Called method_two"
    @classmethod
    def method_three(cls):
        cls.method_two()
class T2(Test):
    @staticmethod
    def method_two():
        print "T2"

a_test = Test()
a_test.method_one()
a_test.method_two()
a_test.method_three()
b_test = T2()
b_test.method_three()

Test.method_two()

T2.method_three()

rawDescription: Overriding a static method in python

description: Overriding a static method in python


code:
import pymssql

from slybot.item import create_item_version

class SQLStore(object):
    def __init__(self):
        self.conn = pymssql.connect(host='XXXXXX', user='sa', password='1timep', database='DBSample')
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        try:
            self.cursor.execute("INSERT INTO Movie(Description, Location,Title) VALUES (%s, %s, %s)",
                                (item['Description'], item['Location'], item['Title']))
            self.conn.commit()
        except pymssql.Error, e:
            print ("error")

        return item

rawDescription: Scrapy pipeline for MSSQL

description: Scrapy pipeline for MSSQL


code:
import random

class CarBase(object):
    pass

class meta_car(type):
    car_brands = {}
    def __init__(cls, cls_name, cls_bases, cls_dict):
        super(meta_car, cls).__init__(cls_name, cls_bases, cls_dict)
        if(not CarBase in cls_bases):
            meta_car.car_brands[cls_name] = cls

    def __call__(self, *args, **kwargs):
        make = kwargs.get("make", "")
        if(meta_car.car_brands.has_key(make) and not (self is meta_car.car_brands[make])):
            obj = meta_car.car_brands[make].__call__(*args, **kwargs)
            if(make == "Toyota"):
                if(random.randint(0, 100) < 2):
                    obj.defect = "sticky accelerator pedal"
            elif(make == "GM"):
                if(random.randint(0, 100) < 20):
                    obj.defect = "shithouse"
            elif(make == "Great Wall"):
                if(random.randint(0, 100) < 101):
                    obj.defect = "cancer"
        else:
            obj = None
            if(not meta_car.car_brands.has_key(self.__name__)):
                new_class = meta_car(make, (GenericCar,), {})
                globals()[make] = new_class
                obj = new_class(*args, **kwargs)
            else:
                obj = super(meta_car, self).__call__(*args, **kwargs)
        return obj

class Car(CarBase):
    __metaclass__ = meta_car

    def __init__(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

    def __repr__(self):
        return "<%s>" % self.description

    @property
    def description(self):
        return "%s %s %s %s" % (self.color, self.year, self.make, self.model)

class GenericCar(Car):
    def __init__(self, **kwargs):
        kwargs["make"] = self.__class__.__name__
        super(GenericCar, self).__init__(**kwargs)

class Toyota(GenericCar):
    pass

colours = \
[
    "blue",
    "green",
    "red",
    "yellow",
    "orange",
    "purple",
    "silver",
    "black",
    "white"
]

def rand_colour():
    return colours[random.randint(0, len(colours) - 1)]

some_cars = \
[
    Car(make="Toyota", model="Prius", year=2005, color=rand_colour()),
    Car(make="Toyota", model="Camry", year=2007, color=rand_colour()),
    Car(make="Toyota", model="Camry Hybrid", year=2013, color=rand_colour()),
    Car(make="Toyota", model="Land Cruiser", year=2009, color=rand_colour()),
    Car(make="Toyota", model="FJ Cruiser", year=2012, color=rand_colour()),
    Car(make="Toyota", model="Corolla", year=2010, color=rand_colour()),
    Car(make="Toyota", model="Hiace", year=2006, color=rand_colour()),
    Car(make="Toyota", model="Townace", year=2003, color=rand_colour()),
    Car(make="Toyota", model="Aurion", year=2008, color=rand_colour()),
    Car(make="Toyota", model="Supra", year=2004, color=rand_colour()),
    Car(make="Toyota", model="86", year=2013, color=rand_colour()),
    Car(make="GM", model="Camaro", year=2008, color=rand_colour())
]

dodgy_vehicles = filter(lambda x: hasattr(x, "defect"), some_cars)
print dodgy_vehicles

rawDescription: Python : Understanding metaclass and inheritance


code:
def b():
    ID = [0, 1, 2]
    ID2 = ('ID=%d.%d.%d' % tuple(ID))
    return ID2

if __name__ == '__main__': ID2 = b()

def c(ID2):
    print ID2

if __name__ == '__main__': myObject = c(ID2)

rawDescription: Storing list variables as a string and storing it as a variable


code:
# don't use `list` as a variable name; it masks the built-in `list` constructor
str_list = ['a b', 'b c d e', 'c', 'd e f g h', 'e f g h i j', 'f g h', 'g h']
for s in str_list:
    split_list = s.split(' ')
    if len(split_list) > 3 and split_list[3] == 'c':
        print "True"
    else:
        print "False"

rawDescription: if item in list exists: do stuff

description: If item in list exists: do stuff


code:
import os
import time
import signal
import sys

class ChildProcess:
  def __init__(self, m):
    self.pid = None
    self.ttl = 10
    self.master = m
    self.pipe_in = None
    self.pipe_out = None

  def hey(self):
    self.ttl -= 1
    self.pipe_out.write('Hello worker %d\n' % self.pid)
    self.pipe_out.flush()

  def tell_me(self):
    msg = self.pipe_in.readline()
    print '[M] Worker process %d says: %s' % (self.pid, msg),

  def live(self):
    r1, w1 = os.pipe()
    r2, w2 = os.pipe()
    pid = os.fork()
    self.pid = pid
    if pid:
      print('[M] Created worker process %d' % pid)
      os.close(w1)
      os.close(r2)
      self.pipe_in = os.fdopen(r1, 'rt')
      self.pipe_out = os.fdopen(w2, 'wt')
      self.master.add(self)
    else:
      print('[W] Worker process ready to rock')
      os.close(r1)
      os.close(w2)
      wr = os.fdopen(w1, 'wt')
      reader = os.fdopen(r2)
      try:
        while True:
          wr.write('Hello Master\n')
          wr.flush()
          msg = reader.readline()
          print('[W] Master says %s' % msg),
      except KeyboardInterrupt:
        sys.exit()

  def die(self):
    print('[W] aghhh ... %d' % self.pid)
    os.kill(self.pid, signal.SIGTERM)

class Master:
  def __init__(self):
    self.workers = []

  def add(self, worker):
    self.workers.append(worker)

  def rulez(self, nbr=2):
    for i in range(nbr):
      worker = ChildProcess(self)
      worker.live()
    while True:
      for w in self.workers:
        w.tell_me()
        time.sleep(1)
        w.hey()

  def reap(self):
    print len(self.workers)
    for w in self.workers:
      w.die()

if __name__ == '__main__':
  master = Master()

  try:
    master.rulez(4)
  except KeyboardInterrupt:
    master.reap()

rawDescription: Python: process printing to the console multiple time after it is killed


code:
import fileinput
import os

# assume script name is unique in the .bashrc context
uniqkey = os.path.basename(__file__)
startupfile = os.path.expanduser('~/.bashrc')
startupline = 'python %s &\n' % os.path.abspath(__file__)

written = False
for line in fileinput.input(startupfile, inplace=1):
    if uniqkey in line:
        if not written:
            written = True
            print startupline, # rewrite
        #else do nothing (it removes duplicate lines)
    else:
        print line,

if not written: # add startup line if it is not present
   open(startupfile,'a').write('\n'+startupline) # ignore possible race condition

rawDescription: Python search through file

description: Python search through file


code:
def show_most_informative_features(vectorizer, clf, n=20):
    feature_names = vectorizer.get_feature_names()
    coefs_with_fns = sorted(zip(clf.coef_[0], feature_names))
    top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])
    for (coef_1, fn_1), (coef_2, fn_2) in top:
        print "\t%.4f\t%-15s\t\t%.4f\t%-15s" % (coef_1, fn_1, coef_2, fn_2)

rawDescription: How to get most informative features for scikit-learn classifiers?

description: Get most informative features for scikit-learn classifiers


code: print u'This is a full block: \u2588'

rawDescription: Python unicode character codes?

description: Python unicode character codes


code:
#!/usr/bin/env python
from twisted.internet import reactor,defer, threads
from twisted.internet.task import LoopingCall
import time

def main_loop():
    print 'doing stuff in main loop.. do not block me!'

def aBlockingRedisCall(x):
    if x<5: #all connections are busy, try later
        print '%s is less than 5, get a redis client later' % x
        x+=1
        d = defer.Deferred()
        d.addCallback(aBlockingRedisCall)
        reactor.callLater(1.0,d.callback,x)
        return d

    else:
        print 'got a redis client; doing lookup.. this may take a while'
        def getstuff( x ):
            time.sleep(3)
            return "stuff is %s" % x

        # getstuff is blocking, so you need to push it to a new thread
        d = threads.deferToThread(getstuff, x)
        d.addCallback(gotFinalResult)
        return d

def gotFinalResult(x):
    return 'final result is %s' % x

def result(res):
    print res

def aBlockingMethod():
    print 'going to sleep...'
    time.sleep(10)
    print 'woke up'

def main():
    lc = LoopingCall(main_loop)
    lc.start(2)

    d = defer.Deferred()
    d.addCallback(aBlockingRedisCall)
    d.addCallback(result)
    reactor.callInThread(d.callback, 1)
    reactor.run()

if __name__=='__main__':
    main()

rawDescription: Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden?


code:
import fileinput

temp_values = []
for line in fileinput.input("weerstation.txt"):
    print line, type(line)
    if 'temperatuur' in line:
        temp_values.append(line.strip().split()[1])  # split the list and just add the temperature

with open("temp_values.txt", "w") as fp:
    fp.write("\n".join(temp_values))                 # save values to temp_values.txt and finish assignment 1

print temp_values
# ['10.4', '10.9', '10.9', '10.9', '11.0', '11.1', '11.3', '11.4', '11.5', '11.5', '12.0', '12.5', '13.0', '13.5', '13.5', '12.5', '10.5', '9.5', '9.0', '9.0', '8.5', '8.25', '7.0', '5.0']

import matplotlib.pyplot as plt                     # using matplotlib to draw figure and finish assignment 2

plt.plot([i for i in xrange(0, 24)], temp_values)
plt.xlabel("Hours")
plt.ylabel("Temperatures")
plt.show()

rawDescription: How to create values from text file

description: Create values from text file


code:
qTable = self.dockwidget.tableWidget
example_group = root.findGroup('Main group')
all_items = []
gis_map = QgsMapLayerRegistry.instance().mapLayersByName( "Map" )[0]
idx = gis_map.fieldNameIndex("Rank")
for row in range(qTable.rowCount()):
    constraint_item = qTable.item(row, 0)
    constraint_name = str(constraint_item.text())
    item = qTable.item(row, 1)
    item_string = str(item.text())
    all_items.append(item_string)
    for group in example_group.children():
        if group.name() == "Sub group":
            if idx == -1:
                if len(set(all_items)) == 1:
                    print 'success'
                else:
                    print 'fail'
            else:
                print constraint_name

rawDescription: Confused by using too many for loops, if and else statements


code:
bn = 5
neighbors = [10, 12, 2, 4]
print bn, ' '.join(map(str, sorted(neighbors)))

rawDescription: python - write formated file without fixed number of variables to print

description: Python - write formated file without fixed number of variables to print


code:
import numpy

a = numpy.array([1, 2, 3, 4, 5, 6])
b = numpy.array([])

sum = 0
for num in a:
    if sum != 6:
       sum += num
       b = numpy.append(b, num)
    else:
       break

print b.astype(int) # [1 2 3]

rawDescription: elements in an array from the sum

description: Elements in an array from the sum


code:
def print_certifications(self):
    print "The supplement %s has the following certifications:" % self.name
    if not self.certifications:  # len(self.certifications) == 0
        print "Sorry, no certifications for this product."
    for certification in self.certifications:
        print certification

rawDescription: Finding length of a list inside an object in python


code:
import subprocess

recipient = 'xxxxx@gmail.com'
subject = 'test'
body = 'testing mail through python'

def send_message(recipient, subject, body):
    try:
      process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    except Exception, error:
      print error
    process.communicate(body)

send_message(recipient, subject, body)

print("sent the email")

rawDescription: Executing shell mail command using python


code:
import networkx as nx

G = nx.DiGraph()
G.add_nodes_from(["Start", "a", "b", "c", "End"])
G.add_edges_from([("Start", "a"), ("Start", "c"), ("a", "b"), ("b", "a"), ("c", "End")])

total_num_nodes = G.number_of_nodes()

if len(nx.shortest_path(G, source="Start")) < total_num_nodes:
    print "\nThis FSM has inaccessible states"
else:
    print "\nAll nodes reachable from 'Start'"

H = G.reverse()
if len(nx.shortest_path(H, source="End")) < total_num_nodes:
    print "\nThis FSM has dead-end states"
else:
    print "\nAll nodes have a path to reach the 'End' state"

rawDescription: Validate reachability of each state in a FSM from a 'start' state and to an 'end' state


code:
result = []
trs = table.findAll("tr")
for tr in trs:
   tds = tr.findAll('td')
   _res = []
   for i in range (0, 6):
       _res.append(tds[i].text)
   result.append(_res)
print result

rawDescription: BeautiFul Soup in django

description: BeautiFul Soup in django


code:
x = 0
def run_5():
    print "5 minutes later"
    x += 5
    return x

x=run_5()
print x

rawDescription: Using a variable outside of function in Python


code:
for question in so.questions(tagged=['python'], pagesize=10):
    print question
    assert 'python' in question.tags

rawDescription: Py-StackExchange filter by tag

description: Py-StackExchange filter by tag


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base, AbstractConcreteBase

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)

class BC(AbstractConcreteBase, Base):
    pass

class B(BC):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)

    a_id = Column(Integer, ForeignKey('a.id'))
    __mapper_args__ = {
        "polymorphic_identity": "b",
        "concrete": True
    }

class C(BC):
    __tablename__ = 'c'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('a.id'))
    __mapper_args__ = {
        "polymorphic_identity": "c",
        "concrete": True
    }

configure_mappers()
A.collection = relationship(BC, primaryjoin=BC.a_id == A.id)

engine = create_engine("sqlite://", echo=True)

Base.metadata.create_all(engine)

sess = Session(engine)

sess.add_all([
    A(collection=[
        B(),
        C(),
        C()
    ]),
    A(collection=[
        B(),
        B()
    ])
])

sess.commit()

for a in sess.query(A):
    for bc in a.collection:
        print a, bc

rawDescription: sqlalchemy polymorphic many-to-many

description: Sqlalchemy polymorphic many-to-many


code:
def foo():
    print "Hello!"

if __name__ == "__main__":
   foo()

rawDescription: Python for C++ or Java Programmer

description: Python for C++ or Java Programmer


code:
for owner in ris:
    for property in owner.properties:
        if property.type == 'attribute':
            print property.name
            print property.content

rawDescription: python. how to get attribute value with libxml2

description: Python. how to get attribute value with libxml2


code:
def messageCB(sess,mess):
    print 'MESSAGE'*100
    nick=mess.getFrom().getResource()
    text=mess.getBody()
    #print mess,nick
    print text

client.RegisterHandler('message',messageCB)

while 1:
    client.Process(1)

rawDescription: How can I get a response with XMPP client in Python

description: Get a response with XMPP client in Python


code:
from PySide.QtCore import *
from PySide.QtGui import *

import sys

class Main(QWidget):

    def __init__(self, parent=None):
        super(Main, self).__init__(parent)

        layout  = QHBoxLayout(self)
        layout.addWidget(QLabel("this is the main frame"))

    def mousePressEvent(self, QMouseEvent):
        #print mouse position
        print QMouseEvent.pos()

a = QApplication([])
m = Main()
m.show()
sys.exit(a.exec_())

rawDescription: How to detect any mouse click on PySide Gui?

description: Detect any mouse click on PySide Gui


code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", port))
s.listen(5)
print "OK."
print "  Listening on port:", port
import subprocess
try:
    while 1:
        con, addr = s.accept()
        try:
            datagram = con.recv(1024)
            if not datagram:
                continue
            print "Rx Cmd:", datagram
            print "Launch:", datagram
            process = subprocess.Popen(datagram, shell=True, stdout=subprocess.PIPE)
            stdout, stderr = process.communicate()
            con.send(stdout)
        finally:
            print "closing connection"
            con.close()
except KeyboardInterrupt:
    pass
finally:
    print "closing socket"
    s.close()

rawDescription: Looping Fget with fsockopen in PHP 5.x

description: Looping Fget with fsockopen in PHP 5.x


code:
import time
import threading

import numpy as np

from traits.etsconfig.etsconfig import ETSConfig
ETSConfig.toolkit = "qt4"

from enable.api import ComponentEditor
from chaco.api import ArrayPlotData, Plot

from traits.api import Event, HasTraits, Instance
from traitsui.api import View, Item

class PlotWindow(HasTraits):

    dataset = Instance(ArrayPlotData)
    plot = Instance(Plot)

    def _dataset_default(self):
        x = np.linspace(0,2*np.pi,200)
        y = np.sin(x)
        plotdata = ArrayPlotData(x=x, y=y)
        return plotdata

    def _plot_default(self):
        plot = Plot(self.dataset, padding=50, border_visible=True)
        plot.plot(('x', 'y'))
        return plot

    def update_display(self, x, y):
        print 'updating', threading.current_thread()
        self.dataset.set_data('x', x)
        self.dataset.set_data('y', y)

    traits_view = View(
        Item('plot', editor=ComponentEditor(size=(400, 400)), show_label=False)
    )

def run_collection(datamodel):
    # this is where I would start and stop my hardware,
    # but I will just call the read function myself here
    for i in range(1,10):
        x = np.linspace(0,2*np.pi,200)
        y = np.sin(x*i)
        datamodel.update_display(x, y)
        time.sleep(0.5)

def main():
    plot = PlotWindow()

    t = threading.Thread(target=run_collection, args=(plot,))
    t.start()

    # Starts the UI and the GUI mainloop
    plot.configure_traits()

    # don't call t.join() as it blocks the current thread...

if __name__ == "__main__":
    main()

rawDescription: Signal fails to emit with Chaco and PyQt


code:
import re

a="This is a testing text and used to test and test and test."
print [m.start() for m in re.finditer(r"\btest\b", a)]
print [m.start() for m in re.finditer(r"\btest and\b", a)]

rawDescription: How to use regex to find a specific word from text and return all occurences?

description: Use regex to find a specific word from text and return all occurences


code: print "I'm inside Python file %s" % __file__

rawDescription: How do I find out the path of the currently executing script?

description: Find out the path of the currently executing script


code:
import lxml.html
import mechanize, cookielib
import multiprocessing as mp

def download(i):
    link = 'http://www.google.com'
    response = browser.open(link)
    tree = lxml.html.parse(response)
    print tree
    return 0

def init(count):
    global browser
    browser = mechanize.Browser()
    cookie_jar = cookielib.LWPCookieJar()
    browser.set_cookiejar(cookie_jar)
    browser.set_handle_equiv(True)
    browser.set_handle_gzip(True)  #warning
    browser.set_handle_redirect(True)
    browser.set_handle_referer(False)
    browser.set_handle_robots(False)
    browser.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),
                               max_time=1)
    browser.addheaders = [('User-agent',
        'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:2.0.1) '
        'Gecko/20100101 Ubuntu/11.04 maverick Firefox/4.0.1')]

    count.value -= 1

if __name__ == '__main__':
    import time
    count = mp.Value('I', mp.cpu_count())
    pool = mp.Pool(count.value, initializer=init, initargs=(count,))
    #wait until all processes are initialized
    while count.value > 0:
        time.sleep(0.1)

    tasks = range(8)
    r = pool.map_async(download, tasks)
    r.wait()

rawDescription: Python: How can I fix this code so it works on Windows?


code:
import types

class C(object):
  def __init__(self):
    print 'init'

class OldC:
  def __init__(self):
    print 'initOld'

c = object.__new__(C)
print c

oc = types.InstanceType(OldC)
print oc

rawDescription: Best way to test instance methods without running __init__

description: Test instance methods without running __init__


rawDescription: Python: Printing unicode characters beyond FFFF


code:
for related_object in A._meta.get_all_related_objects():
    print related_object.model

rawDescription: Get all related model class in django

description: Get all related model class in django


code:
with open(DateTime + '.txt',"a") as text_file:
    for row in table.findAll('tr')[1:]:
        items = row.text.replace(u"kn","")# remove kn so items line up when unpacking
        time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
        data = items.split()[1:7]
        text_file.write(str(data))
        print items

rawDescription: Write an entire html table to a text file


code:
class _ExitCode:
    _exit_codes=["EXIT_CODE","EXIT_CODE_TWO"]
    def __getattr__(self, name):
        if name in _ExitCode._exit_codes:
            return -(_ExitCode._exit_codes.index(name)+1)
        raise AttributeError("Exit code %s not found" % name)

ExitCode=_ExitCode()
print ExitCode.EXIT_CODE #-1

rawDescription: How do you implement 'EXIT_CODES' in python?

description: Implement 'EXIT_CODES' in python


code:
def is_just_outside(fig, event):
    x,y = event.x, event.y
    print x, y
    for ax in fig.axes:
        xAxes, yAxes =  ax.transAxes.inverted().transform([x, y])
        print xAxes, yAxes
        if  (-0.02 < xAxes < 0) | (1 < xAxes < 1.02):
            print "just outside x-axis"
        if  (-0.02 < yAxes < 0) | (1 < yAxes < 1.02):
            print "just outside y-axis"

x = np.linspace(-np.pi,np.pi,100)
y = np.sin(x)
fig = plt.figure()
plt.plot(x,y)
ax = fig.add_subplot(111)
fig.canvas.mpl_connect('button_press_event', lambda e: is_just_outside(fig, e))
plt.show()

rawDescription: Matplotlib: determining when mouse is in axis text rectangle


code:
import operator
def eval_prefix(expr):
    d = {'+': operator.add,
         '-': operator.sub,
         '*': operator.mul,
         '/': operator.div, # for 3.x change this to operator.truediv
         '%': operator.mod}
    for n in range(10):
        d[str(n)] = n
    e = list(d.get(e, None) for e in expr)
    i = 0
    while i + 3 <= len(e):
        o, l, r = e[i:i+3]
        if type(o) == type(operator.add) and type(l) == type(r) == type(0):
            e[i:i+3] = [o(l, r)]
            i = 0
        else:
            i += 1
    if len(e) != 1:
        print 'Error in expression:', expr
        return 0
    else:
        return e[0]

def test(s, v):
    r = eval_prefix(s)
    print s, '==', v, r, r == v

test("+34", 7)
test("*-567", -7)
test("-*33+2+11", 5)
test("-+5*+1243", 14)
test("*+35-72", 40)
test("%3/52", 1)
test("****", 0)
test("-5bob", 10)

rawDescription: Using Python, How can I evaluate an expression in the form of prefix notation compacted?


code:
from rackspace_auth_openstack.plugin import RackspaceAuthPlugin, auth_url_us

from novaclient.client import Client
nova = Client(version = 2,
              username = '******',
              project_id = '******',
              api_key = '******************************',
              region_name = 'DFW',
              auth_system = 'rackspace',
              auth_plugin = RackspaceAuthPlugin(),
              auth_url = auth_url_us(),
              service_type = 'volume') # Right here

print nova.volumes.list()

rawDescription: Getting a list of block storage volumes at Rackspace using novaclient Python API


rawDescription: python: padding punctuation with white spaces (keeping punctuation)

description: Python: padding punctuation with white spaces (keeping punctuation)


code:
s = "Tag: tie, Tag: ball, Tag: honey"
print s.replace("Tag: ", "")

rawDescription: Replace all occurences of one word in string in python


code:
from ast import literal_eval
mr_x = str(x)
quote_pos = mr_x.find("'")
mr_x = '[[' + mr_x[quote_pos:]
x = literal_eval(mr_x)
print x

[['problems', -436, 'have', -448, 'usually', -435, 'found', -452]]

rawDescription: How to acces an existing(!) matrix which partly contains invalid syntax?

description: Acces an existing(!) matrix which partly contains invalid syntax


code:
from sqlalchemy import *
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import FromClause
from sqlalchemy.sql import table, column

class values(FromClause):
    def __init__(self, *args):
        self.list = args

    def _populate_column_collection(self):
        self._columns.update(
            [("column%d" % i, column("column%d" % i))
                    for i in xrange(1, len(self.list[0]) + 1)]
        )

@compiles(values)
def compile_values(element, compiler, asfrom=False, **kw):
    v = "VALUES %s" % ", ".join(
        "(%s)" % ", ".join(compiler.render_literal_value(elem, None) for elem in tup)
        for tup in element.list
    )
    if asfrom:
        v = "(%s)" % v
    return v

if __name__ == '__main__':
    t1 = table('t1', column('a'), column('b'))
    t2 = values((1, 0.5), (2, -0.5)).alias('weights')
    print select([t1, t2]).select_from(t1.join(t2, t1.c.a==t2.c.column2))

rawDescription: VALUES clause in SQLAlchemy

description: VALUES clause in SQLAlchemy


code:
import signal, os

def handleSigTERM(*args):
    print "OMG I'M GETTING KILLED"
    # Do what you want

signal.signal(signal.SIGTERM, handleSigTERM)

print "I'm process:", os.getpid()
while True:
    pass

rawDescription: how to terminate a python2.7 process after executing the desired function while killing that process using linux kill command

description: Terminate a python2.7 process after executing the desired function while killing that process using linux kill command


code:
import re

data = '''[name]bill billy [email]bill.billy@hotmail.com [dob]01.01.81
[name]mark hilly [email]mark.hilly@hotmail.com [dob]02.11.80
[name]gill silly [email]gill.silly@hotmail.com [dob]03.12.79'''

group_matcher = re.compile(r'\[(.*?)\]([^\[]+)')

for line in data.split('\n'):
    o = dict(group_matcher.findall(line))
    print o['email']

rawDescription: Python - trying to capture the middle of a line, regex or split


code:
import statsmodels.tsa.api
import pylab

data = [[ 120.634, 65.766, -402.844, -258.187, 151.982, -370.8 ],
        [ 140.634, 65.766, -402.844, -358.187, 151.982, -370.8 ]]

Y = [data[0] , data[1]]
Vmodel = statsmodels.tsa.api.VAR(zip(*Y))
results = Vmodel.fit(2)
print results.summary()
print results.plot()
results.plot_acorr()
pylab.show()

rawDescription: statsmodels.tsa.api.VAR how to plot the results

description: Statsmodels.tsa.api.VAR how to plot the results


code:
import os
import maya.cmds as cmds
from functools import partial

# Location of Folders

folder_names = ('C:/Users/OCuinn/Dropbox/Maya Scripts/Python Code',
                'C:/Users/OCuinn/Dropbox/Maya Scripts/Mel Code',
                'C:/Users/OCuinn/Dropbox/Maya Scripts')

# Delete the Menu if it already exists
if cmds.menu('PadraigsTools', exists = True):
    cmds.deleteUI('PadraigsTools')

#Creating the GUI
PadraigsTools=cmds.menu('PadraigsTools', p='MayaWindow', label='PadraigsTools')

# The Refresh Function / Refresh the scripts
cmds.menuItem(p=PadraigsTools, l="Refresh", c='PadraigsTools')
cmds.menuItem(p=PadraigsTools, d=1)

# Browse through Directories
cmds.menuItem(p=PadraigsTools, l="Change")
cmds.menuItem(p=PadraigsTools, d=1)

Python = cmds.menuItem("Python",subMenu=1, label='Python')
cmds.setParent(Python, menu=True )
cmds.menuItem(label ='Python Files')

Mel = cmds.menuItem("Mel", subMenu=1, label='Mel', p='PadraigsTools')
cmds.setParent( Mel, menu=True)
cmds.menuItem (label='melFileList.mel')

Plugins = cmds.menuItem("Plugins", subMenu=1, label='Plugins', p='PadraigsTools')
cmds.setParent( Plugins, menu=True)
cmds.menuItem (label='Plugin.mll')

Other = cmds.menuItem("Other", subMenu=1, label='Other', p='PadraigsTools')
cmds.setParent( Other, menu=True)
cmds.menuItem (label='Other', p=Other)

# Searching for Mel and Python Files
def find_files(root, extensions = ('mel', 'py')):
    def clean_path(*p):
        return "/".join(p).replace('\\', '')

    for root, _, files in os.walk(root):
        used = [f for f in files if f.split(".")[-1] in extensions]
        for u in used:
            yield clean_path(root, u)
# Creating a dictionary with given files
def relativize(abs, roots):
    low_roots = map (str.lower, roots) # all lower for comparison
    for root, low_root in zip(roots,low_roots):
        if abs.lower().startswith(low_root):
            return root, abs[len(root):]
    return "", abs

relative_paths = find_files('C:/Users/OCuinn/Dropbox/Maya Scripts/')

root_dict = {}
for item in relative_paths :
    folders, files = relativize(item, ('C:/Users/OCuinn/Dropbox/Maya Scripts/Python Code','C:/Users/OCuinn/Dropbox/Maya Scripts/Mel Code', 'C:/Users/OCuinn/Dropbox/Maya Scripts'))
    if not folders in root_dict:
        root_dict[folders] = []
    root_dict[folders].append(files)

# call this on every button selection
def test(filepath, ignore):
    # maya will send "test(name, False)"; we just ignore the 'False'
    print "Here's where I would reload", filepath

for name in folder_names:
    PadraigsTools = name
    if PadraigsTools:
        PadraigsTools = PadraigsTools.split("/")[-2] # we used trailing slashes
    else:
        PadraigsTools = "root"
    cmds.menu(label = PadraigsTools)
    file_names = root_dict[name]
    file_names.sort()
    for fn in file_names:
        if fn.endswith(".py"):
            cmds.menuItem(label = fn, p="Python", command = partial(test, fn))
        else:
            if fn.endswith(".mel"):
                    cmds.menuItem(label = fn, p="Mel", command = partial(test, fn))

rawDescription: Maya Python - attaching dictionary files to already created submenus


code:
from collections import defaultdict

input = [(1.2,2), (1.2, 6), (1.2, -2), (2,8), (2,7), (2,18)]

indices_dict = defaultdict(lambda: list([[], []]))

for idx, val in enumerate(input):
    indices_dict[val[0]][0].append(idx)
    indices_dict[val[0]][1].append(val[1])

for key in indices_dict:
    y_values = indices_dict[key][1]
    idx_values =  indices_dict[key][0]
    max_idx = idx_values[y_values.index(max(y_values))]
    min_idx = idx_values[y_values.index(min(y_values))]
    print 'Max diff for x=%s is found between points %s and %s' %(key, input[min_idx], input[max_idx])

rawDescription: Finding 'edge cases' in a dataset

description: Finding 'edge cases' in a dataset


code:
f = open("file.txt", "w+")
print f.read()      # prints ''
f.write("Hello")
f.seek(0)
print f.read()      # print 'Hello'
f.close()

rawDescription: Weird behavior when writing and reading file


code:
from random import sample

set_a = set(sample(range(0, 50), 10))
set_b = set(sample(range(0, 50), 10))

print set_a.intersection(set_b) # [3, 4]
print set_a & set_b # sugar for the same thing

rawDescription: Creating two lists and compare the matching


code:
from urllib2 import unquote
bytesquoted = u'å%8f°å%8d%97 è¦ªå%90é¤%90å»³'.encode('latin1')
unquoted = unquote(bytesquoted)
print unquoted.decode('utf8')

rawDescription: Decoding unknown encoded Traditional Chinese character strings using Python


code: print repr(mystringobject)

rawDescription: Replacing Microsoft Word Newline Character in Python


code:
from StringIO import StringIO
import string

inputs = ["10:a stringly",
         "i1234e" ,
         "l1:a1:be",
         "d1:a1:b3:one3:twoe"]

# Constants
DICT_TYPE = 'd'
LIST_TYPE = 'l'
INT_TYPE  = 'i'
TOKEN_EOF = ''
TOKEN_END = 'e'
COLON     = ':'

class BadTypeIndicatorException(Exception):pass

def read_int(stream):

   s = ""

   while True:
      ch = stream.read(1)
      if ch not in [TOKEN_EOF, TOKEN_END, COLON]:
         s += ch
      else:
         break

   return s

def tokenize(stream):

   s = ""

   while True:

      ch = stream.read(1)

      if ch == TOKEN_END or ch == TOKEN_EOF:
         return

      if ch == COLON:
         length = int(s)
         yield stream.read(length)
         s = ""

      else:
         s += ch

def parse(stream):

   TYPE = stream.read(1)

   if TYPE in string.digits:
      length = int( TYPE + read_int(stream) )
      return stream.read(length)

   elif TYPE is INT_TYPE:
      return int( read_int(stream) )

   elif TYPE is LIST_TYPE:
      return list(tokenize(stream))

   elif TYPE is DICT_TYPE:
      tokens = list(tokenize(stream))
      return dict(zip(tokens[0::2], tokens[1::2]))

   else:
      raise BadTypeIndicatorException

for input in inputs:
   stream = StringIO(input)
   print parse(stream)

rawDescription: How to match a string of a certain length with a regex

description: Match a string of a certain length with a regex


code:
class VideoLayer (Layer):
    def __init__(self, video_name):
        super(VideoLayer, self).__init__()

        source = pyglet.media.load(video_name)
        format = source.video_format
        if not format:
            print 'No video track in this source.'
            return

        self.media_player = pyglet.media.Player()
        self.media_player.queue(source)
        self.media_player.play()

    def draw(self):
        self.media_player.get_texture().blit(0, 0)

rawDescription: how to play avi or mpeg video with python cocos2d

description: Play avi or mpeg video with python cocos2d


rawDescription: Python - Extract multiple lists from a list of lists by index


code:
removed = set()                                               # first new line
for root, dirs, files in os.walk(".", topdown=False):
      dirs = [dir for dir in dirs if os.path.join(root, dir) not in removed] # second
      contents = dirs+files
      print root,"contains:",contents
      if len(contents) == 0:
          print 'Removing "%s"'%root
          shutil.rmtree(root)
          removed.add(root)                                   # third new line
      else:
          print 'Not removing "%s". It has:'%root,contents

rawDescription: Why does python's os.walk() not reflect directory deletion?


code:
from scipy import *
from pylab import *

x = r_[0:50]
y1 = sin(2*pi*x/49)
#y2 = cos(2*pi*x/49)
y2 = np.zeros((y1.shape))
for i in range(15,25):
    y2[i] = 0.9
#print len(y1),len(y2)
#y3 = convolve(y2,y1,mode="same")
y3 = convolve(y2,y1)
subplot(2,2,1)
plot(x,y1)
hold(True)
plot(x,y2)
hold(True)
subplot(2,2,2)
print len(x),len(y3)
xx = r_[0:len(y3)]
print len(xx),len(y3)
plot(xx,y3)
hold(True)
show()

rawDescription: convolution of sinus signal with rectangular pulse

description: Convolution of sinus signal with rectangular pulse


code:
reg = re.compile("
([^<]*)	")
value = reg.findall(htmlbody)
print 'Found %i match(es)' % len(value)

rawDescription: Python Regexp problem

description: Python Regexp problem


code:
import itertools

for a,b,c in itertools.product(cc1, cc2, cc3):
    print a,b,c

rawDescription: Python multiple for loops

description: Python multiple for loops


code:
from BeautifulSoup import BeautifulSoup as bs
import urllib as ul

base_url = 'http://www.yellowpages.ca'
data_file = open('yellow_file.txt', 'a')

bt = bs(ul.urlopen(base_url + '/locations/Quebec/Montreal/90014002.html'))

for div in bt.findAll('div', 'ypgCategory'):
    for a in div.findAll('a'):
        link = base_url + a['href']

        bt = bs(ul.urlopen(link), convertEntities=bs.HTML_ENTITIES)

        titles = bt.findAll('span', 'listingTitle')
        phones = bt.findAll('a', 'phoneNumber')

        for title, phone in zip(titles, phones):
            line = '%s   %s\n' % (title.text, phone.text)
            data_file.write(line.encode('utf-8'))
            print line.rstrip()

data_file.close()

rawDescription: Can't decode output from BeautifulSoup in Python


code:
import xml.etree.ElementTree as etree

parser = etree.XMLTreeBuilder()

def end_tag_event(tag):
    node = self.parser._end(tag)
    print node

parser._parser.EndElementHandler = end_tag_event

def data_received(data):
    parser.feed(data)

rawDescription: Non-Blocking method for parsing (streaming) XML in python


code:
import subprocess
import wx

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        self.txt = wx.TextCtrl(self)
        notepad_btn = wx.Button(self, label="Send to Invoice")
        notepad_btn.Bind(wx.EVT_BUTTON, self.onSendInvoice)

        my_sizer = wx.BoxSizer(wx.VERTICAL)
        my_sizer.Add(self.txt, 0, wx.EXPAND|wx.ALL, 5)
        my_sizer.Add(notepad_btn, 0, wx.CENTER|wx.ALL, 5)
        self.SetSizer(my_sizer)

    #----------------------------------------------------------------------
    def onSendInvoice(self, event):
        """"""
        txt = self.txt.GetValue()
        print txt

        # write to file
        with open("invoice.txt", 'w') as fobj:
            fobj.write(txt)

        # open Notepad
        subprocess.Popen(['notepad.exe', 'invoice.txt'])

########################################################################
class MainWindow(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Jobs")
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainWindow()
    app.MainLoop()

rawDescription: wxPython, Getting input from TextCtrl box to send to Notepad

description: WxPython, Getting input from TextCtrl box to send to Notepad


code:
my_list = [('a', 'b'), ('c', 'd')]

for a, _ in my_list:
    print a

rawDescription: python - assistance with "nested" lists

description: Python - assistance with "nested" lists