code:
import pygame
import sys

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

WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )

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

MAIN_BUTTON = 2

KEYBOARD = True
WORDS = False

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

class evt_type(): # UserEvent - types

    PANE     = pygame.USEREVENT + 1
    KEYBOARD = pygame.USEREVENT + 2

class evt_code(): # UserEvent - codes

   KEYBOARD_CLOSED = 100
   PANE_CLICKED = 200

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

class Pane():

    def __init__(self, textToDisplay, rect, screen, fgColor=(0,0,0), bgColor=(255,255,255), mouseoverBgColor=(255,255,0) ):

        self.textToDisplay = textToDisplay
        self.rect = pygame.Rect(*rect)
        self.screen = screen

        # colors

        self.fgColor = fgColor
        self.bgColor = bgColor

        self.mouseoverBgColor = mouseoverBgColor

        self.currentFgColor = self.fgColor
        self.currentBgColor = self.bgColor

        self.font = pygame.font.SysFont('Palace Script MT', 25)

        self.is_movable = True
        self.is_moving = False
    #---------------------------

    def coordinates(self):
        return self.rect

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

    def text(self):
        return self.textToDisplay

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

    def draw(self):
        # background
        self.screen.fill(self.currentBgColor, self.rect)

        # border
        pygame.draw.rect(self.screen, self.currentFgColor, self.rect, 2)

        # text
        self.screen.blit(self.font.render(self.textToDisplay, True, self.currentFgColor), self.rect)

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

    def test_coordinates(self, posx, posy):
        return self.rect.collidepoint(posx, posy)

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

    def event_handler(self, event):

        # standard pane color
        self.currentFgColor = self.fgColor
        self.currentBgColor = self.bgColor

        # if mouse over pane change color

        if event.type == pygame.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                self.currentBgColor = self.mouseoverBgColor

                if self.is_movable and self.is_moving:
                    self.rect.move_ip(event.rel)
                    self.currentBgColor = (0,0,255)

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                if self.is_movable:
                    pygame.event.post(pygame.event.Event(evt_type.PANE, {'code': evt_code.PANE_CLICKED, 'widget': self}))
                self.currentBgColor = (255,0,0)
                self.is_moving = True

        elif event.type == pygame.MOUSEBUTTONUP:
            if self.rect.collidepoint(event.pos):
                self.currentBgColor = self.mouseoverBgColor
            self.is_moving = False

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

class Keyboard():

    Keys = []
    paneLocs = []
    visible = False
    #---------------------------

    def __init__(self, screen):

        self.screen = screen
        self.font = pygame.font.SysFont('Arial', 25)

        self.create()

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

    def create(self):

        letter_code = ord("A")

        for y in range(2):
            for x in range(13):
                lock = (100*x, 100*y, 100, 100)
                self.paneLocs.append(lock)
                self.Keys.append(Pane(chr(letter_code), lock, self.screen, (0,0,0), (0,255,0)))
                self.Keys[-1].is_movable = False
                letter_code += 1

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

    def draw(self):
        for key in self.Keys:
            key.draw()

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

    def event_handler(self, event):

        textToReturn = None

        # let panes handle event
        for key in self.Keys:
            key.event_handler(event)

        if event.type == pygame.MOUSEBUTTONUP:
            posx, posy = event.pos
            for key in self.Keys:
                #print "debug: keyboard.event_handler", posx, posy
                if key.test_coordinates(posx, posy):
                    textToReturn = key.text()

                    print textToReturn

            # if Q was
            if textToReturn == 'Q':
                self.onKeyQ(textToReturn)

        return textToReturn

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

    def onKeyQ(self, text):

        # hide keyboard
        self.visible = False

        # send event to inform main loop that keyboard was closed
        pygame.event.post(pygame.event.Event(evt_type.KEYBOARD, {'code': evt_code.KEYBOARD_CLOSED, 'key':text}))

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

class Application():

    NoOfPanes = 0
    Panes = []

    paneLocs = [(583, 334, 300, 150),
                (633, 150, 200, 125),
                (633, 600, 200, 125),
                (350, 360, 200, 100),
                (925, 360, 200, 100),
                (1000, 150, 150, 100),
                (275, 150, 150, 100),
                (275, 600, 150, 100),
                (1000, 600, 150, 100),
                (75, 350, 200, 100),
                (0, 668, 200, 100)
                ]

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

    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Box Test')

        self.font = pygame.font.SysFont('Arial', 25)
        self.screen = pygame.display.set_mode((1366,768), 0, 32)

        self.show_panes = True

        self.createPanes()

        self.keyboard = Keyboard(self.screen)

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

    def close(self):
        print "pygame quit"
        pygame.quit()
        sys.exit()

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

    def createPanes(self):
        self.addPane("1", WORDS)
        self.addPane("2", WORDS)
        self.addPane("3", WORDS)
        self.addPane("4", WORDS)
        self.addPane("5", WORDS)
        self.addPane("6", WORDS)
        self.addPane("7", WORDS)
        self.addPane("8", WORDS)
        self.addPane("9", WORDS)
        self.addPane("10", WORDS)
        self.addPane("Keyboard", WORDS)

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

    def addPane(self, textToDisplay, keyboardFlag):
        if (not keyboardFlag) and (self.NoOfPanes > 11):
            print("Limit Reached")
        else:
            print(int(self.NoOfPanes))

            if not keyboardFlag:
                self.Panes.append(Pane(textToDisplay, self.paneLocs[self.NoOfPanes], self.screen))
                self.NoOfPanes += 1

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

    def drawPanes(self):
        for Pane in self.Panes:
            Pane.draw()

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

    def mousePosition(self, event):
            if event.type == MAIN_BUTTON:
                self.Pos = event.pos
                return MAIN_BUTTON
            else:
                return False

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

    def event_handler(self, event):

        textToReturn = None

        # let panes handle events
        for pane in self.Panes:
            pane.event_handler(event)

        if event.type == pygame.MOUSEBUTTONUP:
            posx, posy = event.pos
            for pane in self.Panes:
                #print "debug: app.event_handler", posx, posy
                if pane.test_coordinates(posx, posy):
                    textToReturn = pane.text()

                    if textToReturn == "Keyboard":
                        self.keyboard.visible = True
                        self.show_panes = False

                    print textToReturn
        return textToReturn

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

    def run(self):

        clock = pygame.time.Clock()

        RUNNING = True
        while RUNNING:

            # --- events ---

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    RUNNING = False
                    break

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.keyboard.visible = not self.keyboard.visible
                        self.show_panes = not self.show_panes

                if event.type == evt_type.KEYBOARD:
                    print "USEREVENT:: TYPE:", event.type, "CODE:", event.code
                    # event from keyboard
                    if event.code == evt_code.KEYBOARD_CLOSED:
                        # keyboar was closed so I have to show panes
                        self.show_panes = True

                if event.type == evt_type.PANE:
                    print "USEREVENT:: TYPE:", event.type, "CODE:", event.code
                    if event.code == evt_code.PANE_CLICKED:
                        # move to the end - move to top of screen
                        index = self.Panes.index(event.widget)
                        self.Panes.append(self.Panes.pop(index))

                if self.show_panes:
                    self.event_handler(event)

                if self.keyboard.visible:
                    self.keyboard.event_handler(event)

            # --- draws ---

            self.screen.fill(WHITE)

            if self.show_panes:
                self.drawPanes()

            if self.keyboard.visible:
                self.keyboard.draw()

            pygame.display.update()

            # --- FPS ---

            clock.tick(25)

        self.close()

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

Application().run()

rawDescription: why is my code still displaying the old panes?

description: Why is my code still displaying the old panes


code:
for key, elem in testDict.items():
    print key, elem

rawDescription: Python Iterate Dictionary by Index

description: Python Iterate Dictionary by Index


code:
import re

desc_match = re.search(r'''(?sx)
    (?P<loc>Location:.+?)[\n\r]
    (?P<time>Time:.+?)[\n\r]
    (?P<vends>Vendors:.+?)(?:\n\r?){2}''', desc)

if desc_match:
    for gname in ['loc', 'time', 'vends']:
        print desc_match.group(gname)

rawDescription: parsing string - regex help in python

description: Parsing string - regex help in python


code:
def am_i_alive(hit_points):
    if hit_points == 0:
        print 'dead'
    elif hit_points <= 5:
        print 'almost dead'
    else:
        print 'alive'

am_i_alive(20)
am_i_alive(3)
am_i_alive(0)

rawDescription: What are the errors in this code?

description: What are the errors in this code


code:
import os
for root, dirnames, filenames in os.walk("cm3mm/SAM3/src"):
    print "-----"
    print "root =", root
    print "dirnames =", dirnames
    print "filenames =", filenames

rawDescription: How can I use os.walk or any other alternative to traverse folders recursively by the natural name order?

description: Use os.walk or any other alternative to traverse folders recursively by the natural name order


rawDescription: group by on scipy sparse matrix

description: Group by on scipy sparse matrix


code:
a = [6, 7]
b = [6, 7, 8]
for i in b:
    if i in a:
            print '%d in both sets!' %(i)
    else:
            print '%d does not match!' %(i)

rawDescription: Compare unequal lists

description: Compare unequal lists


code:
import clip
print "clipboard contains: %s" % clip.read()

rawDescription: How do I use Tkinter and allow my application to keep the focus?

description: Use Tkinter and allow my application to keep the focus


code:
import pyxb
import Foo

def checkedAppendBar(rs, bar):
    rs.Bar.append(bar)
    bar = rs.Bar[-1]
    try:
        bar.validateBinding()
    except pyxb.ValidationError as e:
        print e.details()
    return bar

rs = Foo.ResultSet()
# Fails:
#bar = checkedAppendBar(rs, pyxb.BIND(name='a'))
bar = checkedAppendBar(rs, pyxb.BIND(name='a', code='42'))

rawDescription: PyXB : Creating More Rigid Instances of Anonymous Types


code: print datetime.time(0, 0, durationTime.seconds).strftime("%M:%S")

rawDescription: How to format duration in Python (timedelta)?

description: Format duration in Python (timedelta)


code:
print len(df[df['Date'] == df['Date'].shift()])
35636

rawDescription: Create a DataFrame with DatetimeIndex with unique values by adding a timedelta


code:
stream = urllib2.urlopen('http://www.example.com')
stream.headers['content-type']
data = stream.read()
print data[:100]

rawDescription: HTTP Banner Grabbing with Python

description: HTTP Banner Grabbing with Python


code:
import boto3

# create the s3 resource
s3 = boto3.resource('s3')

# get the file object
obj = s3.Object('bucket_name', 'key')

# read the file contents in memory
file_contents = obj.get()["Body"].read()

# print the occurrences of the new line character to get the number of lines
print file_contents.count('\n')

rawDescription: Is it possible to loop through Amazon S3 bucket and count the number of lines in its file/key using Python?


code:
import json
json_string = '{"a":"value", "b":"value"},{"a":"value", "b":"value"}'
def parseJson(string):
    parsed_json = None
    try:
        parsed_json = json.loads(string)
        print parsed_json
    except ValueError, e:
        print string, "didnt parse"
        if  "Extra data" in str(e.args):
            newString = "["+string+"]"
            print newString
            return parseJson(newString)

rawDescription: Python -- get at JSON info that's written like XML


code:
bird = Bird()
pipes = pygame.Group()
pipes.add(pipeTop)
pipes.add(pipeBottom)

while True:
    if pygame.sprite.spritecollide(bird,pipes):
        print "Game Over"

rawDescription: Pygame collision detect with object and rect


code:
def process(elem, parent):
   print elem.tag, repr(elem.text), parent.tag if parent is not None else None
   for child in elem:
      process(child, elem)
process(page, None)

rawDescription: Iterating multiple (parent,child) nodes using Python ElementTree


code:
from mock import patch, PropertyMock

class Foo(object):
    f = {'a': 1}

new_foo = Foo()

with patch.object(Foo, 'f', new_callable=PropertyMock) as mock:
    mock.return_value = {'b': 2}
    print new_foo.f

print new_foo.f

rawDescription: How to patch an attribute in an object

description: Patch an attribute in an object


code:
#!/usr/bin/python

import tokenize
import token
import sys

with open(sys.argv[1], 'rU') as f:
    toks = list(tokenize.generate_tokens(f.readline))
    for i in xrange(len(toks) - 1):
        tok = toks[i]
        # print tok
        tok2 = toks[i + 1]
        if tok[0] == token.STRING and tok[0] == tok2[0]:
            print "implicit concatenation in line " \
                "{} between {} and {}".format(tok[2][0], tok[1], tok2[1])

rawDescription: Identifying implicit string literal concatenation


code:
from collections import Counter, defaultdict

test = Counter({(0, 0): 0.25, (-2, -2): 0.125, (-2, 2): 0.125, (2, 2): 0.125, (2, -2): 0.125, (-4, 0): 0.0625, (0, 4): 0.0625, (0, -4): 0.0625, (4, 0): 0.0625})

result = defaultdict(list)
for k,v in test.iteritems():
    result[v].append(k)
print result

#or more readable
for k,v in result.iteritems():
    print k,v

rawDescription: How to group identical collections together

description: Group identical collections together


code:
for envvar in iter(iter(environ).next, None):
    print envvar

rawDescription: python: getting actual environment variables to modify and pass to subprocess

description: Python: getting actual environment variables to modify and pass to subprocess


code:
import math

# Customary to distinguish variables that are unchanging by making them ALLCAP
A_LAMBDA = 1.0
RHO = 0.8
C = 1.0
B = RHO * C / A_LAMBDA
P0 = (1 - (A_LAMBDA*B))
P1 = (1-(A_LAMBDA*B))*(math.exp(A_LAMBDA*B) - 1)

p_value_cache = {0: P0, 1: P1}

def a(n):
    return math.exp(-A_LAMBDA*B) * ((A_LAMBDA*B)**n) / math.factorial(n)

def p(n, p_dict=p_value_cache):
    # return pre-calculated value if p(n) is already known
    if n in p_dict:
        return p_dict[n]

    # Calculate p(n) using modified formula
    p_n = ((p(n-1)
            - (p(0) + p(1)) * a(n - 1)
            - sum(p(j) * a(n + 1 - j) for j in xrange(2, n)))
          / a(0))

    # Save computed value into the dict
    p_dict[n] = p_n
    return p_n

p(6)
print p_value_cache

rawDescription: Solving a mathematical equation recursively in Python


code:
class Tester( object ):
    def method( self ):
        print 'I am a Tester'

rawDescription: How to get the function definition from an object?

description: Get the function definition from an object


code:
import re
pattern = re.compile(r'\d+\/(\d+)') # Group the needed data in the regex pattern
matches = re.search(pattern, div.text)
print matches.group(0)

rawDescription: python beautifulsoup get footer from chinese website

description: Python beautifulsoup get footer from chinese website


code:
print prev_word_list
['lazy', 'big', 'furry']

rawDescription: how to find approximate words in python using find

description: Find approximate words in python using find


code:
#!/usr/bin/env python

wrd = raw_input('Enter a word: ')

for i in range(len(wrd) - 1):
    print wrd[0:i] + wrd[i+1] + wrd[i] + wrd[i+2:]

rawDescription: Get a python slice to reverse the order of only part of a string( Swapping consecutive characters in a string )?


code:
"""
demo of multiple processes doing processing and publishing the results
to a common subscriber
"""
from multiprocessing import Process

class Worker(Process):
    def __init__(self, filename, bind):
        self._filename = filename
        self._bind = bind
        super(Worker, self).__init__()

    def run(self):
        import zmq
        import time
        ctx = zmq.Context()
        result_publisher = ctx.socket(zmq.PUB)
        result_publisher.bind(self._bind)
        time.sleep(1)
        with open(self._filename) as my_input:
            for l in my_input.readlines():
                result_publisher.send(l)

if __name__ == '__main__':
    import sys
    import os
    import zmq

    #assume every argument but the first is a file to be processed
    files = sys.argv[1:]

    # create a worker for each file to be processed if it exists pass
    # in a bind argument instructing the socket to communicate via ipc
    workers = [Worker(f, "ipc://%s_%s" % (f, i)) for i, f \
               in enumerate((x for x in files if os.path.exists(x)))]

    # create subscriber socket
    ctx = zmq.Context()

    result_subscriber = ctx.socket(zmq.SUB)
    result_subscriber.setsockopt(zmq.SUBSCRIBE, "")

    # wire up subscriber to whatever the worker is bound to
    for w in workers:
        print w._bind
        result_subscriber.connect(w._bind)

    # start workers
    for w in workers:
        print "starting workers..."
        w.start()

    result = []

    # read from the subscriber and add it to the result list as long
    # as at least one worker is alive
    while [w for w in workers if w.is_alive()]:
        result.append(result_subscriber.recv())
    else:
        # output the result
        print result

rawDescription: Python Multi-Processing Question?

description: Python Multi-Processing Question


code:
from scipy.ndimage import imread
image2 = imread('gray.jpg')
print image2.shape

rawDescription: In OpenCV (Python), why am I getting 3 channel images from a grayscale image?


code:
import subprocess

proc = subprocess.Popen("./echotest",
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE)

proc.stdin.write('abc')
message = proc.stdout.read(3)
print "return message ->" + message + " written by python \n"
proc.stdin.write('q')
proc.wait()

rawDescription: piping binary data between python and c++

description: Piping binary data between python and c++


code:
_sentinel = object()

class example_class():
    _example_text_default = 'I print this: '
    def example_function(self, number, text=_sentinel):
        if text is _sentinel:
            text = self._example_text_default
        print text, number

rawDescription: How to change default of function parameter for an instance of an object?

description: Change default of function parameter for an instance of an object


code:
with open(inputfilename) as inputfile:
    words = []
    for line in inputfile:
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        word, positions = line.split(':')
        words.extend((int(p), word) for p in positions.split(','))

print ' '.join([w for p, w in sorted(words)])

rawDescription: Turning a text file with words and their positions into a sentence


code:
def logDecorator(func):

    def wrapper(*args, **kwargs):
        print "Before", func.__name__
        ret = func(*args, **kwargs)
        print "After", func.__name__
        return ret

    return wrapper

class MyClass(object):

    @logDecorator
    def mymethod(self):
        print "xxx"

MyClass().mymethod()

rawDescription: How do I add a method with a decorator to a class in python?

description: Add a method with a decorator to a class in python


code:
import pdb

def Pdb_reset_list(self, arg):
    self.lineno = None
    print >>self.stdout, "Reset list position."
pdb.Pdb.do_reset = Pdb_reset_list
pdb.Pdb.do_rl = Pdb_reset_list

a = 1
b = 2

pdb.set_trace()

print a, b

rawDescription: In pdb how do you reset the list (l) command line count?


code:
n = int(input("Insert a number: "))
nums = range(1,n+1)
print sum(nums)

rawDescription: Python. Using input and while

description: Python. Using input and while


code:
from jinja2 import Template
template = Template('''
{% for column in LINKS|sort|slice(3) %}

    {% for name, link in column %}

{{ name }}

    {% endfor %}

{% endfor %}
''')
links = [
    ('Foo', 'link/to/foo'),
    ('Bar', 'link/to/bar'),
    ('Spam', 'link/to/spam'),
    ('Ham', 'link/to/ham'),
    ('Eggs', 'link/to/eggs'),
]
print template.render(LINKS=links)

rawDescription: Split AND sort list Jinja/Pelican

description: Split AND sort list Jinja/Pelican


code:
import nltk
import csv
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

def stop_Words(fileName,fileName_out):
    file_out=open(fileName_out,'w')
    with open(fileName,'r') as myfile:
        for line in myfile:
            stop_words=set(stopwords.words("english"))
            words=word_tokenize(line)
            filtered_sentence=[""]
            for n in words:
                if n not in stop_words:
                    filtered_sentence.append(""+n)
            file_out.writelines(filtered_sentence+["\n"])
    print "All Done SW"

rawDescription: How to read a CSV file line by line and store it to new CSV file on new row every time?

description: Read a CSV file line by line and store it to new CSV file on new row every time


code:
r = Test()
print r.__dict__
print Test.__dict__
print getattr(r,'test1')

rawDescription: How to get all attribute in class?

description: Get all attribute in class


code:
def handy(self, play_deck):
    a = raw_input('How many hands? ')
    for i in range(int(a)):
        h = "hand" + str(i+ 1) # dynamilly create key
        q, play_deck = self.deal(self.full_deck) # pull cards from deck
        self.dict_of_hands.setdefault(h, q) # load up dict of hands

    hand_keys = self.dict_of_hands.keys()
    the_hands = self.dict_of_hands

    first_cards = []
    second_cards = []
    for hand in the_hands:
        # print the_hands[hand][0]
        first_cards.append(the_hands[hand][0])

    for hand in the_hands:
        # print the_hands[hand][1]
        second_cards.append(the_hands[hand][1])

    header = self.dict_of_hands.keys()

    table = texttable.Texttable()
    table.header(header)
    table.add_rows([first_cards, second_cards], header=False)
    print table.draw()

rawDescription: Python: how do I dynamically print a table of strings in the terminal?


rawDescription: When I read csv, I want to save specified row


code:
import collections
Nationalities = collections.namedtuple('Nationalities',
                                       ['Poland', 'France', 'Germany'])
nat = Nationalities('PL', 'FR', 'DE')
print nat.Poland
print nat.index(nat.Germany)

rawDescription: Convert enum to int in python

description: Convert enum to int in python


code:
import math as M
frct = M.sqrt(2)

for i in range(7):
    frct = 1 / (frct - int(frct))
    print 'Attempt %d: %.20f' % (i, frct)

rawDescription: Python code on continued fractions

description: Python code on continued fractions


code:
from lxml import objectify

root = objectify.fromstring(xml_string)

paras = [p.text for p in root.abstract.para]
keywords = [k.text for k in root.keywordSet.keyword]

print paras
print keywords

rawDescription: Handling nested elements with Python lxml


code:
import re
import codecs

with codecs.open('projectsinline.txt', 'r', encoding="utf-8") as f:
    for line in f:
        unicode_pattern = re.compile(r'\b\w{6}\b', re.UNICODE)
        result = unicode_pattern.findall(line)
        for word in result:
            print word

rawDescription: Encode Python list in order to use re module


code:
import re
from bs4 import BeautifulSoup

data = """

"""

soup = BeautifulSoup(data)

pattern = re.compile(r"javascript:Set_Variables\('(\w+)','(\w+)'")
for a in soup('a'):
    match = pattern.search(a['href'])
    if match:
        print match.groups()

rawDescription: python BeautifulSoup finding certain things in a table

description: Python BeautifulSoup finding certain things in a table


code:
my_users = build_row("users",["username","password","avatar"])
my_users = my_users()  #if you need to operate on an instance.... but class method would be better
#users is the name of a table already in our database, whose columns are username,password, and avatar
db=sqlite3.connect("some_database.sql")
for user in my_users.retrieve(db.cursor(),"username='bob'"):
    print user #something like users_record({'username':'bob','password':'123%gw','avatar':None)
    print user.username #bob
    print user.avatar #None
    print user.password #whatever
    print user.blah #Error!!!!

rawDescription: Add method to class returned by function


code:
class printclass():
    string="yes"

    def __init__(self):
        self.dotheprint()

    def dotheprint(self):
        print self.string

printclass()

rawDescription: Call a function inside a class when calling the class in python


code:
_initialized=False
def initialize(path=None):
  if _initialized:
    if path:
      raise ValueError, "initialize called after first use"
    return
  if path is None:
    path = default_path
  load_dll(path)
  determine_features()

rawDescription: Parameterising an import statement

description: Parameterising an import statement


code:
game = lottery()
print game.list()

rawDescription: recursive function in class in python

description: Recursive function in class in python


code:
import glob
import os
import io
#import csv
#fileWriter = csv.writer(open('inventory.csv', 'wb'), delimiter=',')
#fileWriter.writerow(["Computer Name", "Service Tag"])
for filename in glob.glob('*.txt'):
    content = io.open(filename, encoding='utf-16')
    lines = content.readlines()
    computer_name = os.path.splitext(filename)[0]
    service_tag = lines[1]
    row = [computer_name, service_tag]
    print service_tag
    print row
    #fileWriter.writerow(row)

rawDescription: How do I properly format this string in Python?

description: Properly format this string in Python


rawDescription: Python convert list to tree representation format


code:
for k, v in Counter('abbba').iteritems():
  print k, v

rawDescription: How to iterate over the elements of a map in python

description: Iterate over the elements of a map in python


code:
import sys

MAX_NUMLINES = 7
counter = 0

class TooMuchLine(Exception):
    pass

def tracer(frame, event, arg):
    global counter
    if event == "line":
        counter += 1
        print "counter", counter
        if counter > MAX_NUMLINES:
             raise TooMuchLine()

    return tracer

def badfunc():
    while True:
      import time
      time.sleep(1)

sys.settrace(tracer)

print 'start'

try:
   badfunc()
except TooMuchLine:
   print 'stopped'

print 'done'

rawDescription: Python / Tracing - How to stop a function's execution (return from it ) from within a tracer


code:
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import cElementTree as ET

def get_root_tag_from_xml_file(xml_file_path):
    result = f = None
    try:
        f = open(xml_file_path, 'rb')
        for event, elem in ET.iterparse(f, ('start', )):
            result = elem.tag
            break
    finally:
        if f: f.close()
    return result

if __name__ == "__main__":
    import sys, glob
    for pattern in sys.argv[1:]:
        for filename in glob.glob(pattern):
            print filename, get_root_tag_from_xml_file(filename)

rawDescription: How to obtain the root of a tree without parsing the entire file?

description: Obtain the root of a tree without parsing the entire file


code:
import pyparsing as pypar
import itertools

def python_equiv(s):
    return s.replace('||',' or ').replace('&&',' and ')

def substitute(s,truth_table, VARS):
    for v,t in zip(VARS,truth_table):
        s = s.replace(v,t)
    return s

def check_statements(A1,A2):
    VARS = set()
    maths    = pypar.oneOf("( ! = | & )")
    keywords = pypar.oneOf("and or")
    variable = pypar.Word(pypar.alphanums)
    variable.setParseAction(lambda x: VARS.add(x[0]))
    grammar  = pypar.OneOrMore(maths | keywords | variable)

    # Determine the variable names
    grammar.parseString(A1)
    grammar.parseString(A2)

    A1 = python_equiv(A1)
    A2 = python_equiv(A2)

    bool_vals = map(str, [False,True])

    for table in itertools.product(bool_vals,repeat=len(VARS)):
        T1 = substitute(A1,table,VARS)
        T2 = substitute(A2,table,VARS)
        if eval(T1) != eval(T2):
            print "FAIL AT ", table,
            return False

    print "Statements equiv:",

    return True

# Original example
A1 = '''((op1 != v1) || ((op2 != v2) || (op3 != v3)))'''
A2 = '''((op2 != v2) ||  (op1 != v1) || (op3 != v3))'''
print check_statements(A1,A2)

# Example with a failure
A1 = '''((op1 != v1) || ((op2 != v2) || (op3 != v3)))'''
A2 = '''((op2 != v2) ||  (op1 != v1) && (op3 != v3))'''
print check_statements(A1,A2)

rawDescription: Check if two "simple" 'if statements' in C are equivalent


code:
def tree_map(f, o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        return type(o)(tree_map(f, value, tree_types) for value in o)
    else:
        return f(o)

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print tree_map(lambda o: type(o).__name__, data)
# prints [('int', 'int', ('int', 'int', ('int', 'str'))), ('int', 'int', 'int'), ('int',), 'int', ('int', ('int', ('str',)))]

rawDescription: Traversing a "list" tree and get the type(item) list with same structure in python?


code:
import glob
import os.path

dir = '.'
files = glob.glob(os.path.join(dir, '*.mp4'))
print files

rawDescription: listdir a directory and find if a file name that endswith ".mp4""

description: Listdir a directory and find if a file name that endswith ".mp4""


code:
eq7 = eq6.replace('=', '==')
if eval(eq7) == True:
    print 'test1'
    print eq7
else:
    print 'oops1'
    print eq7

rawDescription: Advice on a simple algebra solver(python)


code:
myfile = open("/Users/it/Desktop/Python/In-Class Programs/countries.csv", "rb")

countries = []
for line in myfile:
    country_name = line.split(",")[1]
    value_of_interest = float(line.split(",")[3])
    countries.append(
        {"Country Name": country_name,
         "Value of Interest": value_of_interest})

ave_value = sum([country["Value of Interest"] for country in countries])/len(countries)
max_value = max([country["Value of Interest"] for country in countries])
min_value = min([country["Value of Interest"] for country in countries])

print "Country Average == ", ave_value
for country in countries:
    if country["Value of Interest"] == max_value:
        print "Max == {country}:{value}".format(country["Country Name"], country["Value of Interest"])
    if country["Value of Interest"] == min_value:
        print "Min == {country}:{value}".format(country["Country Name"], country["Value of Interest"])

rawDescription: Find max number in .CSV file in Python

description: Find max number in .CSV file in Python


code:
from collections import defaultdict

import csv

with open('path/to/file') as infile:
    answer = defaultdict(int)
    for row in csv.reader(infile, delimiter="|"):
        for field in row:
            answer[field] += 1

for k in sorted(answer, key=lambda k: answer[k]):
    print answer[k], "times", k

rawDescription: Parsing specific fields and counting the occurrence with python


code:
fullstr = "my|name|is|will"
begin = fullstr.index('|')+1
end = fullstr.index('|', begin)
print fullstr[begin:end]

rawDescription: Getting Substring in Python

description: Getting Substring in Python


code:
#!/usr/bin/python
import sys
if sys.argv[1] == 'tdi': print '~/long/tedious/path/to/tdi'
elif sys.argv[1] == 'xyz':  print '~/long/tedious/path/to/xyz'

rawDescription: Change working directory in shell with a python script


code:
from itertools import repeat
print zip([1,2], repeat(123))
# [(1, 123), (2, 123)]

rawDescription: Why does zip on a generator return just one item?


code: print MyClass().some_method

rawDescription: Possible to change a Python method's __str__() attribute?


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

import ast
import sys

with open(sys.argv[0], 'r') as my_source:
    my_ast = ast.parse(my_source.read())

print ast.dump(my_ast)

rawDescription: Recommended Compiler Parse Tree Data Structure


code:
import threading
import time

class MonitoringThread(threading.Thread):
    def __init__(self, interval, dict):
        super(MonitoringThread, self).__init__()
        self._continue = True
        self._interval = interval
        self._dict = dict

    def stop(self):
        self._continue = False

    def run(self):
        while self._continue:
            print self._dict
            time.sleep(self._interval)

def main():
    data_dict = {'test': 0}

    t = MonitoringThread(10, data_dict)
    t.start()

    try:
        while True:
            time.sleep(1)
            data_dict['test'] += 1  # Example update
    except:
        t.stop()

if __name__ == '__main__':
    main()

rawDescription: Running a timer in python forever

description: Running a timer in python forever


code:
def retrieve(self):
    db = TinyDB('entry.json')
    f = db.search(Query().time != 0)[0]
    print f

rawDescription: How to save information to json as array python

description: Save information to json as array python


code:
def myHandler():
  print "Whoa! Watchdog expired. Holy heavens!"
  sys.exit()

watchdog = Watchdog(y, myHandler)

def doSomethingRegularly():
  # make sure you do not return in here or call watchdog.reset() before returning
  watchdog.reset()

rawDescription: How to implement a watchdog timer in Python?

description: Implement a watchdog timer in Python


code:
x = raw_input("Starting Month: ").lower()

if x == "january":
   stMonth = '00'
elif x == "february":
    stMonth = '01'
elif x == "march":
    stMonth = '02'
elif x == "april":
    stMonth = '03'
elif x == "may":
    stMonth = '04'
elif x == "june":
    stMonth = '05'
elif x == "june":
    stMonth = '06'
elif x == "august":
    stMonth = '07'
elif x == "september":
    stMonth = '08'
elif x == "october":
    stMonth = '09'
elif x == "november":
    stMonth = '10'
elif x == "december":
    stMonth = '11'
else:
    print "error"
print stMonth

rawDescription: Python - Novice: Why this simple if-elif (replication of the C case block) always produces the same result?


code:
import hashlib
hashes_to_crack = ["5badcaf789d3d1d09794d8f021f40f0e", "d0763edaa9d9bd2a9516280e9044d885", "8621ffdbc5698829397d97767ac13db3"]
dict_file = "dict.txt"

def main(hash_to_crack):
    with open(dict_file) as fileobj:
        for line in fileobj:
            line = line.strip()
            if hashlib.md5(line).hexdigest() == hash_to_crack:
                print "Successfully cracked the hash %s: It's %s" % (hash_to_crack, line)
                return ""
    print "Failed to crack the file."

if __name__ == "__main__":
    for hashToCrack in hashes_to_crack:
        main(hashToCrack)

rawDescription: Python MD5 Hash Passwords and Dictionary


code:
from lxml import etree

data = """<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to> Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
"""

tree = etree.fromstring(data)
print [item.tag for item in tree.xpath('//*')]

rawDescription: List of distinct XML element names using BeautifulSoup


code:
import zmq
import threading
import time

def receive():
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.bind("tcp://127.0.0.1:5000")
    socket.setsockopt(zmq.SUBSCRIBE, '')
    while True:
        print 'Parent received: %s' % socket.recv()

threading.Thread(target=receive).start()

def send(data):
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.connect("tcp://localhost:5000")
    while data:
        socket.send('Sender: %i' % data)
        data -= 1
        time.sleep(1)

rawDescription: communication with 0mq

description: Communication with 0mq


code:
import fileinput
for line in fileinput.input('file.html', inplace = True):
   #do something with line
   print line  #writes the line back to 'file.html'

rawDescription: How to modify file contents as string whilst having access to methods effecting lines within string?

description: Modify file contents as string whilst having access to methods effecting lines within string


code:
for line in output.split("\n"):
    value = None
    metric = ""
    for word in line.split():
        if word.isdigit():
            value = int(word)
        else:
            metric = metric + " " + word
    print "%s => %s" % (metric.strip(":"), str(value))

rawDescription: Python Regex Either/Or within Line

description: Python Regex Either/Or within Line


code:
all_stems = {
 'chair' : set(['high', 'arm']),
 'charge': set(['over', 'under']),
 'fall'  : set(['down', 'water', 'night']),
 'up'    : set(['lock', 'crack', 'vote']),
 'down'  : set(['lock', 'crack', 'fall']),
}

endings     = all_stems.keys()
stem_sets   = all_stems.values()

i = 0
for target_stem_set in stem_sets:
    i += 1
    j  = 0

    remaining_stems = stem_sets[i:]
    for remaining_stem_set in remaining_stems:
        j += 1
        union = target_stem_set & remaining_stem_set
        if len(union) > 1:
            print "%d matches found" % len(union)
            for stem in union:
                print "%s%s" % (stem, endings[i-1])
                print "%s%s" % (stem, endings[j+i-1])

rawDescription: Finding combinations of stems and endings


code:
table1 = {'item1': {'quantity': 3, 'value': 3.0}, \
          'item2': {'quantity': 10, 'value': 30} \
          }

table2 = {'item1': {'quantity': 5, 'value': 5.0}, \
          'item3': {'quantity': 7, 'value': 10.5} \
          }

for key, val in table2.items():
   if key not in table1:
       table1[key] = val
   else:
       for k, v in val.items():
           if k not in table1[key]:
               table1[key][k] = v
           else:
               table1[key][k] += v

print table1

rawDescription: Add values in two dictionaries together on same key


code:
class O2(object):
    __metaclass__ = ObservingMeta

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

    @on_event_method
    def eventx(self, data):
        print self.name + " Event: " + data

rawDescription: How to use decorator in observer pattern for Python 2.7

description: Use decorator in observer pattern for Python 2.7


rawDescription: Python native parsing of path names with unknown path separators


code:
text = \
"""a b c d e
f g h i j
k l m n o
p q r s t"""

# Translate file to matrix (list of lists)
matrix = map(lambda x: x.split(" "), text.split("\n"))

# Determine height and height of matrix
height = len(matrix)
width = len(matrix[0])

# Choose two (unique) numbers for transposing the first two columns
transpose_list = sample(xrange(0, height), 2)

# Now build a new matrix, transposing only the first two
# columns.
new_matrix = []
for y in range(0, height):
    row = []
    for x in range(0, 2):
        transpose = (y + transpose_list[x]) % height
        row.append(matrix[transpose][x])

    for x in range(2, width):
        row.append(matrix[y][x])

    new_matrix.append(row)

# And create a list again
new_text = "\n".join(map(lambda x: " ".join(x), new_matrix))
print new_text

rawDescription: Python - Shuffling a list with constraints


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

rawDescription: converting scrapy to lxml

description: Converting scrapy to lxml


code:
def validation_check():
    input_rna = raw_input("Type RNA sequence: ").upper()
    if re.match(r"^[AUGCT]+$", input_rna):
        print("Correct! That is a valid sequence.")
        print translate(input_rna)
    else:
        print("That is not a valid RNA sequence, please try again.")
        validation_check()

rawDescription: RNA to PROTEIN program questions

description: RNA to PROTEIN program questions


code:
def g():
        n=6
        iters = 1000
        S=np.repeat(list(itertools.product([-1,1], repeat = n+1)),iters, axis=0).reshape((-1,n+1))
        F=np.random.choice(np.array([-1,0,0,1], dtype=np.int8), size = (iters*(2**(n+2)),n)) #oversampling
        F=F[~(F==0).all(1)][:iters*(2**(n+1))]
        FS=np.asanyarray(map(lambda x, y: np.convolve(x, y, 'valid'), F, S))
        firstzero=(FS[:,0]==0).sum()
        bothzero=(FS==0).all(1).sum()
        print "firstzero",    firstzero
        print "bothzero",  bothzero

rawDescription: How to speed up numpy code

description: Speed up numpy code


code:
def liner2(fh,eol,lenchunk,nl=0):
    L = len(eol)
    NL = len(eol) if nl else 0
    chunk = fh.read(lenchunk)
    tail = ''
    while chunk:
        last = chunk.rfind(eol)
        if last==-1:
            kept = chunk
            newtail = ''
        else:
            kept = chunk[0:last+L]   # here: L
            newtail = chunk[last+L:] # here: L
        chunk = tail + kept
        tail = newtail
        x = y = 0
        while y+1:
            y = chunk.find(eol,x)
            if y+1: yield chunk[x:y+NL] # here: NL
            else: break
            x = y+L # here: L
        chunk = fh.read(lenchunk)
    yield tail

fh = open('fofo.txt', 'rb')
te = clock()
for line in liner2(fh,':;:', 65536):
    pass
print clock()-te

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


code:
import signal
import sys

count = 0

def handler(signum,frame):
    global count
    print "Value of 'i' is",i
    count += 1
    if count >= 2:
        sys.exit(0)

signal.signal(signal.SIGINT,handler)
i = 0
while True:
    i += 1

rawDescription: Python - Print a value without intterupting a loop/function


code:
class Foo(object):
     def bar(self, arg1, arg2):
         print arg1, arg2

foo = Foo()
# this:
foo.bar(1,2)  # prints '1 2'
# does about the same thing as this:
Foo.__dict__['bar'].__get__(foo, type(foo))(1,2)  # prints '1 2'

rawDescription: How does a classmethod object work?

description: How does a classmethod object work


code:
valid_doors = {"door 1" : 1.0, "door 2" : 2.0, "door 3" : 3.0, "door 4": 4.0}

x = raw_input("Enter first door: ")
y = raw_input("Enter second door: ")

if x in valid_doors and y in valid_doors:
    print abs(valid_doors[x] - valid_doors[y]) * 2.5
else:
    print 'not a door'

rawDescription: Distance of different points on a list

description: Distance of different points on a list


code:
from win32com.client import Dispatch

xl= Dispatch("Excel.Application")
xl.Visible = True # otherwise excel is hidden

# newest excel does not accept forward slash in path
wb = xl.Workbooks.Open(r'U:\Example.xls')
print "count of sheets:", wb.Sheets.Count
for sh in wb.Sheets:
    print sh.Name
wb.Close()
xl.Quit()

rawDescription: pywin32 excel find how many sheets are in a workbook and index by number?

description: Pywin32 excel find how many sheets are in a workbook and index by number


code:
u = u'\xd0\xb8\xd1\x81\xd0\xbf\xd1\x8b\xd1\x82\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5'
print u.encode('latin-1').decode('utf-8')

rawDescription: Non-latin text outputting as nonsense in Python


code:
#!/usr/bin/python
import collections
Job = collections.namedtuple('Job', ['title', 'salary'])
salaries = {}
with open("jobs.txt", "r") as job_file:
    headers = job_file.readline()
    for line in job_file:
        (title, fsal) = line.rstrip().split('\t')
        fsal = float(fsal.replace('"', '').replace(',', ''))
        if title in salaries:
            salaries[title].append(fsal)
        else:
            salaries[title] = [fsal]
average = lambda alist: sum(alist) / len(alist)
average_salaries = [Job(title, average(salaries[title]))
                    for title in salaries]
sorted_salaries = sorted(
    average_salaries, key=lambda job: job.salary, reverse=True)
for i, j in enumerate(sorted_salaries):
    print '%i. %s \t%g' % (i + 1, j.title, j.salary)

rawDescription: Finding and sorting average in list

description: Finding and sorting average in list


code:
s = '''www.something.com

get the 2 above

www.somethingss.com

get the 2 above

www.somethingssss.com

get the 2 above'''

s = s.splitlines()
for i, line in enumerate(s):
    if 'get the 2 above' in line:
        print s[i-1], s[i-2]

rawDescription: How to get two line above a selected string?

description: Get two line above a selected string


code:
import sympy as sp

A, B1, B2, C = sp.symbols("A, B1, B2, C")

chain1 = [(A,0,1,5),(B1,1,.4,4),(C,0,0.4,0)]
chain2 = [(A,0,1,5),(B2,2,.6,6),(C,0,0.6,0)]
master_chain = [chain1, chain2]

finals = {}
for subchain in master_chain:
    for i, (species, number, decay_prob, half_life) in enumerate(subchain):
        input_species = sp.Symbol(str(species) + "_i")
        if species not in finals:
            finals[species] = -input_species / half_life if half_life else 0
        if i < len(subchain) - 1:
            (other_species, other_number, other_decay_prob, other_half_life) = subchain[i+1]
            if other_species not in finals:
                finals[other_species] = -sp.Symbol(str(other_species) + "_i") / other_half_life if other_half_life else 0
            finals[other_species] += input_species * decay_prob / half_life

print finals

rawDescription: Generate system of equations

description: Generate system of equations


code:
def sortkey(x):
    print x
    return x
inputlist = range(5)
random.shuffle(inputlist)
sorted(inputlist, key=sortkey)

rawDescription: Explaination of this lambda function please?


code: print MyClass.__dict__

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


code:
class OSMap(object):
    def __init__(self, os = "", version = ""):
        self.os = os
        self.version = version

os_map = dict()
os_map["A"] = OSMap("Windows", "7")
os_map["B"] = OSMap("Ubuntu", "13.10")
print os_map["A"].version, os_map["A"].os
print os_map["B"].version, os_map["B"].os

rawDescription: Python datastructure for map like access


code:
path = '/home/chris/sources/a/b/c/d/e/test.py'.split('/')
if 'sources' in path:
    print '/'.join(path[:path.index('sources') + 1])

rawDescription: Path manipulation

description: Path manipulation


rawDescription: Working with large primes in Python

description: Working with large primes in Python


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

PLT_PAGE_NUM = 39 # default is 39
SUB_PLT_NUM = 20 # default is 20
TIME_LENGTH = 1000

xcor_real_arr = np.random.random((SUB_PLT_NUM*PLT_PAGE_NUM,TIME_LENGTH))
xcor_imag_arr = np.random.random((SUB_PLT_NUM*PLT_PAGE_NUM,TIME_LENGTH))
for pp in xrange(0,PLT_PAGE_NUM):

    plt.figure(figsize=(20,12))

    start_time = time.time()
    for kk in xrange(0,SUB_PLT_NUM):
        plt.subplot(5,4,kk+1)
        plt.plot(np.arange(0,TIME_LENGTH), xcor_real_arr[SUB_PLT_NUM*pp+kk,0:],'r-',
                 range(0,TIME_LENGTH), xcor_imag_arr[SUB_PLT_NUM*pp+kk,0:],'b-')
        plt.title('XCOR of '+ str(SUB_PLT_NUM*pp+kk), color='k')

    plt.savefig('test_imag_real'+str(pp)+'.png',format='png',dpi=100)
    print 'Fig-'+str(pp)+' has been saved'
    print "Excution time:", time.time()-start_time

rawDescription: How to speed up matplotlib when plotting and saving lots of figures?

description: Speed up matplotlib when plotting and saving lots of figures


code:
alpha = 5
while alpha > 2:
    print alpha   # <-- these 2 lines of code will be executed repeatedly
    alpha -= 1    # <-- as long as alpha is > to 2

rawDescription: Explaining the result of an if loop in python


code: re.sub(ur'[\s\xa0]+', u' ', samplestr)

rawDescription: python regular expression works in sample code but not the code required

description: Python regular expression works in sample code but not the code required


code:
def get_attrs(element, tag, attr):
    """Return attribute `attr` of `tag` child elements of `element`."""

    # If an element has any cildren (nested elements) loop through them:
    if len(element):
         for node in element:
            # Recursively call this function, yielding each result:
            for attribute in get_attrs(node, tag, attr):
                yield attribute

    # Otherwise, check if element is of type `tag` with attribute `attr`, if so
    # yield the value of that attribute.
    if element.tag == 'variable':
        if attr in element.attrib:
            yield element.attrib[attr]

ids = [id for id in get_attrs(e, 'variable', 'id')]

print ids

rawDescription: Simple loop for all elements of an etree object?


code:
sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
for i in original_parser.parse(sent):
    print i
    break

rawDescription: NLTK: can I add terminal to grammar that is already generated


code:
for line in tablerow:
     match = re.search("\bCheck\b", line)
     if match:
         print "Yay"

rawDescription: Using Beautifulsoup to find cell data, then print entire row if certain cell value is found


code:
numbers = [20,4,67,22,445,1,34]
k = 3
newList = numbers[:k]

for i in numbers[k:]:
    mini = min(newList)
    if i > mini:
        print "Replacing {0} with {1}".format(mini, i)
        newList.remove(mini)
        newList.append(i)

print newList

rawDescription: finding top k elements in array python without heapq or sorting

description: Finding top k elements in array python without heapq or sorting


code:
from datetime import timedelta as td, datetime

start_date = '2016-01-01'
end_date = '2016-01-02'
d1 = datetime.strptime(start_date, '%Y-%m-%d')
d2 = datetime.strptime(end_date, '%Y-%m-%d')

def get_delta(d1, d2):
    delta = d2 - d1
    return delta

delta = get_delta(d1,d2)
for i in range(delta.days * 24 + 1):
    print d1 + td(hours=i)

rawDescription: Calculate hour range between dates in python


code:
import difflib

def sequ(s1, s2):
    words1 = s1.split()
    words2 = s2.split()
    matcher = difflib.SequenceMatcher(a=words1, b=words2)
    for block in matcher.get_matching_blocks():
        if block.size == 0:
            continue
        yield ' '.join(words1[block.a:block.a+block.size])

txt1 = 'the heavy lorry crashed into the building at midnight'
txt2 = 'what a heavy lorry it is that crashed into the building'
print list(sequ(txt1, txt2))

rawDescription: Text alignment: extracting matching sequence using python


code:
def create_variations(split_string):
    init_list = split_string.split(', ')
    for i in range(len(init_list)):
        var_list.append(init_list[:])
        init_list.insert(0, init_list.pop())

    print var_list

rawDescription: Python - Appending list to list during while loop - Result not as expected


code:
out = [0]  # your output array

s = "Example" # a byte string, not a Unicode string
l = list(s)   # convert to array of ints

out = out + l
print out

rawDescription: How to write data to a binary file using Python

description: Write data to a binary file using Python


code:
a = np.genfromtxt('filename', skip_header=2, delimiter=",", dtype = 'str')
print a

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

description: Setup string to float converters for numpy genfromtxt


code:
def add(a,b):
    return a+b

add2 = functools.partial(add, 2)
print add2(10)  # >> 12

rawDescription: return a function object with parameter binded?

description: Return a function object with parameter binded


rawDescription: Python output complex line with floats colored by value


code:
input = 'num=123-456-7890&kv1=1&kv2=12&kv3=0'
keys = {k: v for k, v in [i.split('=') for i in input.split('&')]}

print keys # {'num': '123-456-7890', 'kv2': '12', 'kv1': '1', 'kv3': '0'}

result = {}
for key, value in keys.items():
    if key == 'kv1':

        # if you need to increase result['kv1']
        _value = result[key] + int(value) if key in result else int(value)
        result[key] = _value

        # if you need to set result['kv1']
        result[key] = int(value)

print result # {'kv1': 1}

rawDescription: Aggregating key value pair in python

description: Aggregating key value pair in python


code:
allFruits = set()
for i,(k,v) in enumerate(sorted(dd.iteritems()), 1):
    allFruits.update(v)
    print i, len(allFruits)

rawDescription: Cumulative count of unique values in a dictionary


code:
import csv
s = """a,b,c
1,2,3
4,5,6
7,8,9"""
import io
reader_list = csv.DictReader(io.StringIO(s))
print reader_list.fieldnames
for row in reader_list:
    print row

rawDescription: Python csv.DictReader: parse string?

description: Python csv.DictReader: parse string


code:
import example
import struct
buf = struct.pack('BBBB', 0x41, 0x42, 0x43, 0x44)
print 'python:', buf
e = example.ExampleClass()
e.printBuffer(buf)

rawDescription: How do I pass a pre-populated "unsigned char*" buffer to a C++ method using boost.python?

description: Pass a pre-populated "unsigned char*" buffer to a C++ method using boost.python


code:
import urlparse
import cgi
parsed_url = urlparse.urlparse(url_to_parse)
query_as_dict = cgi.parse_qs(parsed_url.query)
print query_as_dict

rawDescription: Having trouble parsing HTML

description: Having trouble parsing HTML


code:
with open('conts.txt', 'w') as fh:
    fh.write('oh my god becky look at her butt it is soooo big')

consonants = "bcdfghjklmnpqrstvwxyz"
def count_cons(_file):
    results = {}
    with open(_file, 'r') as fh:
        for line in fh:
            for word in line.split(' '):
                conts = sum([1 if letter in consonants else 0 for letter in word])
                if conts in results:
                    results[conts] += 1
                else:
                    results[conts] = 1
    return results

print count_cons('conts.txt')

rawDescription: MapReduce to count the frequency of the number consonants in words from a text file


code:
from itertools import cycle

def foobar():
    A = [1, 2, 3, 4, 5]
    B = [6, 7, 8, 9, 10]
    tmp = 0
    iter_A = cycle(A)
    iter_B = cycle(B)
    it = iter_A
    while True:
        item = next(it)
        print item, tmp
        if tmp > 10:
            it = iter_B
        if tmp > 30:
            return tmp

        tmp += item

rawDescription: Can I redefine the iterator variable in the body of a for-loop?

description: Redefine the iterator variable in the body of a for-loop


code:
def columnize(mylists, maxcolumns):
    return [j[:-1]+([None]*(maxcolumns-len(j)))+j[-1:] for j in mylists]

print columnize(mylists,5)

[['author1', 'author2', 'author3', None, 'this is the title of the article'], ['author1', 'author2', None, None, 'this is the title of the article'], ['author1', 'author2', 'author3', 'author4', 'this is the title of the article']]

rawDescription: Inserting values in a Python list

description: Inserting values in a Python list


code:
from nltk.corpus import wordnet

dog = wordnet.synset('dog.n.01')
print dog.lemma_names

rawDescription: Is there any lib for python that will get me the synonyms of a word?


rawDescription: Python: Group List by Set of Keys

description: Python: Group List by Set of Keys


code:
labels = ("done", "rema", "succ", "fails", "size")

data = dict(zip(labels, [int(x) for x in starf]))

print data['done']

rawDescription: A better way to assign list into a var

description: A better way to assign list into a var


code:
for myVar in iter(myFunc, sentinel):
    print myVar

rawDescription: Call function in loop line and store return value to variable to then be used in the loop?


code:
from BeautifulSoup import BeautifulSoup
import urllib2

site= "http://www.google.com/search?q=shakespeare+pdf"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

req = urllib2.Request(site, headers=hdr)

try:
    page = urllib2.urlopen(req).read()
    soup = BeautifulSoup(page)
    ka=soup.findAll('cite',attrs={'class':'_Rm'})
    for i in ka:
        print i.text
except urllib2.HTTPError, e:
    print e.fp.read()

rawDescription: BeautifulSoup get <cite> tags from Google


rawDescription: How do I format the output of this Python program?

description: Format the output of this Python program


code:
import time
import threading

def do_something():
    T0 = time.clock()
    while (time.clock() - T0) < 60 and not e.isSet(): #as long as 60s haven't elapsed
                                                      #and the flag is not set
        #here do a bunch of stuff
        time.sleep(5)

thread = threading.Thread(target=do_something, args=())
e = threading.Event()
thread.start()

print 'Press CTRL-C to interrupt'
while thread.isAlive():
    try: time.sleep(1) #wait 1 second, then go back and ask if thread is still alive
    except KeyboardInterrupt: #if ctrl-C is pressed within that second,
                              #catch the KeyboardInterrupt exception
        e.set() #set the flag that will kill the thread when it has finished
        print 'Exiting...'
        thread.join() #wait for the thread to finish

rawDescription: Python - do something until keypress or timeout


code:
import time
class Measurement():
    values = []
    def add_value(self, value):
        print "added value"
        self.values.append(value)

def smart_delay(output_f, input_f):
    start_time = time.time()
    while 5 > (time.time() -  start_time):
        print "Calling function"
        output_f(input_f())
        time.sleep(1)

measurement = Measurement()

smart_delay(measurement.add_value, time.time)

rawDescription: Function as argument in python

description: Function as argument in python


code:
import re
from operator import itemgetter

def sorted_nicely(l, key):
    """ Sort the given iterable in the way that humans expect."""
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda item: [ convert(c) for c in re.split('([0-9]+)', key(item)) ]
    return sorted(l, key = alphanum_key)

print sorted_nicely([('b10', 0), ('0', 1), ('b9', 2)], itemgetter(0))

rawDescription: Naturally sort a list of alpha-numeric tuples by the tuple's first element in Python


code:
print B.foo.this_val   # 123
print C.foo.this_val   # 456

rawDescription: help with python inheritance

description: Help with python inheritance


code:
f = open('file.txt')
for x in f:
    start = x.split()[0][:-1]
    end = f.next().split()[0][:-1]
    print str(datetime.datetime.strptime(end,"%H:%M:%S")- datetime.datetime.strptime(start,"%H:%M:%S")).split(':')[-1]

rawDescription: Subtracting an integer value from a text file and displaying the result in Python2.7


code:
self.all_vars = {} # dictionary

def other_entry1(self, selection, row):
    if selection == "Other":
        self.all_vars[row] = StringVar()
        Entry(self.frame1, textvariable=self.all_vars[row]).grid(row=row, column=6)

#Calling it as part of an optionMenu
self.e33 = OptionMenu(self.frame1, self.ea_tf, *fixtures, command=lambda selection:self.other_entry1(selection,15))

# another place

row = 15
print "row:", row
print "value in Entry:", self.all_vars[row].get()

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


code:
import sys
import select
import tty
import termios

def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())

    i = 0
    while 1:
        print i
        i += 1

        if isData():
            c = sys.stdin.read(1)
            if c == '\x1b':         # x1b is ESC
                break

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

rawDescription: Python nonblocking console input

description: Python nonblocking console input


rawDescription: Python: how to convert utf-8 code string back to string?


code:
pos = [1, 2, 3, 4]
neg = [5, 6, 7, 8]

def vectorize(pos, neg):
    vec = dict.fromkeys(pos, 1)
    vec.update(dict.fromkeys(neg, 0))
    return vec

print vectorize(pos, neg)

rawDescription: Pythonic way to manipulate same dictionary


code:
datalist = [{"vehicle_class": "c1", "vehicle_class_count1": 16, "vehicle_usage_count1": 29, "vehicle_usage": "u1", "vehicle_type_count1": 16, "vehicle_type": "t1"}, {"vehicle_class": "c2", "vehicle_class_count1": 11, "vehicle_usage_count1": 29, "vehicle_usage": "u1", "vehicle_type_count1": 11, "vehicle_type": "t1"},{"vehicle_class": "c2", "vehicle_class_count1": 1, "vehicle_usage_count1": 29, "vehicle_usage": "u2", "vehicle_type_count1": 1, "vehicle_type": "t3"},{"vehicle_class": "c3", "vehicle_class_count1": 1, "vehicle_usage_count1": 29, "vehicle_usage": "u2", "vehicle_type_count1": 1, "vehicle_type": "t2"}]

levels_index = {1: 'vehicle_usage', 2: 'vehicle_type', 3: 'vehicle_class'}

result = []

def build_node(obj, key):
    '''This build the node for your result list'''
    return {
        'name': obj[key],
        'imageURL': '',
        'type': obj[key],
        'size': obj['%s_count1' % key],
        'children': []
    }

def build_level(input_list, keyindex):
    ''' This build one level at a time but call itself recursively'''
    key = levels_index[keyindex]
    levels_memory = {'vehicle_usage': [], 'vehicle_type': [], 'vehicle_class': []}
    output = []
    for obj in input_list:
        if obj[key] not in levels_memory[key]:
            levels_memory[key].append(obj[key])
            output.append(build_node(obj, key))
            if keyindex < len(levels_index):
                output[-1]['children'] = build_level(
                    [_ for _ in input_list if _[key] == output[-1]['name']],
                    keyindex + 1)
    return output

print build_level(datalist, 1)

rawDescription: Create a list of dictionaries which contains nested dictionaries


code:
import itertools
import pandas as pd
import io
txt = """1975;a;b
1976;b;c;d;e;f
1977;b;a
1977;a;b;g
1978;c;d
1979;e;f;b;k
1980;a;f"""

f = io.BytesIO(txt) # change this line to f = open("yourfile.csv")
result = []
for line in f:
    data = line.strip().split(";")
    year = data[0]
    for row in itertools.combinations(data[1:], 2):
        result.append((year,) + row)
df = pd.DataFrame(result)
print df

rawDescription: Transform dataframe rows with lists of items into rows with pairs of items


code:
def OnMove(self, event):
    print event.GetPosition()

rawDescription: wxPython, Triggering an Event While Dragging

description: WxPython, Triggering an Event While Dragging


code:
def foo(bar):
    print 'Bar:', bar

def baz(qux, *args):
    print 'Qux:', qux
    foo(*args)

rawDescription: Best approach to pass and handle arguments to function


code:
for i,line in enumerate(sample):
    print i+1, line

rawDescription: Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules


code:
from multiprocessing import Process, Queue
from Queue import Empty
from random import choice as rndchoice
import time

def worker(id, todo_q, start_q, finish_q):
    """multiprocessing worker"""
    msg = None
    while (msg!='DONE'):
        try:
            msg = todo_q.get_nowait()    # Poll non-blocking on todo_q
            if (msg!='DONE'):
                start_q.put((id, msg))   # Let the controller know work started
                time.sleep(0.05)
                if (rndchoice(range(3))==1):
                    # Die a fraction of the time before finishing
                    print "DEATH to worker %s who had task=%s" % (id, msg)
                    break
                finish_q.put((id, msg))  # Acknowledge work finished
        except Empty:
            pass
    return

if __name__ == '__main__':
    NUM_WORKERS = 5
    WORK_ID = set(['A','B','C','D','E']) # Work to be done, you will need to
                                    #    name work items so they are unique
    WORK_DONE = set([])             # Work that has been done
    ASSIGNMENTS = dict()            # Who was assigned a task
    workers = dict()
    todo_q = Queue()
    start_q = Queue()
    finish_q = Queue()

    print "Starting %s tasks" % len(WORK_ID)
    # Add work
    for work in WORK_ID:
        todo_q.put(work)

    # spawn workers
    for ii in xrange(NUM_WORKERS):
        p = Process(target=worker, args=(ii, todo_q, start_q, finish_q))
        workers[ii] = p
        p.start()

    finished = False
    while True:
        try:
            start_ack = start_q.get_nowait()  # Poll for work started
            ## Check for race condition between start_ack and finished_ack
            if not ASSIGNMENTS.get(start_ack[0], False):
                ASSIGNMENTS[start_ack[0]] = start_ack   # Track the assignment
                print "ASSIGNED worker=%s task=%s" % (start_ack[0],
                    start_ack[1])
                WORK_ID.remove(start_ack[1])      # Account for started tasks
            else:
                # Race condition. Never overwrite existing assignments
                # Wait until the ASSIGNMENT is cleared
                start_q.put(start_ack)
        except Empty:
            pass

        try:
            finished_ack = finish_q.get_nowait()  # Poll for work finished
            # Check for race condition between start_ack and finished_ack
            if (ASSIGNMENTS[finished_ack[0]][1]==finished_ack[1]):
                # Clean up after the finished task
                print "REMOVED worker=%s task=%s" % (finished_ack[0],
                    finished_ack[1])
                del ASSIGNMENTS[finished_ack[0]]
                WORK_DONE.add(finished_ack[1])
            else:
                # Race condition. Never overwrite existing assignments
                # It was received out of order... wait for the 'start_ack'
                finish_q.put(finished_ack)
            finished_ack = None
        except Empty:
            pass

        # Look for any dead workers, and put their work back on the todo_q
        if not finished:
            for id, p in workers.items():
                status = p.is_alive()
                if not status:
                    print "    WORKER %s FAILED!" % id
                    # Add to the work again...
                    todo_q.put(ASSIGNMENTS[id][1])
                    WORK_ID.add(ASSIGNMENTS[id][1])
                    del ASSIGNMENTS[id]      # Worker is dead now
                    del workers[id]
                    ii += 1
                    print "Spawning worker number", ii
                    # Respawn a worker to replace the one that died
                    p = Process(target=worker, args=(ii, todo_q, start_q,
                        finish_q))
                    workers[ii] = p
                    p.start()
        else:
            for id, p in workers.items():
                p.join()
                del workers[id]
            break

        if (WORK_ID==set([])) and (ASSIGNMENTS.keys()==list()):
            finished = True
            [todo_q.put('DONE') for x in xrange(NUM_WORKERS)]
        else:
            pass
    print "We finished %s tasks" % len(WORK_DONE)

rawDescription: Recovering lost multiprocessing.Queue items when a worker Process dies


code:
x = 1.23
y = 4.56
list = [[4,5]]
sublist = [x,y]
list.append(sublist)
print list

rawDescription: Is it possible to append two things at once as a list within a list? (Python)


code:
from collections import OrderedDict
orig = ['a=1', 'b=2', 'c=3', 'd=4', 'd=5', 'd=6', 'e=7']
d = OrderedDict()
for item in orig:
    k,v = item.split('=',1)
    d.setdefault(k,[]).append(v)

new = ['{0}={1}'.format(k,','.join(v)) for k,v in d.items()]
print new # ['a=1', 'b=2', 'c=3', 'd=4,5,6', 'e=7']

rawDescription: Collect parts of duplicated elements in a list and merge them in just one element


code:
dict_options = {1: 'Development', 2: 'Certification', 3: 'Production'}

print " " + str(dict_options).strip('{}') \
                    .replace(',', '\n') \
                    .replace(':', ')') \
                    .replace("'", '')

rawDescription: python - list a dictionary using raw_input

description: Python - list a dictionary using raw_input


code:
total_seq=[]
with open("out.txt") as lines:
    for l in lines:
        split_list = l.split()

        header = "".join(split_list[0:2])
        seq = split_list[2]
        disorder = split_list[4]

        # Create the new disorder string
        new_disorder = ["Disorder: Posi R"]
        print new_disorder
        for i, x in enumerate(disorder):
            print disorder
            if x == "X":
                # Appends of the form: "AminoAcid Position"
                new_disorder.append("{} {}".format(i, seq[i]))

        new_disorder = " ".join(new_disorder)

        total_seq.append([header, seq, new_disorder])
with open("seq2.txt", "a") as f:
    for seq in total_seq:
        f.write( "\n".join(seq))

rawDescription: How to align disorder region and sequence in a larger scale (python)

description: Align disorder region and sequence in a larger scale (python)


code:
a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']

import re

for elem in b:
    for test in a:
        if re.search(r'\b' + re.escape(elem) + r'\b', test):
            print elem

rawDescription: string comparison on 2 lists

description: String comparison on 2 lists


code: print "DOC STRING: %s" % application.__doc__

rawDescription: uWSGI optimize option

description: UWSGI optimize option


code:
import re

def replace_number(n):
    return str(int(round(int(n.group(0)), -2)))

data = ['F/O 1751 HOBART PL NW', '11TH ST NW 2301', '801 MT VERNON ST NW']

## I'm assuming you only want to munge numbers with 3 or more digits:
for datum in data:
    print re.sub(r"(\d{3,})", replace_number, datum)

rawDescription: Fastest Way To Round Number Inside List of Strings Python


rawDescription: How to solve recurrence relations in python

description: Solve recurrence relations in python


code:
def formatted(x, y, z):
   print "{:<10}{:<5}{}".format(x, y, z)
formatted(1, "f", "bar")
formatted(10, "fo", "bar")
formatted(100, "foo", "bar")

rawDescription: Formatting a basic table

description: Formatting a basic table


code:
print df.groupby('one').apply(net_func).loc[(slice('AAL','AAPL'),slice(1,1)),:]
#         one  two  dailyTrue  dailyFalse
#one
#AAL  1   AAL    2          1           0
#AAPL 1  AAPL    2          1           0

rawDescription: Python Pandas, slice rows from group in .groupby().apply()


code:
import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

print "received data:", data

rawDescription: Convert file into string then Rebuild that String and make it a file again


code:
import cv2

img = cv2.cv.LoadImage('rgbw.png')
pixels = []
for ch in img.tostring():
  pixels.append(ord(ch))
print pixels

[0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255]

rawDescription: How do you marshal Python cv2.cv.LoadImage tostring data into C IplImage->imageData struct

description: Marshal Python cv2.cv.LoadImage tostring data into C IplImage->imageData struct


code:
import csv

with open('input.csv', 'rb') as f_input:
    for row in csv.reader(f_input):
        row = [col.strip() for col in row]

        print row

rawDescription: How can trailing spaces be removed from Python CSV import?


code:
from bs4 import BeautifulSoup
data = """
<! Created by program ApproxMAP by Hye-Chung(Monica) Kum>

 Cluster Support= [Pattern=
 50
 % : Variation=
 20
 %]; Database Support= [Min=
 1
  seq: Max=
 50
 %]

 cluster=0 size=3
   =<100:
 85:
 70:
 50:
 35:
 20>

 PATTERN:
 {1,} {2,3,} {4,5,}

 =
 5

 {
 1
 12
 }
 {
 24
 }
 {
 2
 3
 25
 }
 {
 1
 4
 5
 }
 {
 26
 }

 PATTERN:
 {9,10,} {11,} {12,13,}

 =
 5

 {
 9
 10
 }
 {
 11
 }
 {
 11
 }
 {
 12
 13
 }

 TOTAL LEN=
 10

"""

soup = BeautifulSoup(data)

for elm in soup.find_all(text="PATTERN:"):
    print elm.find_parent("font").find_next_sibling("font").get_text(strip=True)

rawDescription: Python extract info from a local html file


code:
from collections import defaultdict
d = defaultdict(list)

for (value, key) in testdata:
    d[key].append(value)

print d

rawDescription: Make sets from a list of lists in Python


code:
Base = declarative_base()

class MyClass(Base):
    __tablename__ = 'mytable'
    key = Column(Integer, primary_key=True)
a = MyClass(key=1)

from sqlalchemy.inspection import inspect
pk = inspect(a).identity
print pk

rawDescription: Generic way to get primary key from declaratively defined instance in SQLAlchemy


code:
for module in modules:
    print module['moduletitle']
    for submodule in module['submodules']:
        print "  ", submodule['moduletitle']
        for content in submodule['content']:
            print "    ", content['content']

rawDescription: Python code not working similar in Jinja Template


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

# random data in your range
hmin,hmax = 0.00612598903444, 0.0344927479091
histmeans = hmin + np.random.rand(50)*(hmax-hmin)

x = np.arange(0.006,0.0345,0.0015)
print (x)

#Make historical (1979-2015) histogram
plt.figure(figsize=(11,7))
n,bins,edges = plt.hist(histmeans, x, color='#808080',edgecolor='k')

#Check bins
print bins

#labels & axes
#plt.locator_params(nbins=19, axis='x')
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
plt.title('Precip. Flux Anomaly (1979-2015 means, CanESM2 Hist)',fontsize=20)
plt.xlabel('Precip. Flux Mean (mm/day)',fontsize=15)
plt.ylabel('Number of Members',fontsize=15)
plt.xticks(x)
plt.xlim(0.006,0.0345)

print (np.min(histmeans))
print (np.max(histmeans))

plt.show()

rawDescription: Aligning bins to xticks in plt.hist

description: Aligning bins to xticks in plt.hist


code:
from nltk import NaiveBayesClassifier as nbc

# Allocate some sort of labels for the data.
training = [(hindi, 'hi'), (bangla, 'ba'), (marathi, 'ma'), (telugu, 'te')]
# This is how you can extract ngrams
print ngrams(telugu[:10], 2)
print
print ngrams(hindi[:10], 3)
print

vocabulary = set(chain(*[ngrams(txt, 2) for txt,tag in training]))

feature_set = [({i:(i in ngrams(sentence, 2)) for i in vocabulary},tag) for sentence, tag in training]

classifer = nbc.train(feature_set)

test1 = u'पूर्ण प्रत' # hindi
test2 = u'মহিষের সন্' # bangla
test3 = u'सनातनवा' # marathi
test4 = u'ఆడిట్ ' # telugu

for testdoc in [test1, test2, test3, test4]:
    featurized_test_sent =  {i:(i in ngrams(testdoc,2)) for i in vocabulary}
    print "test sent:", testdoc
    print "tag:", classifer.classify(featurized_test_sent)
    print

rawDescription: python based naive base classifer for new language

description: Python based naive base classifer for new language


code:
# assume the file is saved as "temp.py"

import inspect

class RegisteredObject(object):
    def __new__(cls, *args, **kwargs):
        new_instance = super(RegisteredObject, cls).__new__(cls, *args, **kwargs)
        stack_trace = inspect.stack()
        created_at = '%s:%d' % (
            stack_trace[1][1], stack_trace[1][2])
        new_instance.created_at = created_at
        return new_instance

    def get_file_of_object_creation(self):
        return self.created_at

class MyObject(RegisteredObject):
    pass

def create_A():
    return MyObject()

def create_B():
    return MyObject()

if __name__ == '__main__':
    t1 = create_A()
    t2 = create_B()
    t3 = create_A()
    t4 = create_B()
    t5 = MyObject()
    print '"t1" was created at "%s"' % t1.get_file_of_object_creation()
    print '"t2" was created at "%s"' % t2.get_file_of_object_creation()
    print '"t3" was created at "%s"' % t3.get_file_of_object_creation()
    print '"t4" was created at "%s"' % t4.get_file_of_object_creation()
    print '"t5" was created at "%s"' % t5.get_file_of_object_creation()

rawDescription: How to know where an object was instantiated in python?

description: Know where an object was instantiated in python


code:
import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame({'Time':['1:10,10', '1:16,32', '3:03,04']})
df['time'] = df.Time.apply(lambda x: datetime.datetime.strptime(x,'%M:%S,%f'))
df['timedelta'] = df.time - datetime.datetime.strptime('00:00,0','%M:%S,%f')
df['secs'] = df['timedelta'].apply(lambda x: x / np.timedelta64(1, 's'))
print df

rawDescription: Pandas; transform column with MM:SS,decimals into number of seconds


code:
# Flatten the dictionary keys.
# This turns ['boxes']['time_minutes']['coord']
# into "boxes_time_minutes_coord"
def flatten_dict(d, k_pre=None, delim='_', fd=None):
    if fd is None:
        fd = {}
    for k, v in d.iteritems():
        if k_pre is not None:
            k = '{0}{1}{2}'.format(k_pre, delim, k)
        if isinstance(v, dict):
            flatten_dict(v, k, delim, fd)
        else:
            fd[k] = v
    return fd

fd = flatten_dict(d)
locals().update(fd)

print boxes_time_minutes_coord

rawDescription: Create named variables in the local scope from JSON keys


code:
import random

data = []
for _ in range(100):
    data.append(random.randint(1, 100))
# Ok, a is populated with 100 integers.

# Grab chunks of 10 "points"
chunks=[data[x:x+10] for x in xrange(0, len(data), 10)]

# Initialization for the example done. Now, to your max list:
maxes = []
for chunk in chunks:
    maxes.append(max(chunk))
    print "The max number in chunk %s was: %s" % (chunk, maxes[-1])
print maxes #prints out the 10 max values of the 10 arrays of 10 numbers

rawDescription: Building an array in a loop

description: Building an array in a loop


code:
import redis
import time
import sys

r = redis.StrictRedis()
channel = sys.argv[1]
interval = float(sys.argv[2])

while True:
    # Resubscribe at each iteration to ensure we are only receiving
    # the newest message
    pubsub = r.pubsub()
    pubsub.subscribe(channel)

    _ = pubsub.listen().next() # the first message is always just a "1"
    message = pubsub.listen().next()

    print message['data']
    time.sleep(interval )

rawDescription: Use a class to monitor a data stream and print reports to two different windows at different time intervals in python


rawDescription: Parsing **kwargs

description: Parsing **kwargs


code:
def where_is(student, klasses):
    return (x for x in klasses if student in x.students)

for klass in where_is(john, [klass1, klass2]):
    print klass

rawDescription: Pythonic way to yield / return main item within a sub loop


code:
from flask import Flask, g

app = Flask(__name__)

def connect_db():
    print 'I ended up inside the actual function'
    return object()

@app.before_request
def before_request():
    g.db = connect_db()

@app.route('/')
def root():
    return 'Hello, World'

rawDescription: in a Flask unit-test, how can I mock objects on the request-global `g` object?

description: In a Flask unit-test, how can I mock objects on the request-global `g` object


code:
file2.py
def action(name):
    print name

rawDescription: Calling variables from other files in Python


code:
import csv
import re
import os

#need the sys module to get the command line args
import sys

def main(testV):
    fileobj = csv.reader(open('c:\\paths1.csv', 'rb'), delimiter=' ', quotechar='|')

    for row in fileobj:
        for x in row:
            with open(x) as f:
                for line in f:
                    if re.match(testV, line):
                        print 'The version match: '+ line
                    else:
                        print 'wrong version'
                        filesize= os.path.getsize(x)
                        print 'The file size is :'+ str(filesize) +' bytes'

if __name__=='__main__':
    #get the first command line argument and pass it to main
    testV = sys.argv[1]
    main(testV)

rawDescription: I would like to pass the value entered into the textbox to a python program


code:
def func2(msg):
    return 'result of func2("' + func1(msg) + '")'

def func1(msg):
    return 'result of func1("' + msg + '")'

print func1('test')
print func2('test')

rawDescription: Call a function from within another function in Python


code:
sentence = "These tests will benefit in the long run."
for word in wordlist:
    if re.search(r'\b' + word + r'\b', sentence):
         print word

rawDescription: Formatting regular expressions in Python


code:
from sklearn import preprocessing
import pandas as pd

df1 = pd.DataFrame({'A' : ['A', 'A', 'C', 'D','B'],
                    'B' : ['one', 'one', 'two', 'three','four']})

df2 = pd.DataFrame({'A' : ['D', 'D', 'B', 'A','A'],
                    'B' : ['one', 'five', 'two', 'three','four']})

le = preprocessing.LabelEncoder()
df1_int = le.fit_transform(df1['A'])
print df1_int

df2_int = le.transform(df2['A'])
print df2_int

rawDescription: convert categorial variables into integers using pandas

description: Convert categorial variables into integers using pandas


code:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst

rawDescription: Append a portion of a string to a list

description: Append a portion of a string to a list


code:
tree = html.fromstring(HTML)
results = dict()

def unpack(data):
    return data[0], data[1:]

for item in tree.xpath('//table/tr[not(contains(@bgcolor, "505050"))]'):
    key, values = unpack(item.xpath('.//td/text()'))
    results[key] = values

print results

rawDescription: Extracting rows from a table

description: Extracting rows from a table


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

home = NavigationToolbar2.home

def new_home(self, *args, **kwargs):
    print 'new home'
    home(self, *args, **kwargs)

NavigationToolbar2.home = new_home

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

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

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


code:
class B(object):

    def func(self):
        print 'Inside B'

class A(object):

    def __init__(self):
        self.df = B()
        self.name = 'Charlie'

    def get_name(self):
        return self.name

    def __getattr__(self, attr):
        try:
            return getattr(self.df, attr)
        except AttributeError:
            #If attribute was not found in self.df, then try in self
            return object.__getattr__(self, attr)

rawDescription: pass an undefined method call to an attribute containing a different object

description: Pass an undefined method call to an attribute containing a different object


code:
import urllib2
from bs4 import BeautifulSoup

def main():
    url = 'http://www.fbschedules.com/ncaa-15/sec/2015-texas-am-aggies-football-schedule.php'
    html = urllib2.urlopen(url).read()
    soup = BeautifulSoup(html)
    table = soup.find("table",{"class" : "cfb-sch"})
    # Working on the teams
    teams_td = table.findAll("td",{"class" : "cfb2"})
    teams = []
    for t in teams_td:
        teams.append(t.text.split('\r\n')[0].strip())
    # Working on the dates
    dates_td = table.findAll("td",{"class" : "cfb1"})
    dates = []
    # In the HTML table only 1 on 3 cfb1 is the date
    for i in range(0,len(dates_td),3):
        dates.append(dates_td[i].text)

    # Print everytin
    for s in zip(dates, teams):
        print s

if __name__ == '__main__':
    main()

rawDescription: Iterate and remove HTML from list elements in python


code:
import csv
with open("tsv.tsv") as tsvfile:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    for line in tsvreader:
        print line[1:]

rawDescription: python reading in multi-column tsv file with row numbers

description: Python reading in multi-column tsv file with row numbers


code:
array = [1, 2, 3, 4]
result = array[0] << 24 | array[1] << 16 | array[2] << 8 | array[3]
print result

rawDescription: Python: How to convert array of 4 digits to a larger number, bitwise?


code:
def weakness(self):
    if self.poketype == 'fire':
        print 'strong against grass'
        print 'weak against water'

    elif self.poketype == 'water':
        print 'strong against first'
        print 'weak against grass'

    elif self.poketype == 'grass':
        print 'strong against water'
        print 'weak against fire'

rawDescription: Error with a simple program, printing error (python)


code:
from change_defaults import Default, set_defaults

my_defaults = dict(USER_INPUT=0)

@set_defaults(my_defaults)
def DoSomething(var_of_data, user_input=Default("USER_INPUT")):
    return var_of_data, user_input

def main():
    print DoSomething("This")

    my_defaults["USER_INPUT"] = 1

    print DoSomething("Thing")

    my_defaults["USER_INPUT"] = 2

    print DoSomething("Actually")
    print DoSomething("Works", 3)

if __name__ == "__main__":
    main()

rawDescription: Python 2.7: Defining default parameters based on globals?


code:
class C(object):
    def m(self):
        print "m"

x=C()
x.m()

rawDescription: Difference between dir(…) and vars(…).keys() in Python?


code:
import glob

for file in glob.glob('/mydir/apple*.json.gz'):
    print file

rawDescription: Find files in a directory with a partial string match


code:
import re

test = "this matches"
match = re.match('(\w+\s\w+)', test)
print match.groups()

rawDescription: how to match whitespace and alphanumeric characters in python

description: Match whitespace and alphanumeric characters in python


code: print "Content_type: text/html\n\n"

rawDescription: Redirect python script to another python script for validation of login credentials


code:
class Weapon:
    def __init__(self, name, armor_hp_bonus = 0, skill_hp_bonus = 0):
       self.skill_hp_bonus = skill_hp_bonus
       self.armor_hp_bonus = armor_hp_bonus
       self.__name__ = name

class Hero:
    def __init__(self):
        self.basehp = 10
        self.armorhp = 0
        self.skillhp = 0
        self.righthand = None
        self.inventory = []

    def choose_weapon(self):
        while True:
            for idx, item in enumerate(self.inventory):
                print '{i}: {weapon}'.format(i=idx, weapon=item.__name__)
                choice = raw_input("Pick your weapon: ")
                try:
                    self.equip(self.inventory.pop(int(choice)))
                    return
                except IndexError:
                    print "Invalid choice"
                    continue

    def equip(self, weapon):
        if self.righthand:
            print "Weapon already equipped to right hand!"
            return
        else:
            self.righthand = weapon
            self.armorhp += weapon.armor_hp_bonus
            self.skillhp += weapon.skill_hp_bonus

    def unequip(self):
        if not self.righthand:
            print "No weapon to unequip!"
            return
        self.skillhp -= self.righthand.skill_hp_bonus
        self.armorhp -= self.righthand.armor_hp_bonus
        self.inventory.append(self.righthand)
        self.righthand = None

    def acquire_weapon(self, weapon):
        self.inventory.append(weapon)

    def calc_effective_hp(self):
        return self.basehp + self.skillhp + self.armorhp

rawDescription: Can I call a function from within a list? (python2.7)

description: Call a function from within a list? (python2.7)


code:
def foo(a, optional=object()):
    if optional is foo.func_defaults[0]:
        optional = 42
        print "1 arg"
    else:
        print "2 args"

rawDescription: Number of actual function arguments

description: Number of actual function arguments


code:
# selfimport.py
import selfimport

bar = 3

def foo():
    selfimport.bar = 5

if __name__ == '__main__':
    print selfimport.bar
    foo()
    print bar # bar is still 3!

rawDescription: python: can i import the module namespace within the module itself?

description: Python: can i import the module namespace within the module itself


code:
L = [[1,2,3],[4,5,6], [7,8,9]]
# number of rows, number of columns: ie L is m x n
m, n = len(L), len(L[0])

# Retreive the NE-SW (diag1) and NW-SE (diag2) diagonals
diag1 = []
diag2 = []
for p in range(m+n-1):
    diag1.append([])
    diag2.append([])
    q1 = 0
    if p >= n:
        q1 = p - n + 1
    q2 = m
    if p < m-1:
        q2 = p+1
    for q in range(q1, q2):
        x, y = p - q, q
        diag1[-1].append(L[y][x])
        # To get the other diagonal, read each row "backwards"
        x = n - x - 1
        diag2[-1].append(L[y][x])
print 'diag1:', diag1
print 'diag2:', diag2

rawDescription: Diagonals at different points of a 2D list in Python


code:
from pyparsing import (Suppress, Word, alphas, alphanums, nums, delimitedList,
    Combine, Optional, Group)

LBRACK,RBRACK,COLON = map(Suppress,"[]:")

ident = Word(alphas+"_", alphanums+"_")
integer = Combine(Optional('-') + Word(nums))
integer.setParseAction(lambda t : int(t[0]))
intrange = Group(integer + COLON + integer)

rangedIdent = ident("name") + LBRACK + delimitedList(intrange|integer)("indexes") + RBRACK

def expandIndexes(t):
    ret = []
    for ind in t.indexes:
        if isinstance(ind,int):
            ret.append("%s[%d]" % (t.name, ind))
        else:
            offset = (-1,1)[ind[0] < ind[1]]
            ret.extend(
                "%s[%d]" % (t.name, i) for i in range(ind[0],ind[1]+offset,offset)
                )
    return ret
rangedIdent.setParseAction(expandIndexes)

print rangedIdent.parseString("abc[0:3]")
print rangedIdent.parseString("abc[3:0]")
print rangedIdent.parseString("abc[0:3,7,14:16,24:20]")

rawDescription: decompress name

description: Decompress name


code:
def count_modify(l, n):
    print [i for i in l if i > n]

count_modify([1, 4, 6 , 9, 5, 3, 0], 3)
count_modify([9, 4, 6 , 9, 5, 3, 2], 9)

rawDescription: Print to same line

description: Print to same line


code:
print 1 in b2a
print 'a' in b2a

rawDescription: Data structure for many-many

description: Data structure for many-many


code:
from StringIO import StringIO
from PIL import Image
data = pygame.image.tostring(surf, 'RGBA')
img = Image.fromstring('RGBA', (100,200), data)
zdata = StringIO()
img.save(zdata, 'JPEG')
print zdata.getvalue()

rawDescription: How to save pygame Surface as an image to memory (and not to disk)

description: Save pygame Surface as an image to memory (and not to disk)


code: print "foo","bar","spam"

rawDescription: How can I print variable and string on same line in Python?

description: Print variable and string on same line in Python


code:
d = deque()
print d
print d.maxlen
d = deque(maxlen=3)
print d
print d.maxlen
d = deque(range(5))
print d
print d.maxlen
d = deque(range(5), maxlen=3)
print d
print d.maxlen

rawDescription: Check maxlen of deque in python 2.6

description: Check maxlen of deque in python 2.6


code: print ",".join(actors)

rawDescription: Keep CSV commas inside fields with Python


code:
list_tup = [('NYC', 'SF'), ('HOU', 'BOS'), ('NYC', 'DAL')]
sls = ['SF', 'DAL', 'NYC', 'HOU', 'BOS']

# Convert `sls` to a dictionary with the index as the value
sls_d = {item:idx for idx, item in enumerate(sls)}

# Sort individual tuples based on the index from `sls_d`
print [tuple(sorted(items, key=sls_d.get)) for items in list_tup]
# [('SF', 'NYC'), ('HOU', 'BOS'), ('DAL', 'NYC')]

rawDescription: sorting tuples in a list according to another self-made order

description: Sorting tuples in a list according to another self-made order


code:
from collections import Counter
with open('abc.txt') as f:
    c = Counter(int(line.split(None, 1)[0]) for line in f)
    print c

rawDescription: Count all +1's in the file python

description: Count all +1's in the file python


code:
def test(self, loc = None):
    if loc is None:
       loc = self.loc
    print loc

rawDescription: Python method defaults based off of class __init__ args


code:
class IntPoly(object):
    def __init__(self, poly_list):
        self.poly_list = poly_list

    def multiply():
        """Here you would do your proper conversion and parsing
        given the representation of the polynomials.
        But pretending that they are just numbers, you would do the following:"""
        return reduce(lambda x,y: x*y, self.poly_list)

myPolyObject = IntPoly([[4, 3, 2], [1, 2, 3], [4, 7, 8]])
print myPolyObject.multiply()

rawDescription: How do variables get passed in and out of methods in Python?


code:
from timeit import Timer
t = Timer(lambda: search_fast(prod_nums))
print t.timeit() # In my case will print 0.336354970932
t = Timer(lambda: search_slow(prod_nums))
print t.timeit() # 0.374251127243

rawDescription: Don't understand how Timeit works. Need an explanation


code:
with open(sectionedfile, 'r') as inputfile:
    for section in per_section(inputfile):
        print section

rawDescription: How to read a textfile by x number of lines, but x is unknown?

description: Read a textfile by x number of lines, but x is unknown


code:
email_address = "email_address_you_know@somewhere.com"

for data in j['items']:
    if email_address in data['message']:
        print data['message']

rawDescription: Search JSON response with python

description: Search JSON response with python


code:
print(letter_grade(91))
print(letter_grade(45))
print(letter_grade(75))
print letter_grade(1000)

rawDescription: Python Script returns unintended "None" after execution of a function


code:
with app.request_context({'wsgi.url_scheme': "", 'SERVER_PORT': "", 'SERVER_NAME': "", 'REQUEST_METHOD': ""}):
    from flask import g
    from flask_babel import refresh
    # set your user class with locale info to Flask proxy
    g.user = user
    # refreshing the locale and timezeone
    refresh()
    print lazy_gettext(u"This text should be in your language")

rawDescription: Change Flask-Babel locale outside of request context for scheduled tasks


code:
def parens(s):
    i=s[s.find('('):s.find(')')].count('(')   #counts number of '(' until the first ')'
    groups = s[s.find('('):].split(')')       #splits the string at every ')'
    print ')'.join(groups[:i]) +')'           #joins the list with ')' using the number of counted '('

rawDescription: Python - Return all substrings in the first group of nested parentheses


code:
import json
a = tree()
a['1']
addNode(a, '1', 'new')
print json.dumps(a)
a['1']['2']['3']
addNode(a, '3', 'new2')
print json.dumps(a)

rawDescription: Python recursive tree issues (adding elements or arbitrary nodes)


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


code:
data = ['a','b','c']
a, b = data[0], data[1:]
print a, b

rawDescription: How to unpack list into two variables in python2.x

description: Unpack list into two variables in python2.x


code: print name.decode('latin-1')

rawDescription: How do convert unicode escape sequences to unicode characters in a python string


code:
import datetime
today = datetime.date.today()
print today

rawDescription: Using result from python further down in a batch file


code:
s = "MMX Lions Television Inc"
regex = re.compile(r'\b(?=[MDCLXVI]+\b)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b')
print regex.sub(roman_to_int_repl, s)

rawDescription: Convert a string containing a roman numeral to integer equivalent


code:
import xml.etree.ElementTree as ET
tree = ET.parse('nmaptest.xml')

hosts = tree.findall(".//host")

for host in hosts:
    for elem in host.iter():
        if elem.tag == "hostname":
            print elem.attrib['name']
        if elem.tag == "address":
            print elem.attrib['addr']
        if elem.tag == "port":
            print elem.attrib['portid']

rawDescription: How do you walk an Element tree parsed using Python's elmenttree module?

description: Walk an Element tree parsed using Python's elmenttree module


code:
def foo(a='a', b='b', c='c'):
    print a + b + c

rawDescription: Python: is this a passing parameter convention?


code:
import requests
par = {"text": "He is a good boy"}
headers={"Accept" : "application/rdf+xml"}
r = requests.get("http://wit.istc.cnr.it/stlab-tools/fred/",
    data=par, headers=headers)
print r["text"]

rawDescription: FRED rest API in python

description: FRED rest API in python


code:
import requests
from bs4 import BeautifulSoup

query='http://www.realestate.com.au/buy/with-2-bedrooms-in-epping%2c+nsw+2121/list-1?maxBeds=2&source=refinements'
resp = requests.get(query)

soup = BeautifulSoup(resp.text)
ads = soup.find("div", {"class": "vcard"})
print ads.h2.a.text

rawDescription: Get House Price data

description: Get House Price data


rawDescription: Use regular expression to remove contents in brackets in python


code:
import logging
from apscheduler.scheduler import Scheduler

def _scheduler():
        print "scheduler"

def main():
    logging.basicConfig()
    scheduler = Scheduler(standalone=True)
    scheduler.add_interval_job(_scheduler, seconds=2)  # I doubt that `lambda` is necessary here ...
    scheduler.start()

if __name__ == "__main__":
    main()

rawDescription: Python Multithreading (while and apscheduler)


code:
group = {}

words = ['mom', 'dad', 'aaa', 'bob', 'ccc', 'xyz', 'abc']

for w in words:
    h = eq_hash(w)
    group[h] = group.get(h, []) + [w]

print group.values()
# [['xyz', 'abc'], ['mom', 'dad', 'bob'], ['aaa', 'ccc']]

rawDescription: Find equivalent words in a list through arbitrary mapping