code:
x = [random.random() for r in xrange(1000)]
num_bins = 50
counts, bins = np.histogram(x, bins=num_bins)
bins = bins[:-1] + (bins[1] - bins[0])/2
probs = counts/float(counts.sum())
print probs.sum() # 1.0
plt.bar(bins, probs, 1.0/num_bins)
plt.show()

rawDescription: How to plot a probability mass function in python

description: Plot a probability mass function in python


code:
import pandas as pd
from StringIO import StringIO
import sys
pathToFile = 'mydata.txt'
f = open(pathToFile)
s = StringIO()
cur_ID = None
for ln in f:
    if not ln.strip():
            continue
    if ln.startswith('ID'):
            cur_ID = ln.replace('\n',',',1).replace('#',',',1)
            continue
    if ln.startswith('TIME'):
            continue
    if cur_ID is None:
            print 'NO ID found'
            sys.exit(1)
    s.write(cur_ID + ln)
s.seek(0)
# create new dataframe with desired column names
df = pd.read_csv(s, names=['ID','Name','TIME_BIN', 'COUNT', 'AVG'])

rawDescription: Read inconsistently formatted csv file into Pandas Dataframe (blocks with headline and repeating column headers)


code:
with open('somefile.txt', 'r') as f:
  for line in f:
    if 'elements are suitable' in line:
      print line

rawDescription: finding and printing the line which contains the test string

description: Finding and printing the line which contains the test string


code:
some_path = "C:\\Folder testing"
dirs = [f for f in os.listdir(some_path) if os.path.isdir(os.path.join(some_path, f))]
dirs_sorted = sorted(dirs, key=int, reverse=True)
try:
    print dirs_sorted[1]
except IndexError:
    print "Folder doesn't exist"

rawDescription: Print second folder name

description: Print second folder name


code:
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4

import subprocess
import sys
import select

p = subprocess.Popen(["find", "/proc"],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)

stdout = []
stderr = []

while True:
    reads = [p.stdout.fileno(), p.stderr.fileno()]
    ret = select.select(reads, [], [])

    for fd in ret[0]:
        if fd == p.stdout.fileno():
            read = p.stdout.readline()
            sys.stdout.write('stdout: ' + read)
            stdout.append(read)
        if fd == p.stderr.fileno():
            read = p.stderr.readline()
            sys.stderr.write('stderr: ' + read)
            stderr.append(read)

    if p.poll() != None:
        break

print 'program ended'

print 'stdout:', "".join(stdout)
print 'stderr:', "".join(stderr)

rawDescription: Can you make a python subprocess output stdout and stderr as usual, but also capture the output as a string?

description: Make a python subprocess output stdout and stderr as usual, but also capture the output as a string


code:
import thread, time

def takes_a_while():

    def print_status():
        while True:
            print i   # print current i every two seconds
            time.sleep(2)

    status_thread = thread.start_new_thread(print_status, ())
    for i in xrange(10000000):
        print '*',
        time.sleep(0.1)
    status_thread.exit()

takes_a_while()

rawDescription: Python - while a long-running loop is going, how to have a thread periodically "do something" in the same scope?


code:
total = int(raw_input('What is the total amount for your online shopping?'))
country = raw_input('Shipping within the US or Canada?')

if country == "US":
    if total <= 50:
        print "Shipping Costs $6.00"
    elif total <= 100:
            print "Shipping Costs $9.00"
    elif total <= 150:
            print "Shipping Costs $12.00"
    else:
        print "FREE"

if country == "Canada":
    if total <= 50:
        print "Shipping Costs $8.00"
    elif total <= 100:
        print "Shipping Costs $12.00"
    elif total <= 150:
        print "Shipping Costs $15.00"
    else:
        print "FREE"

rawDescription: python if elif else statement

description: Python if elif else statement


code:
import ast

class PrintFinder(ast.NodeVisitor):
    def __init__(self):
        self.prints_found = []

    def visit_Print(self, node):
        self.prints_found.append(node)
        super(PrintFinder, self).generic_visit(node)

    def visit_Call(self, node):
        if getattr(node.func, 'id', None) == 'print':
            self.prints_found.append(node)
        super(PrintFinder, self).generic_visit(node)

def find_print_statements(filename):
    with open(filename, 'r') as f:
        tree = ast.parse(f.read())
    parser = PrintFinder()
    parser.visit(tree)
    return parser.prints_found

print 'hi'
for node in find_print_statements(__file__):
    print 'print statement on line %d' % node.lineno

rawDescription: Self scanning code to prevent print statments


code:
try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

class SideBar():
    def __init__(self, root):
        sidebarframe = tk.Frame(root)
        self.sometext = tk.Text(sidebarframe)
        button= tk.Button(sidebarframe, text="do something",
                          command = self.do_something)

        sidebarframe.grid(row = 0, column = 0)
        self.sometext.grid(row = 0, column = 1)
        button.grid(row = 0, column = 2)

        self.sometext.focus_set()

    def do_something(self):
        self.sometext.delete(1.0, "end")
        print "do something"

class MainApplication():
    def __init__(self, parent):
        self.parent = parent
        self.SB = SideBar(self.parent)

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root)
    root.mainloop()

rawDescription: Python Tkinter Object Oriented Coding Issue


code:
@vehicle.on_message('SYSTEM_TIME')
def listener(self, name, message):
    print message.time_unix_usec

rawDescription: How can I get the GPS time from the pixhawk, on a "companion computer"

description: Get the GPS time from the pixhawk, on a "companion computer"


code:
import datetime

def getStatus(log_list, dt, tm):
 #filter the list
 log_list = [a_log_entry for a_log_entry in log_list if a_log_entry[0] == dt and a_log_entry[1] <= tm]

    #sort it
 log_list.sort(cmp=lambda x,y: cmp(x[1], y[1]))
 if log_list is []:
     return 'No status available for this day and time.'

    #pull out the status
 status_to_return = log_list[-1][2].split('_')[-1].strip()

 return status_to_return

if __name__ == '__main__':
 in_file = open('a.log', 'rU')
 a_list = []

 for line in in_file:
  if line.strip() is not '': #handle whitespace
   a_list.append(line.split(' '))

 #convert string dates and times to datetime objects
 a_list = [ [datetime.datetime.strptime(el[0], '%d/%m/%Y'),
    datetime.datetime.strptime(el[1], '%H:%M:%S'),
    el[2]] for el in a_list]

 a_date = datetime.datetime(2010, 7, 15)
 a_time = datetime.datetime(1900, 1, 1, 16, 1, 0)
 print getStatus(a_list, a_date, a_time)

rawDescription: Reading and comparing lines in a file using Python


code:
with open ( 'arq.txt') as buffer:
    mat = list(map(int, line.strip()) for line in buffer)
print mat

rawDescription: Read txt and put in matrix in python

description: Read txt and put in matrix in python


code:
import sys
from collections import defaultdict
from time import time
import pygame
from pygame.key import name as keyname
from pygame.locals import *

# Mapping of a key to a list of holdtimes (from which you can average, etc)
holdtimes = defaultdict(list)
# Mapping of a key pair to a list of digraph times
digraphs = defaultdict(list)
# Keys which have been pressed down, but not up yet.
pending = {}
# Last key to be de-pressed, corresponding time).
last_key = None
# Text that the user has typed so far (one sublist for every Enter pressed)
typed_text = [[]]

def show_times():
    all_text = [k for line in typed_text for k in line]
    print "Holdtimes:"
    for key in all_text:
        print "%s: %.5f" % (key, holdtimes[key].pop(0))

    print "Digraphs:"
    for key1, key2 in zip(all_text, all_text[1:]):
        print "(%s, %s): %.5f" % (key1, key2,
                                  digraphs[(key1, key2)].pop(0))

def time_keypresses(events):
    global last_key
    for event in events:
        if event.type == KEYDOWN:
            # ESC exits the program
            if event.key == K_ESCAPE:
                show_times()
                sys.exit(0)

            t = pending[event.key] = time()
            if last_key is not None:
                if event.key != K_RETURN:
                    digraphs[(last_key[0], keyname(event.key))].append(t - last_key[1])
                last_key = None
        elif event.type == KEYUP:
            if event.key == K_RETURN:
                update_screen()
                typed_text.append([])
                pending.pop(event.key)
                last_key = None
            else:
                t = time()
                holdtimes[keyname(event.key)].append(t - pending.pop(event.key))
                last_key = [keyname(event.key), t]
                typed_text[-1].append(keyname(event.key))
        # Any other event handling you might have would go here...

def update_screen():
    global screen
    screen.fill((255, 255, 255))

    header_font = pygame.font.Font(None, 42)
    header = header_font.render("Type away! Press 'Enter' to show.", True, (0, 0, 0))
    header_rect = header.get_rect()
    header_rect.centerx = screen.get_rect().centerx
    header_rect.centery = screen.get_rect().centery - 100

    text_font = pygame.font.Font(None, 32)
    user_text = text_font.render("".join(typed_text[-1]) if typed_text[-1] else "...",
                                 True, (0, 0, 255))
    text_rect = user_text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery

    screen.blit(header, header_rect)
    screen.blit(user_text, text_rect)

    pygame.display.update()

if __name__ == '__main__':
    pygame.init()
    window = pygame.display.set_mode((800, 600))
    screen = pygame.display.get_surface()
    update_screen()
    while True:
        time_keypresses(pygame.event.get())

rawDescription: Can I get the amount of time for which a key is pressed on a keyboard

description: Get the amount of time for which a key is pressed on a keyboard


code:
import ply.lex as lex, re

tokens = (
    "TABLE",
    "JOIN",
    "COLUMN",
    "TRASH"
)

tables = {"tables": {}, "alias": {}}
columns = []

t_TRASH = r"Select|on|=|;|\s+|,|\t|\r"

def t_TABLE(t):
    r"from\s(\w+)\sas\s(\w+)"

    regex = re.compile(t_TABLE.__doc__)
    m = regex.search(t.value)
    if m is not None:
        tbl = m.group(1)
        alias = m.group(2)
        tables["tables"][tbl] = ""
        tables["alias"][alias] = tbl

    return t

def t_JOIN(t):
    r"inner\s+join\s+(\w+)\s+as\s+(\w+)"

    regex = re.compile(t_JOIN.__doc__)
    m = regex.search(t.value)
    if m is not None:
        tbl = m.group(1)
        alias = m.group(2)
        tables["tables"][tbl] = ""
        tables["alias"][alias] = tbl
    return t

def t_COLUMN(t):
    r"(\w+\.\w+)"

    regex = re.compile(t_COLUMN.__doc__)
    m = regex.search(t.value)
    if m is not None:
        t.value = m.group(1)
        columns.append(t.value)
    return t

def t_error(t):
    raise TypeError("Unknown text '%s'" % (t.value,))
    t.lexer.skip(len(t.value))

# here is where the magic starts
def mylex(inp):
    lexer = lex.lex()
    lexer.input(inp)

    for token in lexer:
        pass

    result = {}
    for col in columns:
        tbl, c = col.split('.')
        if tbl in tables["alias"].keys():
            key = tables["alias"][tbl]
        else:
            key = tbl

        if key in result:
            result[key].append(c)
        else:
            result[key] = list()
            result[key].append(c)

    print result
    # {'tb1': ['col1', 'col7'], 'tb2': ['col2', 'col8']}

string = "Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;"
mylex(string)

rawDescription: How to extract table names and column names from sql query?

description: Extract table names and column names from sql query


code:
# open lines as list, using read().split('\n') instead of readlines(),
# because readlines() leaves '\n' after the lines.
csv = open(r'c:\Users\***\Desktop\prvi.csv', 'r').read().split('\n')
csv2 = open(r'c:\Users\***\Desktop\drugi.csv', 'r').read().split('\n')
list1 = []

while True:
    # never use input(), unless you are using python 3
    choice = int(raw_input('Odaberite zeljenu funkciju: \n'
                           '1) Usporedi Book1 sa Book2\n'
                           '2) Usporedi Book2 sa Book1 \n'
                           '3) Print Book1 \n'
                           '4) Print Book2 \n'
                           '5) Izlaz \nOdabir: '))
    if choice == 1:
        for row in csv:
            if not row in csv2:
                list1.append(row)
                print row
        save_file()
    elif choice == 2:
        for row in csv2:
            if not row in csv:
                list1.append(row)
                print row
        save_file()
    elif choice == 3:
        for row in csv:
            print row
    elif choice == 4:
        for row in csv2:
            print row
    elif choice == 5:
        break

def save_file():
    with open('output.txt', 'w') as f:
        f.write('\n'.join(list1))

rawDescription: Python managing lists

description: Python managing lists


code:
def filetodic():
    d={}
    f = open("file.txt")
    for line in f:
        key  = line.split()
        d[key[0]]= ' '.join(key[1:])
    return d

print filetodic()

rawDescription: From file to dictionary

description: From file to dictionary


code:
import time
from multiprocessing import Pool

def printer(ip):
    try:
        for _ in xrange(5):
            print ip+str(_)
            time.sleep(1.0)
        return True
    except Exception as e:
        print e
        return False

class Worker():
    def __init__(self):
        self.pool = Pool(processes=2)

    def callback(self, result):
        if not result:
            print "Error raised in child process. Terminating.."
            self.pool.terminate()

    def do_job(self):
        for i in ["hello", 5]:
            self.pool.apply_async(printer, (i,), callback=self.callback)
        self.pool.close()
        self.pool.join()
        print "good bye"

def test():
    w = Worker()
    w.do_job()

rawDescription: How to exit all the joined processes in case any one has an exception - Python

description: Exit all the joined processes in case any one has an exception - Python


code:
#!/usr/bin/env python
# test.py

class Master(object):
    mydata = []
    def __init__(self):
        s1 = Sub1()
        s2 = Sub2()

class Sub1(Master):
    def __init__(self):
        super(Sub1, self).mydata.append(1)

class Sub2(Master):
    def __init__(self):
        super(Sub2, self).mydata.append(2)

if __name__ == "__main__":
    m = Master()
    print m.mydata

rawDescription: How can I use Python's super() to update a parent value?

description: Use Python's super() to update a parent value


code:
lst = "aaabaabacabaacaca"

def go(it):
    for x in it:
        if x == 'b':
            yield [x] + list(go(it))
        else:
            yield x
            if x == 'c':
                break

print list(go(iter(lst)))

rawDescription: How to process a string into layer of sublists

description: Process a string into layer of sublists


code:
import sys
from unittest import TestCase

import nose
from nose.tools import set_trace

class CollectPlugin(object):
    enabled = True
    name = "test-collector"
    score = 100

    def options(self, parser, env):
        pass

    def configure(self, options, conf):
        self.tests = []

    def startTest(self, test):
        self.tests.append(test)

class MyTestCase(TestCase):
    def test_long_integration(self):
        pass
    def test_end_to_end_something(self):
        pass

if __name__ == '__main__':
    # this code will run just this file, change module_name to something
    # else to make it work for folder structure, etc

    module_name = sys.modules[__name__].__file__

    plugin = CollectPlugin()

    result = nose.run(argv=[sys.argv[0],
                            module_name,
                            '--collect-only',
                            ],
                      addplugins=[plugin],)

    for test in plugin.tests:
        print test.id()

rawDescription: Get data structure of all tests found by Nose


code:
from shapely.ops import cascaded_union
from rtree import index
idx = index.Index()

# Populate R-tree index with bounds of grid cells
for pos, cell in enumerate(grid_cells):
    # assuming cell is a shapely object
    idx.insert(pos, cell.bounds)

# Loop through each Shapely polygon
for poly in polygons:
    # Merge cells that have overlapping bounding boxes
    merged_cells = cascaded_union([grid_cells[pos] for pos in idx.intersection(poly.bounds)])
    # Now do actual intersection
    print poly.intersection(merged_cells).area

rawDescription: Faster way of polygon intersection with shapely


code:
class foo(object):
    def f1(self):
        print "original f1"
    def f2(self):
        print "original f2"

class foo_decorator(object):
    def __init__(self, decoratee):
        self._decoratee = decoratee
    def f1(self):
        print "decorated f1"
        self._decoratee.f1()
    def __getattr__(self, name):
        return getattr(self._decoratee, name)

u = foo()
v = foo_decorator(u)
v.f1()
v.f2()

rawDescription: Implementing the decorator pattern in Python


code:
import random
# l2 is sorted totally:
l2 =[ {'id': '02', 'time': 'bl' }, {'id': '02', 'time': 'm24' },  {'id': '05', 'time': 'bl' }, {'id': '05', 'time': 'm12' }, {'id': '05', 'time': 'm24' }, {'id': '09', 'time': 'm12' }]
idss = set([i['id'] for i in l2])
ids = list(idss)

random.shuffle(ids)
l3 = []

for i in ids:
    for j in l2:
        if i == j['id']:
            # order by `time` is implicit
            l3.append(j)
print l3

rawDescription: Python shuffling only one parameter

description: Python shuffling only one parameter


code:
def myFunc(working_list=None):
    if working_list is None:
        working_list = []
    working_list.append("a")
    print working_list

rawDescription: What is the pythonic way to avoid default parameters that are empty lists?


code:
balance = 5000
annual_interest_rate = 0.18
low = balance/12
high = (balance * (1 + annual_interest_rate / 12) ** 12) / 12
guess = (low + high)/2

def get_bal(g, b, air):
    mon = 0
    while mon < 12:
        mon += 1
        ub = b - g
        b = ub + (air/12) * ub
    return b

while True:
    z = get_bal(guess, balance, annual_interest_rate)
    if abs(round(z, 2)) == 0:
        break
    if round(z, 2) > 0:
        low = guess
    else:
        high = guess
    guess = (high+low)/2

print "Lowest Payment: " + str(round(guess, 2))

rawDescription: Calculate lowest monthly payment using bisection search in python


code:
str = "ababac"
cmpr = "ab"

for chr in cmpr:
    if chr in str:
        str = str.replace(chr,'',1)
print str

rawDescription: Python: return letters not in string

description: Python: return letters not in string


code:
from Bio import SeqIO

for record in SeqIO.parse("NG_009616.gb", "genbank"):

    # You don't have to take care of the number of features with a while
    # Loop all of them.
    for feature in record.features:
        print "Attributes of feature"
        print "Type {0}".format(feature.type)
        print "Start {0}".format(feature.location.start)
        print "End {0}".format(feature.location.end)
        print "Qualifiers {0}".format(feature.qualifiers)
        # This is the right way to extract the sequence:
        print "Sequence {0}".format(feature.location.extract(record).seq)
        print "Sub-features {0}".format(feature.sub_features)

rawDescription: Biopython - String assigning error

description: Biopython - String assigning error


code:
from csv import DictWriter
from StringIO import StringIO
import xml.etree
from xml.etree import ElementTree

xml_str = \
'''
<?xml version="1.0" encoding="utf-8"?>
<root>
    <child>
        <Name>John</Name>
        <Surname>Doe</Surname>
        <Phone>123456</Phone>
        <Phone>654321</Phone>
        <Fax>111111</Fax>
    </child>
    <child>
        <Name>Tom</Name>
        <Surname>Cat</Surname>
        <Phone>98765</Phone>
        <Phone>56789</Phone>
        <Phone>00000</Phone>
    </child>
</root>
'''

root = ElementTree.parse(StringIO(xml_str.strip()))
entry_list = []
for child_tag in root.iterfind("child"):
    child_tags = child_tag.getchildren()

    tag_count = {}
    [tag_count.__setitem__(tag.tag, tag_count.get(tag.tag, 0) + 1) for tag in child_tags]

    m_count = dict([(key, 0) for (key, val) in filter(lambda (x, y): y > 1, tag_count.items())])

    enum = lambda x: ("%s%s" % (x.tag, (" %d" % m_count.setdefault(x.tag, m_count.pop(x.tag) + 1)) if(tag_count[x.tag] > 1) else ""), x.text)
    tmp_dict = dict([enum(tag) for tag in child_tags])

    entry_list.append(tmp_dict)

field_order = ["Name", "Surname", "Phone 1", "Phone 2", "Phone 3", "Fax"]
field_check = lambda q: field_order.index(q) if(field_order.count(q)) else sys.maxint

all_fields = list(reduce(lambda x, y: x | set(y.keys()), entry_list, set([])))
all_fields.sort(cmp=lambda x, y: field_check(x) - field_check(y))

with open("test.csv", "w") as file_h:
    writer = DictWriter(file_h, all_fields, restval="", extrasaction="ignore", dialect="excel", lineterminator="\n")
    writer.writerow(dict(zip(all_fields, all_fields)))
    writer.writerows(entry_list)

rawDescription: Using python's zip and list comprehensions to convert xml to csv


code:
from Tkinter import *
import json
import time
import webbrowser

with open('data.json', 'r') as f:
    database = json.loads(f.read())

def goto(event, href, tag_name):
    res = event.widget
    res.tag_config(tag_name, background='red')  # change tag text style
    res.update_idletasks()  # make sure change is visible
    time.sleep(.5)  # optional delay to show changed text
    print 'opening:', href      # comment out
    #webbrowser.open_new(href)  # uncomment out
    res.tag_config(tag_name, background='white')  # restore tag text style
    res.update_idletasks()

def evaluate(event):
    res.delete('1.0', END)
    search_param = str(entry.get())
    link_count = 0
    for patient_id in database:
        if search_param in str(database[patient_id]).lower():
            href = "https://website.com/" + str(patient_id)
            tag_name = "link" + str(link_count)  # create unique name for tag
            link_count += 1
            # shim to call real event handler with extra args
            callback = (lambda event, href=href, tag_name=tag_name:
                            goto(event, href, tag_name))
            res.tag_bind(tag_name, "<Button-1>", callback) # just pass function
                                                           # (don't call it)
            res.insert(INSERT, href+'\n', (tag_name,))  # insert tagged text

w = Tk()
Label(w, text="Search:").pack()
entry = Entry(w)
entry.bind("<Return>", evaluate)
entry.pack()
res = Text(w)
res.pack()
w.mainloop()

rawDescription: Tkinter and hyperlinks

description: Tkinter and hyperlinks


code:
#!/usr/bin/env python
import sys, itertools
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage

urls = ["http://www.gouvernement.fr/", "http://www.google.com/"]
outputs = ["output1.png", "output2.png"]

def save_page(webpage, output):
    # Set the size of the (virtual) browser window
    webpage.setViewportSize(webpage.mainFrame().contentsSize())

    # Paint this frame into an image
    image = QImage(webpage.viewportSize(), QImage.Format_ARGB32)
    painter = QPainter(image)
    webpage.mainFrame().render(painter)
    painter.end()
    image.save(output)
    print ".png image successfully saved"
    #sys.exit(0)

app = QApplication(sys.argv)
signal.signal(signal.SIGINT, signal.SIG_DFL)

webpage = QWebPage()

def onLoadFinished(result):
    if not result:
        print "Request failed"
        sys.exit(1)
    save_page(webpage, outputs.pop(0))   # pop output name from list and save
    if urls:
        url = urls.pop(0)   # pop next url to fetch from list
        webpage.mainFrame().load(QUrl(url))
    else:
        app.quit()  # exit after last url

webpage.connect(webpage, SIGNAL("loadFinished(bool)"), onLoadFinished)
webpage.mainFrame().load(QUrl(urls.pop(0)))
sys.exit(app.exec_())

rawDescription: PyQt image caputuring error

description: PyQt image caputuring error


code:
selected_indices = list(np.random.choice(indices,500,replace=False))
print [files[i] for i in selected_indices]

rawDescription: select random items from an array

description: Select random items from an array


code:
import glob
from bs4 import BeautifulSoup

for filename in glob.iglob('*.html'):
    with open(filename) as f:
        soup = BeautifulSoup(f)

        title = soup.find("span", id="btAsinTitle")
        author = title.find_next("a", href=True)
        isbn = soup.find('b', text='ISBN-10:').next_sibling
        weight = soup.find('b', text='Shipping Weight:').next_sibling

        print {'title': title.get_text(),
               'author': author.get_text(),
               'isbn': isbn,
               'weight': weight}

rawDescription: How to loop python to read a set of HTML files and dump into JSON

description: Loop python to read a set of HTML files and dump into JSON


code:
import os
print os.environ['REQUEST_METHOD']

rawDescription: How to differentiate between GET and POST in plain CGI

description: Differentiate between GET and POST in plain CGI


code:
class Snake(object):
    @classmethod
    def my_name(cls):
        print cls.__name__

rawDescription: In python how to get name of a class inside its static method


code:
import sqlite3
import datetime

db = sqlite3.connect(':memory:', detect_types = sqlite3.PARSE_COLNAMES)
c = db.cursor()
c.execute('create table foo (bar integer, baz timestamp)')
c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
c.execute('insert into foo values(?, ?)', (42, datetime.datetime.now() + datetime.timedelta(-1)))
c.execute('select bar, baz as "ts [timestamp]" from foo')
print c.fetchall()
c.execute('select max(baz) as "ts [timestamp]" from foo')
print c.fetchall()

rawDescription: Reading back a datetime in sqlite3

description: Reading back a datetime in sqlite3


code:
l = s.split('\\autocite')
print '%s\\autocite%s' % (l[0], ''.join(l[1:]))

rawDescription: How to remove repeating non-adjacent string

description: Remove repeating non-adjacent string


code:
from PIL import Image

file_in = "image.png"
img = Image.open(file_in)
file_out = 'test1.bmp'
print len(img.split()) # test
if len(img.split()) == 4:
    # prevent IOError: cannot write mode RGBA as BMP
    r, g, b, a = img.split()
    img = Image.merge("RGB", (r, g, b))
    img.save(file_out)
else:
    img.save(file_out)

from xlwt import Workbook
w = Workbook()
ws = w.add_sheet('Image')
ws.insert_bitmap(file_out, 0, 0)
w.save('images.xls')

rawDescription: Can I insert matplotlib graphs into Excel programmatically?

description: Insert matplotlib graphs into Excel programmatically


code:
for element in self.driver.find_elements_by_tag_name('img'):
       print element.text
       print element.tag_name
       print element.parent
       print element.location
       print element.size

rawDescription: Python and how to get text from Selenium element WebElement object?


code:
from pylab import *
import time

ion()

tstart = time.time()               # for profiling
x = arange(0,2*pi,0.01)            # x-array
line, = plot(x,sin(x))
for i in arange(1,200):
    line.set_ydata(sin(x+i/10.0))  # update the data
    draw()                         # redraw the canvas

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

rawDescription: Most lightweight way to plot streaming data in python


code:
from scipy.integrate import quad
from scipy.optimize import fsolve
from math import cos, sin, sqrt, pi

def circle_diff(t):
    dx = -sin(t)
    dy = cos(t)
    return sqrt(dx*dx+dy*dy)

def sin_diff(t):
    dx = 1
    dy = cos(t)
    return sqrt(dx*dx+dy*dy)

def curve_length(t0, S, length):
    return quad(S, 0, t0)[0] - length

def solve_t(curve_diff, length):
    return fsolve(curve_length, 0.0, (curve_diff, length))[0]

print solve_t(circle_diff, 2*pi)
print solve_t(sin_diff, 7.640395578)

rawDescription: Finding the location of a given arc distance along a parameterized curve in python


code:
import csv

old = csv.reader(open('old.csv', 'rb'), delimiter=' ')
row1 = old.next()
new = csv.reader(open('new.csv', 'rb'), delimiter=' ')
row2 = new.next()

for row1, row2 in zip(old, new):
    if (row1[8] == row2[8]) and (row1[9] == row2[9]):
        continue
    else:
        print row1[0] + ':' + row1[8] + '!=' + row2[8]

rawDescription: Compare some columns from 2 csv files using python


code:
import csv
from my_django_app.forms import CityForm
with open( "my file", "rb" ) as source:
    rdr = csv.DictReader( source )
    for row in rdr:
        form= CityForm( **row )
        if form.is_valid():
            form.save()
        else:
            print form.errors

rawDescription: How to populate a table while creating the Django model?

description: Populate a table while creating the Django model


code: print myDict[ u'Command']

rawDescription: pymongo result to String

description: Pymongo result to String


code:
import httplib2
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

to_copy = '<id/key_string_from_desired_file_url>'
# Service account e-mail from Google dev console
drive_id = '<my_long_service_account_string>@developer.gserviceaccount.com'
# Get the right permissions
drive_scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
# pem key converted from p12 key generated in dev console
with open(os.path.abspath('my_key.pem'), 'rb') as keyfile:
    drive_key = keyfile.read()

credentials = SignedJwtAssertionCredentials(drive_id, drive_key, drive_scope)

http = httplib2.Http()
http = self.credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
file_copy = {'title': title}

try:
    drive_service.files().copy(fileId=to_copy, body = file_copy).execute()
except errors.HttpError, error:
    print error

rawDescription: Using OAuth and gdata to copy google spreadsheet


code:
def readMultiple(logfile,searchString,countnumber):
    with open(logfile) as search:
        count=0
        for line in search:
            line = line.rstrip()  # remove '\n' at end of line
            #print "Line", line

            if searchString in line:
                #print(line )
                count+=1
                print "count",count

readMultiple("a.txt","This is stack overflow line")

rawDescription: How to search duplicate strings in file using python and getting the last counted string dynamic way

description: Search duplicate strings in file using python and getting the last counted string dynamic way


code:
decrypted = 'abcdefghijklmnopqrstuvwxyz' #normal alphabet
encrypted = 'MNBVCXZLKJHGFDSAPOIUYTREWQ' #your "crypted" alphabet

#Encription
text = 'cryptme' #the string to be crypted
encrypted_text = ''
for letter in text:
    encrypted_text += encrypted[decrypted.find(letter)]
print encrypted_text
#will print BOWAUFC

#Decription
text = encrypted_text #"BOWAUFC" in this example
decrypted_text = ''
for letter in text:
    decrypted_text += decrypted[encrypted.find(letter)]
print decrypted_text
#will print cryptme

rawDescription: How to 'encrypt' a file

description: 'encrypt' a file


code:
import re
print re.findall(r'\.(x\d{2}y\d{2})\.', "name.x00y00.whatever")
# Prints ['x00y00']

rawDescription: trying to find text with wild card integers inside a string in a special format in Python

description: Trying to find text with wild card integers inside a string in a special format in Python


code:
with open('foo.txt', 'w') as f:
    f.write(name)
with open('foo.txt', 'r') as f:
    print 'Text is:', f.read()

rawDescription: Why does python output to a file like this?


code:
from datetime import datetime

def parse_date(thedate):
    result = None

    #try each format
    try:
        result = datetime.strptime(thedate, "%d-%b-%Y")
    except ValueError:
        pass
    except:
        raise

    # Let the last one "blow" up
    if result is None:
        result = datetime.strptime(thedate, "%d/%m/%Y")

    print "{} parsed into {}".format(thedate,result.strftime("%d-%b-%Y %H:%M:%S"))

rawDescription: How to convert date format and add hh:mm:ss to it

description: Convert date format and add hh:mm:ss to it


code: print root.xpath('substring-after(normalize-space(//td[contains(text(), "Shipment Total:")]/following-sibling::td/b/text()), "$")')

rawDescription: XPath run text() through regular expression to return numbers only


code:
import signal

def signal_handler(signum, frame):
    raise Exception("Timed out!")

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10)   # Ten seconds
try:
    long_function_call()
except Exception, msg:
    print "Timed out!"

rawDescription: How to limit execution time of a function call in Python

description: Limit execution time of a function call in Python


code:
inner_dict = places["City"]
for _, city_obj in inner_dict.items():
    print city_obj.population # Assuming population is one of the member variables of the class mod.city

rawDescription: Accessing elements in dictionary of dictionaries


code:
import numpy as np
from sympy import *

x, y = symbols("x, y")
eq = sqrt(x**2 + y**2)

xa = np.random.rand(10)
ya = np.random.rand(10)
f = lambdify((x, y),eq,'numpy')

print f(xa, ya)
print np.sqrt(xa**2 + ya**2)

rawDescription: Sympy: generate figure with multiple subplots


code:
##fix the eq and hash to work correctly
class MyObject:
    def __init__(self,value,meta):
        self.value = value
        self.meta = meta
    def __eq__(self,other):
        return self.value, self.meta == other.value, other.meta
    def __hash__(self):
        return hash((self.value, self.meta))
    def __repr__(self):
        return "%s %s" % (self.value,self.meta)

a = MyObject('1','left')
b = MyObject('1','right')
c = MyObject('2','left')
d = MyObject('2','right')
e = MyObject('3','left')

union =  set([a,c,e]).union(set([b,d]))
print union
#set([2 left, 2 right, 1 left, 3 left, 1 right])

##sort the objects, so that older objs come before the newer equivalents
sl = sorted(union, key= lambda x: (x.value, x.meta) )
print sl
#[1 left, 1 right, 2 left, 2 right, 3 left]
import itertools
##group the objects by value, groupby needs the objs to be in order to do this
filtered = itertools.groupby(sl, lambda x: x.value)
##make a list of the oldest (first in group)
oldest = [ next(group) for key, group in filtered]
print oldest
#[1 left, 2 left, 3 left]

rawDescription: Behavior of object in set operations

description: Behavior of object in set operations


code:
import json
import hashlib
import requests

token = hashlib.sha1()
token.update("calvinrock0406@gmail.comheaven3610255k592k2di4u9uok3e8u9pkfepjfoc809kfutv5z".encode('utf-8'))
token_dig = token.hexdigest()

response = requests.get("https://www.mediafire.com/api/user/get_session_token.php?application_id=36102&signature=" + token_dig + "&email=calvinrock0406@gmail.com&password=heaven&token_version=2&response_format=json")

json_response = response.json()
print json_response["response"]["session_token"]

rawDescription: Pulling token from JSON responce in Python


code:
import xml.sax

class myHandler(xml.sax.ContentHandler):
    def __init__(self):
        self.text = []
        self.keeping_text = False
        self.attributes = []

    def startElement(self, name, attrs):
        if name.lower() in ('tag2', 'tag4'):
            self.keeping_text = True

        try:
            # must attribute1 be on a tag2 or anywhere?
            attr = attrs.getValue('attribute1')
            self.attributes.append(attr)
        except KeyError:
            pass

    def endElement(self, name):
        self.keeping_text = False

    def characters(self, content):
        if self.keeping_text:
            self.text.append(content)

parser = xml.sax.make_parser()
handler = myHandler()
parser.setContentHandler(handler)
parser.parse(open("sample.xml", "r"))

print handler.text
print handler.attributes

# [u'\n', u'      Text I want to use', u'\n', u'   ',
#  u'\n', u'      More text I want to use', u'\n', u'   ']
# [u'attribute_i_need']

rawDescription: How can I get and store the text between XML tags as a string with the python sax parser?

description: Get and store the text between XML tags as a string with the python sax parser


code:
import random
print random.randint(0,5)

rawDescription: random 'module' object has no attribute 'randit'; random.__file__ directs to right module in library frameworks; other solutions have not worked

description: Random 'module' object has no attribute 'randit'; random.__file__ directs to right module in library frameworks; other solutions have not worked


code: print '''Let's begin and end with sets of unlikely 2 chars and bingo'''

rawDescription: using an alternative string quotation syntax in python

description: Using an alternative string quotation syntax in python


code:
def LCG(seed, n, a=1664525, c=1013904223, m=2**32):
    numbers = []
    for i in xrange(n):
        seed = (a * seed + c) % m
        numbers.append(seed)

    return numbers

print LCG(3, 5)

rawDescription: Random numbers algorithm

description: Random numbers algorithm


code:
import time

total_friends = len([friend for friend in s.get_friends()
                     if friend['type'] == 0])

SLEEP_TIME = 60

while True:
    new_friends = 0
    snaps = s.get_snaps()
    for sender in snaps:
        if sender['media_type'] == 3:
            s.add_friend(sender[u'sender'])
            new_friends += 1

    total_friends += new_friends

    if new_friends:
        print 'Amount of confirmed friends:'
        print total_friends, '/ 6000'
    time.sleep(60)

rawDescription: Infinite looping, and only executing part of the script if first part is true


code:
from libs import envlib
from libs import diskoplib
from libs import dblib

class Something(object):

    # Class attributes
    _e = envlib.Query()
    _d = diskoplib.Query()
    _db = dblib.Query()

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

    def do_something(self):
        id = self._e.get_opened_file_id()
        filepath = self._d.get_filepath()
        names = self._db.get_names()

        print id, names, filepath # ready to be used for something

rawDescription: What is the general approach when designing python libraries which require other python libraries?


code:
a=2
s = np.random.zipf(a, 1000)
result = (s/float(max(s)))*1000

print min(s), max(s)
print min(result), max(result)

rawDescription: How to create values from Zipf Distribution with range n in Python?

description: Create values from Zipf Distribution with range n in Python


code:
import collections

with open('results.txt') as infile:
    counts = collections.Counter(l.strip() for l in infile)
for line, count in counts.most_common():
    print line, count

rawDescription: Python: How to count how many lines in a file are the same


code:
import itertools
n = 1
with open('foobar.txt') as f:
    print next(itertools.islice(f, n, n+1))

rawDescription: How to get the 2nd line of a 19GB file - python?

description: Get the 2nd line of a 19GB file - python


rawDescription: Python: Shifted Averaging And Space Delimiting


code:
from dateutil import parser

# sort ascending
print sorted(yourlist, key=lambda k: parser.parse(k['modified']))

# sort descending
print sorted(yourlist, key=lambda k: parser.parse(k['modified']), reverse=True)

rawDescription: How to sort files by list elements by date modified, in Python?

description: Sort files by list elements by date modified, in Python


code:
for x in range(1, 13):
    print ''.join([format(x * y, '2d' if y == 1 else '4d')
                   for y in range(1, 13)])

rawDescription: Differences between the following python and ruby code


code:
import rarfile
import os.path

extracted_dir_name = "samples/sample"    # Directory with extracted files
file = rarfile.RarFile("samples/sample.rar", "r")

# list file information
for info in file.infolist():
     print info.filename, info.date_time, info.file_size

     # Compare with extracted file here
     extracted_file = os.path.join(extracted_dir_name, info.filename)
     if info.file_size != os.path.getsize(extracted_file):
         print "Different size!"

rawDescription: Compare archiwum.rar content and extracted data from .rar in the folder on Windows 7


code:
def m(name, bases, dct):
    for k, v in dct.items():
        if type(v) is type(m):
            dct[k] = classmethod(v)
    return type(name, bases, dct)

class A:
    __metaclass__ = m

    def foo(self):
        print self

A.foo() # <class '__main__.A'>

rawDescription: Metaclass to make class methods the default?


code:
import time, threading

def filechecker():
    #check for new files in a directory and do stuff
    print "{} : called!".format(time.ctime())

INTERVAL = 5 or 1800
t = None

def schedule():
    filechecker()
    global t
    t = threading.Timer(INTERVAL, schedule)
    t.start()

try:
    while True:
        schedule()
        print '{} : Sleeping... Press Ctrl+C or Enter!'.format(time.ctime())
        i = raw_input()
        t.cancel()
except KeyboardInterrupt:
    print '{} : Stopped.'.format(time.ctime())
    if t: t.cancel()

rawDescription: Program that either waits for user input or runs at defined intervals?


code:
for key, (num1, num2, num3) in mydict.iteritems():
    print key, num1, num2, num3

rawDescription: Iterating over dictionaries containing tuples


rawDescription: Overwrite Column in .csv with Column from other .csv


code:
class Blah(object):
    def __init__(self, value):
        self._value = value
    @property
    def value(self):
        return self._value
    @value.setter
    def value(self, value):
        self._value = value + 1

b = Blah(3)
b.value = 25
print b.value
# 26

rawDescription: Intercepting member reads and assignment in python


code:
s = "myprog  -library lib -topcell top -view layout"
print re.sub(r'(-[a-zA-Z0-9]*\s)',r'\\\n\t\1', s)
print re.sub(r'(-[a-zA-Z0-9]*\s)',r'\\\n\t \1 ', s)

rawDescription: Can I use python "re.sub" instead of "sed"?

description: Use python "re.sub" instead of "sed"


code:
keywords=['good','lorry','truck']
with open('qwe.txt','r') as file:
    for line in file:
        for key in keywords:
            if key in line:
               a = 'yes'
               break
            else:
                a = 'no'
        print a

rawDescription: python for loop makes extra listing

description: Python for loop makes extra listing


code:
from ctypes import *
val = c_int64()
windll.Kernel32.QueryPerformanceCounter(byref(val))
print val.value

rawDescription: python on win32: how to get absolute timing / CPU cycle-count

description: Python on win32: how to get absolute timing / CPU cycle-count


code:
threads = []
for startX in xrange(0, width, threadChunk):
    t = Thread(target = threaded_chunk, args = (thread_num, startX, startX + threadChunk, 1, 0, height, 1))
    threads.append(t)
    print 'next thread'

[t.start() for t in threads]
[t.join() for t in threads]

rawDescription: Python Multithreading an Image-Rendering


code:
for key in bucket.list():
   akey = bucket.get_key(key.name)
   print akey.get_metadata("company")

rawDescription: Boto s3 get_metadata

description: Boto s3 get_metadata


code:
word_list = []
word_list2 = open('romeo.txt').read().split()
for item in word_list2:
    if item in word_list:
        continue
    else:
        word_list.append(item)
word_list.sort()
print word_list

rawDescription: Python append words to a list from file

description: Python append words to a list from file


code:
import h5py
import numpy

arr1 = numpy.random.random((2000,2000))

with h5py.File("Plot0.h5", "w") as f:
    dset = f.create_dataset("Plot", data = arr1, maxshape=(None,None))

dsetX, dsetY = 2000,2000
go = ""
while go == "":
    go = raw_input("Current Size: " + str(dsetX) + "  " + str(dsetY) + "  Continue?")
    arr2 = numpy.random.random((2000,2000))

    with h5py.File("Plot0.h5", "r+") as f:
        dset = f["Plot"]
        print len(arr2[:])
        print len(arr2[0][:])
        change = "column"

        dsetX, dsetY = dset.shape

        if change == "column":

            x1 = dsetX
            x2 = len(arr2[:]) + dsetX

            y1 = 0
            y2 = len(arr2[0][:])

            dset.shape = (x2, y2)
        else:
            x1 = 0
            x2 = len(arr2[:])

            y1 = dsetY
            y2 = len(arr2[0][:]) + dsetY

            dset.shape = (x2, y2)
        print "x1", x1
        print "x2", x2
        print "y1", y1
        print "y2", y2

        print dset.shape

        dset[x1:x2,y1:y2] = arr2

        print arr2
        print "\n"
        print dset[x1:x2,y1:y2]

        dsetX, dsetY = dset.shape

rawDescription: Column stack and row stack with H5py to existing datasets


code:
import pandas as pd
import zipfile

z = zipfile.ZipFile('test/file.gz')
print pd.read_csv(z.open("DCCV_OCCUPATIT_Data+FootnotesLegend_175b2401-3654-4673-9e60-b300989088bb.csv"),
                  sep="|",
                  engine = "python")

rawDescription: Load directly gz file into pandas dataframe


code:
import os
from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

filename = "readme.txt"
os.startfile(filename, "edit")

try:
    os.startfile(filename, "edit")
except WindowsError, e:
    MessageBox(text=str(e))

rawDescription: How do I open a file for edit from the command line under Windows?

description: Open a file for edit from the command line under Windows


code:
import paramiko
import os
import sys
from threading import Thread

SERVER_LIST = [{"ip":"192.168.1.2","pass":"Administrator"},{"ip":"192.168.1.4","pass":"AdminStudents"},{"ip":"192.168.1.3","pass":"AdminTeachers"}]

class ExecuteRegister(Thread):
    def __init__ (self,options):
        Thread.__init__(self)
        self.options = options
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    def run(self):
        try:
           self.ssh.connect(self.options['ip'],username='root', password=self.options["pass"])
           self.ssh.exec_command('./register.py -time 6') #6 hour so the script still working for 6 hours
           self.ssh.close()
        except:
           print sys.exc_info()

for server in SERVER_LIST:
    Register = ExecuteRegister(server)
    Register.start()

rawDescription: Commands in Paramiko block due to script execution time


code:
import numpy as np

def local_max(a, start, finish):
    local = a[start:finish+1]
    loc_max = max(local)
    loc_pos = local.index(loc_max) + start
    return loc_max, loc_pos

data = [3, np.nan, 5.3, 7.0, 8, 5.0, 0, 1, 3, 5.0, 2.4, 0.1, 0.3, 0.5]

print local_max(data, 7, 11)
print local_max(data, 0, 5)

rawDescription: Function to find local maximum

description: Function to find local maximum


code:
import sys
import time
import random

ESC = "\x1b"

def home():
    sys.stdout.write(ESC + '[0;0H')
    sys.stdout.flush()

def cls():
    sys.stdout.write(ESC + '[2J')
    sys.stdout.flush()

def print_status():
    w = 8
    print '+' + '-'*w + '+'
    for row in range(3):
        fmt = '|%%%dd |' % (w - 1)
        print fmt % random.randint(0, 1000)
        print '+' + '-'*w + '+'
    sys.stdout.flush()

if __name__ == "__main__":
    cls()
    for k in range(16, 0, -1):
        home()  # or use cls()
        print_status()
        time.sleep(0.5)

rawDescription: Print a fancy string and update it after it's printed to simulate a GUI


code:
#!/usr/bin/env python

import oauth2client

from oauth2client.client import OAuth2WebServerFlow

flow = OAuth2WebServerFlow(client_id='your_client_id',
                           client_secret='your_client_secret',
                           scope='https://spreadsheets.google.com/feeds',
                           redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()

print auth_uri

rawDescription: How to generate RequestToken URL for Google API

description: Generate RequestToken URL for Google API


code:
class MyModel(models.Model):
    field = models.ForeignKey(MyOtherModel)

mymodel_instance = MyModel.objects.get(pk=1)
# queries database for related object and the result is a MyOtherModel instance
print mymodel_instance.field
# result is simply the integer id value, does not do any query
print mymodel_instance.field_id

rawDescription: Django ForeignModels

description: Django ForeignModels


code:
import pycuda.autoinit
import pycuda.driver as drv
import numpy

from pycuda.compiler import SourceModule
mod = SourceModule("""
__global__ void multiply_them(float *dest, float *a, float *b)
{
  const int i = threadIdx.x;
  dest[i] = a[i] * b[i];
}
""")

multiply_them = mod.get_function("multiply_them")

a = numpy.random.randn(400).astype(numpy.float32)
b = numpy.random.randn(400).astype(numpy.float32)

dest = numpy.zeros_like(a)
multiply_them(
        drv.Out(dest), drv.In(a), drv.In(b),
        block=(400,1,1), grid=(1,1))

print dest-a*b

rawDescription: Calling C++ CUDA code from python

description: Calling C++ CUDA code from python


code:
args = [u'Everything', u'okay?', u':)']
message = ' '.join(args)
print message

rawDescription: Putting everything from arraylist to one line?


code:
from PyQt4 import QtCore, QtGui

class BaseWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

    def mymethod(self):
        pass

class AWidget(BaseWidget):
    def __init__(self, parent=None):
        BaseWidget.__init__(self, parent)

    def mymethod(self):
        print "A"

class BWidget(BaseWidget):
    def __init__(self, parent=None):
        BaseWidget.__init__(self, parent)

    def mymethod(self):
        print "B"

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.toolbox = QtGui.QToolBox(self)
        a = AWidget(self.toolbox)
        b = BWidget(self.toolbox)
        self.toolbox.addItem(a, "A")
        self.toolbox.addItem(b, "B")
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.printMethod)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.toolbox)
        layout.addWidget(self.button)

    def printMethod(self):
        for i in range(self.toolbox.count()):
            self.toolbox.widget(i).mymethod()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: how to get subclassed QWidgets from QToolBox?

description: Get subclassed QWidgets from QToolBox


code:
'Vui lòng giúp đỡ tôi'
'Vui lòng giúp đỡ tôi'.decode('utf-8')
print 'Vui lòng giúp đỡ tôi'.decode('utf-8')

rawDescription: How to convert unicode string to decimal number in python?

description: Convert unicode string to decimal number in python


code:
import sys

V = range(100000)
for x in V:
    print x
    sys.stdout.flush()

rawDescription: Using Windows Python from Cygwin

description: Using Windows Python from Cygwin


code:
import pygtk
pygtk.require('2.0')
import gtk
import urllib2

class MainWin:
    def my_timer(self):
        self.response=urllib2.urlopen(
            'http://192.168.1.11:7007/video/now.jpeg')
        self.loader=gtk.gdk.PixbufLoader()
        self.loader.write(self.response.read())
        self.loader.close()
        self.image.set_from_pixbuf(self.loader.get_pixbuf())
        return True# do ur work here, but not for long

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", self.destroy)
        self.window.set_border_width(10)
        self.image=gtk.Image()

        gtk.timeout_add(1000, self.my_timer) # call every min

        self.window.add(self.image)
        self.image.show()
        self.window.show()

    def main(self):
        gtk.main()

if __name__ == "__main__":
    MainWin().main()

rawDescription: Python - how to refresh the Gtk.Image to get the latest image frame from same URL?


code:
print 'The lines that starts with The and Ends with u'

with open('test.txt') as f:
    for line in f:
        line = line.strip()
        if line.startswith('The') and line.endswith('u'):
            print line

rawDescription: Print sentences from text file that starts and ends with particular words or character?


code:
input_str = input().lower()
if input_str.startswith("z"):
  print "yes"
elif input_str.startswith("x"):
  print "no"

rawDescription: Finding differences between words

description: Finding differences between words


rawDescription: Python pandas change variable number of duplicate timestamps to unique


code:
import clr
clr.AddReference('System.Data')
import System
from System.Data import DataSet, DataTable, XmlReadMode
from Spotfire.Dxp.Data import DataType, DataTableSaveSettings
from System.IO import StringReader, StreamReader, StreamWriter, MemoryStream, SeekOrigin
from System.Threading import Thread
from Spotfire.Dxp.Data import IndexSet
from Spotfire.Dxp.Data import RowSelection
from Spotfire.Dxp.Data import DataValueCursor
from Spotfire.Dxp.Data import DataSelection
from Spotfire.Dxp.Data import DataPropertyClass
from Spotfire.Dxp.Data import Import
from System import DateTime
from System import DateTime, TimeSpan, DayOfWeek
from datetime import date
from System.Net import HttpWebRequest
import time
from Spotfire.Dxp.Data.Import import TextFileDataSource, TextDataReaderSettings

rowCount = Document.Data.Tables['Registrations'].RowCount
rowsToInclude = IndexSet(rowCount,True)
myList = []

#Get a cursor to the two columns we want to use. cursor1 is for the key column and cursor2 is for the column selected by the user input
registration = DataValueCursor.CreateFormatted(Document.Data.Tables['Registrations'].Columns["Registration ID"])
date1 = DataValueCursor.Create[DateTime](Document.Data.Tables['Registrations'].Columns["Date 1"])
date2 = DataValueCursor.Create[DateTime](Document.Data.Tables['Registrations'].Columns["Date 2"])
date3 = DataValueCursor.Create[DateTime](Document.Data.Tables['Registrations'].Columns["Date 3"])
date4 = DataValueCursor.Create[DateTime](Document.Data.Tables['Registrations'].Columns["Date 4"])
date5 = DataValueCursor.Create[DateTime](Document.Data.Tables['Registrations'].Columns["Date 5"])

#get users logon name not prid
#print Thread.CurrentPrincipal.Identity.Name

dataSet = DataSet()
dataTable = DataTable("pattern")
dataTable.Columns.Add("Registration ID", System.String)
dataTable.Columns.Add("Date 1", System.DateTime)
dataTable.Columns.Add("Date 2", System.DateTime)
dataTable.Columns.Add("Date 3", System.DateTime)
dataTable.Columns.Add("Date 4", System.DateTime)
dataTable.Columns.Add("Date 5", System.DateTime)
dataTable.Columns.Add("Sequence", System.String)
dataSet.Tables.Add(dataTable)

for  row in  Document.Data.Tables['Registrations'].GetRows(rowsToInclude,registration, date1,date2,date3, date4, date5):
   dates=dict()
   reg = registration.CurrentValue
   value1 = date1.CurrentValue
   value2 = date2.CurrentValue
   value3 = date3.CurrentValue
   value4 = date4.CurrentValue
   value5 = date5.CurrentValue
   dates['date1'] = value1
   dates['date2'] = value2
   dates['date3'] = value3
   dates['date4'] = value4
   dates['date5'] = value5

   sortedDates = sorted(dates.values())

   #print sorted(dates.values())

   pattern = ""
   for key, value in sorted(dates.iteritems(), key=lambda (k,v): (v,k)):
                if str(value) <> '01/01/0001 00:00:00':
                    print 'Found a zero date'
                    if key == 'date1':
                                pattern = pattern + 'd1'
                                print 'Found a date 1'
                    if key == 'date2':
                                pattern = pattern + 'd2'
                                print 'Found a date 2'
                    if key == 'date3':
                                pattern = pattern + 'd3'
                                print 'Found a date 3'
                    if key == 'date4':
                                pattern = pattern + 'd4'
                                print 'Found a date 4'
                    if key == 'date5':
                                pattern = pattern + 'd5'
                                print 'Found a date 5'

   dt = dataTable.NewRow()
   dt["Registration ID"] = reg
   dt["Date 1"] = value1
   dt["Date 2"] = value2
   dt["Date 3"] = value3
   dt["Date 4"] = value4
   dt["Date 5"] = value5
   dt["Sequence"] = pattern
   dataTable.Rows.Add(dt)

textData = "Registration ID\tDate 1\tDate 2\tDate 3\tDate 4\tDate 5\tSequence\r\n"
for row in dataTable.Rows:
                textData +=  row["Registration ID"] + "\t" + str(row["Date 1"]) + "\t" + str(row["Date 2"]) + "\t" + str(row["Date 3"]) + "\t" + str(row["Date 4"]) + "\t" + str(row["Date 5"]) + "\t" + row["Sequence"] + "\r\n"

print textData

stream = MemoryStream()
writer = StreamWriter(stream)
writer.Write(textData)
writer.Flush()
stream.Seek(0, SeekOrigin.Begin)

readerSettings = TextDataReaderSettings()
readerSettings.Separator = "\t"
readerSettings.AddColumnNameRow(0)
readerSettings.SetDataType(0, DataType.String)
readerSettings.SetDataType(1, DataType.Date)
readerSettings.SetDataType(2, DataType.Date)
readerSettings.SetDataType(3, DataType.Date)
readerSettings.SetDataType(4, DataType.Date)
readerSettings.SetDataType(5, DataType.String)

dSource = TextFileDataSource(stream, readerSettings)

if Document.Data.Tables.Contains("Sequence"):
                Document.Data.Tables["Sequence"].ReplaceData(dSource)
else:
                newTable = Document.Data.Tables.Add("Sequence", dSource)
                tableSettings = DataTableSaveSettings (newTable, False, False)
                Document.Data.SaveSettings.DataTableSettings.Add(tableSettings)

rawDescription: How to create a data table on the fly in Spotfire via python

description: Create a data table on the fly in Spotfire via python


code:
import wx
from wx.lib.delayedresult import startWorker

class MainFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(MainFrame, self).__init__(*args, **kwargs)
        self.panel = wx.Panel(self)
        self.gobtn = wx.Button(self.panel, label="Go")
        self.prog = wx.Gauge(self, style=wx.GA_HORIZONTAL)
        self.timer = wx.Timer(self)

        wrap = wx.BoxSizer()
        wrap.Add(self.gobtn, 0, wx.EXPAND|wx.ALL, 10)
        wrap.Add(self.prog, 0, wx.EXPAND|wx.ALL, 10)
        self.panel.SetSizer(wrap)
        self.panel.Fit()
        self.SetInitialSize()

        self.Bind(wx.EVT_BUTTON, self.Go, self.gobtn)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

    def Go(self, event):
        # Start actual work in another thread and start timer which
        # will periodically check the progress and draw it
        startWorker(self.GoDone, self.GoCompute)
        self.progress = 0
        self.timer.Start(100)

    def OnTimer(self, event):
        # Timer draws the progress
        self.prog.SetValue(self.progress)

    def GoCompute(self):
        # This method will run in another thread not blocking the GUI
        numwords = 10000000
        self.prog.SetValue(0)
        for i in range(1, numwords + 1):
            self.progress = int(((float(i) / float(numwords)) * 100) - 1)

    def GoDone(self, result):
        # This is called when GoCompute finishes
        self.prog.SetValue(100)
        self.timer.Stop()
        print "Done"

if __name__ == "__main__":
    app = wx.App()
    frame = MainFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: wx.Gauge fails to update beyond 25% in Windows, works in Linux

description: Wx.Gauge fails to update beyond 25% in Windows, works in Linux


code:
tn = telnetlib.Telnet('64.0.0.1')
tn.write('ls \r\n')
data = ''
while data.find('#') == -1:
    data = tn.read_very_eager()
print data

rawDescription: Reading data using tn.read_all() in python


code:
import argparse
import zmq

parser = argparse.ArgumentParser(description='zeromq server/client')
parser.add_argument('--bar')
args = parser.parse_args()

if args.bar:
    # client
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect('tcp://127.0.0.1:5555')
    socket.send(args.bar)
    msg = socket.recv()
    print msg
else:
    # server
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind('tcp://127.0.0.1:5555')
    while True:
        msg = socket.recv()
        if msg == 'zeromq':
            socket.send('ah ha!')
        else:
            socket.send('...nah')

rawDescription: interprocess communication in python

description: Interprocess communication in python


code:
def main():
    print("Welcome to the autostacker")
    h, w, l = getDim()

    if 20 <= h <= 40:
        if 20 <= w <= 40:
            if 20 <= l <= 40:
                print "height is %d width is %d length is %d" % (h, w, l)
            else:
                print 'length out of range'
        else:
            print 'width out of range'
    else:
        print 'height out of range'

def getDim():
    height = int(input("Enter the height: "))
    width = int(input("Enter the width: "))
    length = int(input("Enter the length: "))
    return height, width, length

main()

rawDescription: defined function repeatedly looping

description: Defined function repeatedly looping


code:
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus()
b = Button(master, text="get", width=10, command=callback)
b.pack()
mainloop()

def callback():
    print master.focus()

rawDescription: In Tkinter how do i remove focus from a widget?


code:
values = {
    u'123453': u'Some Value',
    u'984561': u'837',
    u'123456': u'more stuff',
}

def insertLookup(matchobj):
    return values[matchobj.group(1)]

theString = u"Var 1 value: %%v:123453%%, Var 2 value: %%v:984561%%, Var 3 value: %%v:123456%%"
p = re.compile("\%%v:([0-9]*)%%")
newString = p.sub(insertLookup, theString)

print newString
u"Var 1 value: Some Value, Var 2 value: 837, Var 3 value: more stuff"

rawDescription: How do I get a python regular expression to return all text not matching?

description: Get a python regular expression to return all text not matching


code:
import wx

class TBI(wx.TaskBarIcon):
    def __init__(self):
        wx.TaskBarIcon.__init__(self)
        icon = wx.ArtProvider.GetIcon(wx.ART_FILE_OPEN, wx.ART_TOOLBAR)
        self.SetIcon(icon, "Icon")
        self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.on_right_up)

    def on_right_up(self, event):
         if wx.GetKeyState(wx.WXK_CONTROL):
             print 'ctrl was pressed!'

app = wx.App(redirect=False)
icon = TBI()
app.MainLoop()

rawDescription: detect a ctrl-click on taskbar menu

description: Detect a ctrl-click on taskbar menu


code:
import sys
import StringIO
import contextlib

@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO.StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old

code = """
i = [0,1,2]
for j in i :
    print j
"""
with stdoutIO() as s:
    exec code

print "out:", s.getvalue()

rawDescription: python : get the print output in an exec statement

description: Python : get the print output in an exec statement


code:
import random
i = 1000000

while i > 0:
    i = random.randint(0, i)
    print i

rawDescription: How to randomly generate decreasing numbers in Python?

description: Randomly generate decreasing numbers in Python


code:
data = sorted(rand(10))
new_data = rand(5)
pvals = searchsorted(data,new_data)*1./len(data)
print pvals
#array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

rawDescription: Distributions and p-values in python

description: Distributions and p-values in python


code:
result = set(p[0])
for s in p[1:]:
    result.intersection_update(s)
print result

rawDescription: How to find common elements in list of lists?

description: Find common elements in list of lists


code:
element = driver.find_element_by_xpath(xpath) #Locate the element.

outerHTML = element.get_attribute("outerHTML") #Get its HTML
innerHTML = element.get_attribute("innerHTML") #See where its inner content starts

if len(innerHTML) > 0: # Let's make this work for input as well
    innerHTML = innerHTML.strip() # Strip whitespace around inner content
    toTrim = outerHTML.index(innerHTML) # Get the index of the first part, before the inner content
    # In case of moste elements, this is what we care about
    rightString = outerHTML[:toTrim]
else:
    # We seem to have something like <input class="bla" name="blabla"> which is good
    rightString = outerHTML
# Ie: <span class="something" id="somethingelse">

strippedString = rightString.strip() # Remove whitespace, if any
rightTrimmedString = strippedString.rstrip('<>') #
leftTrimmedString = rightTrimmedString.lstrip('</>') # Remove the <, >, /, chars.
rawAttributeArray = leftTrimmedString.split(' ') # Create an array of:
# [span, id = "something", class="somethingelse"]

curatedAttributeArray = [] # This is where we put the good values
iterations = len(rawAttributeArray)

for x in range(iterations):
    if "=" in rawAttributeArray[x]: #We want the attribute="..." pairs
        curatedAttributeArray.append(rawAttributeArray[x]) # and add them to a list

numberOfAttributes = len(curatedAttributeArray) #Let's see what we got
print numberOfAttributes # There we go

rawDescription: How can I count the number of attributes of an element in Selenium Python?

description: Count the number of attributes of an element in Selenium Python


code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

capabilities = DesiredCapabilities.CHROME
capabilities['loggingPrefs'] = { 'browser':'ALL' }

driver = webdriver.Chrome(desired_capabilities=capabilities)

driver.get('http://foo.com')

# print console log messages
for entry in driver.get_log('browser'):
    print entry

rawDescription: Detect javascript console output with python


code:
def command(f):
    def g(filenames, **kwa):
        lines = readfiles(filenames)
        lines = (outline for line in lines for outline in f(line, **kwa))
        # lines = (line for line in lines if line is not None)
        printlines(lines)
    return g

def readfiles(filenames):
    for f in filenames:
        for line in open(f):
            yield line

def printlines(lines):
    for line in lines:
            print line.strip("\n")

@command
def grep(line, pattern):
    if pattern in line:
        yield line

if __name__ == '__main__':
    import sys
    pattern = sys.argv[1]
    filenames = sys.argv[2:]
    grep(filenames, pattern=pattern)

rawDescription: find occurrences of a string in a large file that cannot fit memory

description: Find occurrences of a string in a large file that cannot fit memory


code:
import multiprocessing as mp

def worker(x):
    name = mp.current_process().name
    print name, 'starting...'
    while x < 10:
            print x
            x+=2
    print name, 'complete!'

if __name__ == '__main__':
    num_procs = 2
    procs = [mp.Process(target=worker, args=(x,)) for x in range(num_procs)]
    for proc in procs:
        proc.start()
    for proc in procs:
        proc.join()

rawDescription: python/multiprocessing: howto simplify "def" fields

description: Python/multiprocessing: howto simplify "def" fields


code:
import wx
import wx.lib.wxpTag

class HtmlCheckListBox(wx.html.HtmlWindow):
    def __init__(self, parent, choices=None):
        wx.html.HtmlWindow.__init__(self, parent)

        check_box = """
        <wxp module="wx" class="CheckBox">
            <param name="id" value="%d">
        </wxp>
        """

        self._ids = dict()

        if choices:
            items = list()
            for c, choice in enumerate(choices):
                i = wx.NewId()
                self._ids[i] = c
                items.append((check_box % i) + choice)
            self.SetPage("
".join(items))

        self.Bind(wx.EVT_CHECKBOX, self.OnCheck)

    def OnCheck(self, event):
        print "item:", self._ids[event.Id], "checked:", event.Checked()

class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.options = HtmlCheckListBox(
            self,
            [
                "one",
                "two",
                "three"
            ]
        )

app = wx.PySimpleApp()
app.TopWindow = TestFrame()
app.TopWindow.Show()
app.MainLoop()

rawDescription: wxPython CheckListBox with HTML

description: WxPython CheckListBox with HTML


code:
def opt(histo,cur):
  tmp=[]
  tmp.append([cur[0]+1,cur[1]])
  tmp.append([cur[0]-1,cur[1]])
  tmp.append([cur[0],cur[1]+1])
  tmp.append([cur[0],cur[1]-1])
  tmp.remove(histo[-2])
  print "current history : ",histo
  print "current tmp : ",tmp
  print "current pos : ",cur
  for i in list(tmp):
    if i in histo:
      print str(i)+" was detected!!"
      tmp.remove(i)
  return tmp

rawDescription: Python 'in' operator doesn't work in array


code:
import maya.cmds as cmds

cmds.progressBar('progressBar') # initialise the progress bar

def callback():
  # Begin loop from 0 to 100 - remember range(n) returns numbers from 0 (inclusive) to n (exclusive)
  for i in range(101):
      cmds.progressBar('progressBar', edit=True, step=1) # increase step by 1
      if (cmds.progressBar('progressBar',q=True, progress=True)==100):
          print "Finished Uploading."
          break
          # Theoretically, breaking is simply here so that you stop wasting iterations in some cases,
          # but it's not necessary for the printout, since we have only specified that the print will
          # happen when the progress value is equal to exactly 100.
          # Finally, if there is NO loop (like the code you pasted originally), then you shouldn't have
          # a break.

callback()

rawDescription: How to break outside the loop?

description: Break outside the loop


code:
splitLen = 2         #  lines per file
outputBase = 'output%d.txt' # output.1.txt, output.2.txt, etc.
restBase = 'rest%d.txt'

with open('file.txt', 'r') as fp:
    input_list = fp.readlines()
    # to skip empties: input_list = [l for l in fp if l.strip()]

for i in range(0, len(input_list), splitLen):
    iteration = (i/splitLen)
    print 'iter', iteration
    with open(outputBase % iteration, 'w') as fp:
        fp.write(''.join(input_list[i:i+splitLen]))
    with open(restBase % iteration, 'w') as fp:
        fp.write(''.join(input_list[:i]))
        fp.write(''.join(input_list[i+splitLen:]))

rawDescription: Python: splitting a file into two parts

description: Python: splitting a file into two parts


code:
class foo(object):
  pass

bar = foo # Works

print type(foo)

class foo2(object):
  bar = foo2 # NameError

rawDescription: Instantiation of "type" in Python

description: Instantiation of "type" in Python


code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
url = 'any_url'
browser.get(url)
browser.find_element_by_id('empty_cart_btn').click()

try:
    WebDriverWait(browser, 5).until(EC.alert_is_present(), 'Waiting for alert timed out')

    alert = browser.switch_to_alert()
    alert.accept()
    print "alert accepted"

except TimeoutException:
    print "no alert"

rawDescription: Close dialog box automatically using Selenium python


code:
import os

filename = "a.txt"
if not os.access(filename, os.W_OK):
    print "Write access not permitted on %s" % filename

rawDescription: How to check whether a file is_open and the open_status in python

description: Check whether a file is_open and the open_status in python


code:
import urllib
import urllib2

url = 'http://59.145.203.105/Login.asp'
values = {'txtRoll' : '1305024',
          'txtEnroll' : '13139428723',
          'txhSubmit'  : 'Submit'
           }

data = urllib.urlencode(values)
binary_data=data.encode()
req = urllib2.Request(url, binary_data)
response = urllib2.urlopen(req)
the_page = response.read().decode()
print the_page

rawDescription: Urllib not loading full response

description: Urllib not loading full response


code:
class XmlMixin(list):
    """
    simple class that provides rudimentary
    xml serialisation capabiities. The class
    class uses attribute child that is a list
    for recursing the structure.
    """
    def __init__(self, *children):
        list.__init__(self, children)

    def to_xml(self):
        data = '<%(tag)s>%(internal)s</%(tag)s>'
        tag = self.__class__.__name__.lower()
        internal = ''
        for child in self:
            try:
                internal += child.to_xml()
            except:
                internal += str(child)
        return data % locals()

# some example classes these could have
# some implementation details
class Root(XmlMixin):
    pass

class View(XmlMixin):
    pass

class Config(XmlMixin):
    pass

class A_Header(XmlMixin):
    pass

root =  Root(
            View(
                Config('my config'),
                A_Header('cool stuff')
            )
       )

#add stuff to the hierarchy
root.append(
        View(
           Config('other config'),
           A_Header('not so cool')
           )
        )

print root.to_xml()

rawDescription: python object to xml hiearchy

description: Python object to xml hiearchy


code:
import numpy as np

def f(*args, **kwargs):
  length = kwargs.get("length", 1)
  ret = []
  for arg in args:
    if isinstance(arg, (float, int)):
      ret.append(np.repeat(arg, length))
    else:
      ret.append(arg)
  return tuple(ret)

print f(1, 2, length=4)

rawDescription: Convert function arguments that are floats to numpy array


code:
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print ', '.join("%s: %s" % item for item in attrs.items())

rawDescription: Print all properties of a Python Class

description: Print all properties of a Python Class


code:
import mylib

class Hello(object):
    _query = mylib.Query() # class attribute

    def say_hello(self):
        print self._query.hello()

    def say_goodbye(self):
        print self._query.goodbye()

rawDescription: How to create object variable upon inheritance?

description: Create object variable upon inheritance


code:
import time

class Foo(object):
    def __init__(self):
        self._bar = None

    @property
    def bar(self):
        if self._bar is None:
            print "starting long calculation"
            time.sleep(5)
            self._bar = 2*2
            print "finished long caclulation"
        return self._bar

foo=Foo()
print "Accessing foo.bar"
print foo.bar
print "Accessing foo.bar"
print foo.bar

rawDescription: "Caching" attributes of classes in Python


code:
import re
m1 = re.search('rice(?! with)', 'rice with beans')
m2 = re.search('rice(?! with)', 'white rice is delicious')
if m1:
  print 'm1 matches!'
  print m1.group(0)

if m2:
  print 'm2 matches!'
  print m2.group(0)

rawDescription: Complement of a regex in python

description: Complement of a regex in python


code:
animation = "|/-\\"
idx = 0
while thing_not_complete():
    print animation[idx % len(animation)] + "\r",
    idx += 1
    time.sleep(0.1)

rawDescription: 'Waiting' animation in command prompt (Python)


code:
from heapq import nlargest
from collections import defaultdict

d = defaultdict(list)

for i in xrange(len(matrix)):
    for j in xrange(i):
      d[matrix[i][j]].append((i, j))

for value, positions in nlargest(5, d.items(), key=lambda item: item[0]):
    print value, positions

rawDescription: Find highest values in similarity matrix not on diagonal


code:
words = [
'word1',
'word2',
'word3',
]

while len(words) > 0:
     word = random.choice(words)
     print "Define: %s" % word
     words.remove(word)

rawDescription: Random Word List Issue

description: Random Word List Issue


code:
from BeautifulSoup import BeautifulSoup, Comment

t = '
' +\
    '
 a 	  1
' +\
    '
 b 	  2
' +\
    '
 c 	  3
' +\
    '
 d 	  4
' +\
    '
'

bs = BeautifulSoup(t)

results = {}
for row in bs.findAll('tr'):
    aux = row.findAll('td')
    results[aux[0].string] = aux[1].string

print results

rawDescription: BeautifulSoup, a dictionary from an HTML table


code:
for i in range(0, len(myArray), N):
    print " ".join([str(v) for v in myArray[i:i+N]])
    # or this
    # print " ".join(map(str, myArray[i:i+N].tolist()))

rawDescription: How to efficiently output n items per line from numpy array

description: Efficiently output n items per line from numpy array


code:
import mechanize

links = [
"http://en.wikipedia.org/wiki/Markov_chain",
"http://en.wikipedia.org/wiki/Dari",
"http://en.wikipedia.org/wiki/Frobnab"
]

br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0')] # A white lie

for link in links:
    print link
    try:
        br.open(link)
        page_name = br.title()[:-35].replace(" ", "_")
        if page_name != link.split("/")[-1]:
            print "redirected to:", page_name
        else:
            print "page OK"
    except mechanize.URLError:
        print "error: dead link"

rawDescription: Sorting list of Wikipedia links

description: Sorting list of Wikipedia links


code:
import os
import pty

def wall(host, pw):
    pid, fd = pty.fork()
    if pid == 0: # Child
        os.execvp('ssh', ['ssh', host, 'ls', '/usr/bin/wall'])
        os._exit(1) # fail to execv

    # read '..... password:', write password
    os.read(fd, 1024)
    os.write(fd, pw + '\n')

    result = []
    while True:
        try:
            data = os.read(fd, 1024)
        except OSError:
            break
        if not data:
            break
        result.append(data)
    pid, status = os.waitpid(pid, 0)
    return status, ''.join(result)

status, output = wall('localhost', "secret")
print status
print output

rawDescription: how to give subprocess a password and get stdout at the same time

description: Give subprocess a password and get stdout at the same time


code:
import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print row[0]

rawDescription: Reading each column from csv file

description: Reading each column from csv file


code:
a = [1,2,3,4]
b = []
for i in range(len(a)):
    b.append(a[-1])
    a.pop()
    print a,b

rawDescription: Emptying a list into a new list

description: Emptying a list into a new list


code:
import time
from datetime import datetime
from apscheduler.scheduler import Scheduler

# Schedule my_job for year, month, day, hour (out of 24), minute.  Then wait.
sched = Scheduler()
sched.start()
def my_job(text):  print text
job = sched.add_date_job(my_job, datetime(2011, 7, 11, 22, 04), ['hello'])
while True:
  print datetime.now()
  time.sleep(1)

rawDescription: Schedule some jobs with php/python at some specific time without crontab


code:
#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
      'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

rawDescription: How to search if dictionary value contains certain string with Python

description: Search if dictionary value contains certain string with Python


code:
for i in range(1, len(w)+1):
    print w[:i].upper()+w[i:]

rawDescription: Python: char capitalization one-by-one

description: Python: char capitalization one-by-one


code:
import sys
import csv
from math import radians,sin,cos,asin,sqrt

def haversine(lat1,lon1,lat2,lon2,radius=3959):
    lat1,lon1,lat2,lon2 = map(radians, [lat1,lon1,lat2,lon2])
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    return 2*radius*asin(sqrt( sin(dlat/2)**2 + cos(lat1)*cos(lat2)*sin(dlon/2)**2 ))

class Zipcodes():
    def __init__(self, fname="zips.csv"):
        self.zips = {}
        with open(fname) as inf:
            r = csv.reader(inf)
            header = r.next()   # discard header row
            for row in r:
                zip = row[0].strip()
                lat = float(row[2].replace('"','').strip())
                lon = float(row[3].replace('"','').strip())
                self.zips[zip] = (lat,lon)
    def dist(self, zip1, zip2):
        try:
            lat1, lon1 = self.zips[zip1]
            lat2, lon2 = self.zips[zip2]
            return haversine(lat1,lon1,lat2,lon2)
        except KeyError:
            return 15000.0

def main():
    z = Zipcodes()

    # you figure out what goes here!
    print z.dist('35004','35007')

if __name__=="__main__":
    main()

rawDescription: Geo location using python

description: Geo location using python


code:
import csv
import urllib
import xml.etree.ElementTree as ET

path = raw_input("Enter source filepath: ")
col = int(raw_input("Column # to extract (starting with zero): "))
latlist = []
lnglist = []
try:
    with open(path, 'r+') as filein:
        data = csv.reader(filein, skipinitialspace=True)
        for item in (row[col] for row in data):
            urlpath = (
                "http://maps.googleapis.com/maps/api/geocode/xml?address=" +
                item + "&sensor=true")
            xml = urllib.urlopen(urlpath)
            tree = ET.parse(xml)
            root = tree.getroot()
            for location in root.iter('location'):
                lat = location.find('lat').text
                latlist.append(lat)
                lng = location.find('lng').text
                lnglist.append(lng)
    print "\n\nLATS\n==========================\n"
    for lats in latlist:
        print lats
    print "\n\nLONGS\n==========================\n"
    for longs in lnglist:
        print longs
except Exception as e:
    print str(e)

rawDescription: Reading a user specifed column from CSV in Python


code:
G.__mro__
print ', '.join(klass.__name__ for klass in G.__mro__)

rawDescription: the searching order of inheritance in python

description: The searching order of inheritance in python


code:
from time import mktime, localtime
from datetime import datetime
from copy import copy

def main():
    input_timestrings = ["9-28 11:07:57.435", "9-28 12:00:00.773"]
    input_datetimes = timestrings_to_datestimes(input_timestrings)

    start_datetime = input_datetimes[0]
    end_datetime = input_datetimes[1]

    # subtraction between datetime objects returns a timedelta object
    period_length = end_datetime - start_datetime

    bins = 3

    # operation w/ timedelta objects and datetime objects work pretty much as you'd expect it to
    delta = period_length / bins
    datetimes = list(custom_range(start_datetime, end_datetime + delta, delta))
    output_timestrings = datetimes_to_timestrings(datetimes)

    print output_timestrings
    return

def timestrings_to_datetimes(timestrings):
    datetimes = [datetime.strptime("2014-"+timestring, "%Y-%m-%d %H:%M:%S.%f") for timestring in timestrings]
    return datetimes

def datetimes_to_timestrings(datetimes):
    timestrings = [datetime_.strftime("%Y-%m-%d %H:%M:%S %Z%z") for datetime_ in datetimes]
    return timestrings

def custom_range(start, end, jump):
    x = start
    while x < end:
        yield x
        x = x + jump

if __name__ == "__main__":
    main()

rawDescription: string convert to datetime timezone

description: String convert to datetime timezone


code:
data = {'1' : 'see john run'}
test = 'run'

if any(test in x for x in data.values()):
    print "true"

rawDescription: Python: matching a word in dictionary value


code:
from gdata.youtube.service import YouTubeService
yt = YouTubeService()
entry = yt.GetYouTubeVideoEntry(video_id='pP9VjGmmhfo')
entry.rating
print entry.rating
entry.rating.average
entry.rating.numRaters
dir(entry.rating)
entry.rating.num_raters

rawDescription: YouTube Average Rating in Python

description: YouTube Average Rating in Python


code:
import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((640, 480),0,32)
clock = pygame.time.Clock()

def makeButton(cur, rect):
    if rect.collidepoint(cur):
        print "button pressed"

square = pygame.Rect((0,0), (32,32))

while True:
    screen.fill((255,255,255))
    screen.fill((55,155,0), square)
    pygame.display.update()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:  # left mouse button?
                makeButton(event.pos, square)

rawDescription: how to get pygame button to register only one click?

description: Get pygame button to register only one click


code:
def getstuff():
    return raw_input("Enter your result")

theresult = getstuff()
print theresult

rawDescription: Trying to capture raw_input to use later


code:
s = """
DONE The C-Arm Test cell humidity in % RH is: Observed value : 25

General Comment text :

{\rtf1\fbidis\ansi\ansicpg936\deff0{\fonttbl{\f0\fnil\fcharset0 Tahoma;}}

{*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\ltrpar\lang1033\f0\fs20 No measurements were taken\par

}

Setup done by : 502184520 Setup done on : 03/24/16
"""

start = "General Comment text :\n"
end = "\nSetup done by :"

print(s.split(start)[1].split(end)[0])

rawDescription: I want to print the string between two strings which has special characters using python regular expressions


code:
import csv
import glob
import ast
from os.path import isfile
from lxml import etree

def look_for_speaker_in_files(speakerAttrib):
    speakerDict = ast.literal_eval(speakerAttrib)
    file_name = str(speakerDict.values()[0]).format()
    l_file_exists = False
    if isfile(file_name + ".csv"):
        l_file_exists = True
    c = csv.writer(open(file_name + ".csv","a"))
    if not l_file_exists:
        c.writerow(["Name", "Filename", "Text"])
    lparser = etree.XMLParser(recover=True)
    for cr_file in glob.iglob('parsed/*.xml'):
        try:
          tree = etree.parse(cr_file,parser=lparser)
          for node in tree.iter('speaking'):
             if node.keys() == speakerDict.keys():
                if node.values() == speakerDict.values():
                    c.writerow([node.attrib, cr_file, node.text])
                else:
                    continue
             else:
                 continue
        except:
          print "bad string " + cr_file
          raise

def main():
    with open("speaking-basic.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            look_for_speaker_in_files(x)
if __name__ == "__main__":
    main()

rawDescription: How to create different files for each time a function is performed on an item in a for loop?

description: Create different files for each time a function is performed on an item in a for loop


code:
data = [1, 2, 3, 3, 3, 5, 8, 1, 8]
from collections import Counter
print [item for item, count in Counter(data).items() if count % 2]
# [2, 3, 5]

rawDescription: remove duplicate element from a list, but only those who has odd number of duplicates

description: Remove duplicate element from a list, but only those who has odd number of duplicates


code:
def lev(seq1, seq2):
    oneago = None
    thisrow = range(1, len(seq2) + 1) + [0]
    for x in xrange(len(seq1)):
        twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1]
        for y in xrange(len(seq2)):
            delcost = oneago[y] + 1
            addcost = thisrow[y - 1] + 1
            subcost = oneago[y - 1] + (seq1[x] != seq2[y])
            thisrow[y] = min(delcost, addcost, subcost)
    return thisrow[len(seq2) - 1]

def di(seq1,seq2):
    return float(lev(seq1,seq2))/min(len(seq1),len(seq2))

print lev('spa','spam')
print di('spa','spam')

rawDescription: Inbuilt Python Function for String Comparison like N-gram


code:
def foo(var):
    if var == 5:
        var = 6
    elif var == 6:
        var = 8
    else:
        var = 10

    return var

def bar(var):
    if var == 5:
        var = 6
    if var == 6:
        var = 8
    if var not in (5, 6):
        var = 10

    return var

print foo(5)        # 6
print bar(5)        # 10

rawDescription: Python: elif or new if?

description: Python: elif or new if


code:
from pebble import process, TimeoutError

with process.Pool() as pool:
    task = pool.schedule(function, args=[1,2], timeout=5)

    try:
        result = task.get()
    except TimeoutError:
        print "Task: %s took more than 5 seconds to complete" % task

rawDescription: Hard-kill hanging sub-processes in Python's multiprocessing


code:
log_list = ['a']
log_list.append('\n')
log_list.append('b')
log_list.append('c')
print '\n'.join(log_list)

rawDescription: Python - print a list adding empty lines at determined points


code:
names = ( "John", "Sal", "Bill" )
ids = ( 123, 321, 231 )
for x,y in zip(names, ids):
    print x,y

rawDescription: Multiple variables for loop python

description: Multiple variables for loop python


code:
import re
p = re.compile(ur'(.{0,50}[\s|$])')
test_str = u"jasdljasjdlk jal skdjl ajdl kajsldja lksjdlkasd jas lkjdalsjdalksjdalksjdlaksjdk sakdjakl jd fgdfgdfg\nhgkjd fdkfhgk dhgkjhdfhg kdhfgk jdfghdfkjghjf dfjhgkdhf hkdfhgkj jkdfgk jfgkfg dfkghk hdfkgh d asdada \ndkjfghdkhg khdfkghkd hgkdfhgkdhfk k dfghkdfgh dfgdfgdfgd\n"

re.findall(p, test_str)

rawDescription: Breaking text into chunks using regex?

description: Breaking text into chunks using regex


code:
import re

edges = {}

with open(dot_file) as fr:
    for line in fr:
        key = tuple(sorted(re.findall('"([a-z ]+)"', line)[:2]))
        edges.setdefault(key, []).append(line.strip())

for v in edges.values():
    if len(v) > 1:
        print re.sub("\[(.+)\]", '[\\1, dir="both"]', v[0])
    else:
        print v[0]

rawDescription: filter out symmetrical lines by python

description: Filter out symmetrical lines by python


code:
#! /usr/bin/python

list = []
while True:
    num = raw_input('please enter your number: ')
    print("You've entered", num)

    if len(list) < int(num):
        for i in range(0, len(list)):
            list[i]=list[i]+(i+1)
        for i in range(len(list), int(num)):
                list.append(i+1)
    else:
        for i in range(0, int(num)):
            list[i]=list[i]+(i+1)

    print list

rawDescription: Array list from the user

description: Array list from the user


code:
from sqlalchemy import create_engine, Column, ForeignKey, Integer, String, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)()
Base = declarative_base(bind=engine)

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, unique=True)

class Workspace(Base):
    __tablename__ = 'workspace'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    users = relationship(User, lambda: user_workspace, backref='workspaces')

user_workspace = Table(
    'user_workspace', Base.metadata,
    Column('user_id', Integer, ForeignKey(User.id), primary_key=True),
    Column('workspace_id', Integer, ForeignKey(Workspace.id), primary_key=True)
)

Base.metadata.create_all()

w1 = Workspace(name='Stack Overflow')
w2 = Workspace(name='Meta Stack Overflow')

u1 = User(name='davidism', workspaces=[w1, w2])
u2 = User(name='itmard', workspaces=[w1])
u3 = User(name='john doe')

w3 = Workspace(name='Hyphen Site', users=[u3])

session.add_all([w1, w2, w3])
session.commit()

print [u.name for u in w1.users]  # outputs ['davidism', 'itmard']

rawDescription: Model in Sqlalchemy

description: Model in Sqlalchemy


code:
from bs4 import BeautifulSoup
import urllib2

content = 'http://www.auc.nl/news-events/events-and-lectures/events-and-lectures.html?page=1&pageSize=40'

soup = BeautifulSoup(urllib2.urlopen(content))

for x in soup.findAll('h3'):
    for y in soup.findAll('p'):
        print y

rawDescription: Parsing tags with BeautifulSoup

description: Parsing tags with BeautifulSoup


code:
largest_so_far =  float('-inf')
smallest_so_far = float('inf')
i = 0
while True:

    value = raw_input(">")
    if value == "done":
        break

    try:
        value = float(value)
        i = i + 1
    except ValueError:
        print "invalid input"
        continue

    if value > largest_so_far:
            largest_so_far = value
    if value < smallest_so_far:
            smallest_so_far = value

rawDescription: Counting the number of iterations in a loop


rawDescription: Regular expression replace except first and last characters


code:
import re

# store attribute as a turple, construct a dictionary, turple_attribute: pattern
regexp = {
    ('title', ): re.compile(r'Merge (.*) into set B.*\n' ),
    ('nimages', 'height_A', 'width_A'): re.compile(r'\s+setA, (\d{1,}) images , image size (\d{1,}) X (\d{1,}).*\n'),
    ('image_no', 'shift_x', 'shift_y'): re.compile(r'\s+setA, image (\d{1,}), shape center shift \((-?\d{1,}), (-?\d{1,})\) compared to image center.*\n'),
    ('gauge_no', ): re.compile(r'Write gauge (\d{1,}), set B.*') }

with open(log_file) as f:
    for line in f:
        print(line)
        for keys, pattern in regexp.iteritems():
            m = pattern.match(line)
            if m:
                # traverse attributes
                for groupn, attr in enumerate(keys):
                    # m.group(0): content of the entrire line
                    print str(groupn)+' '+attr + ' ' + m.group(groupn+1)

rawDescription: extract critical numbers from a mixed log file

description: Extract critical numbers from a mixed log file


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

# set a seed to ensure reproducability
np.random.seed(100)

# build a random image
img = np.random.rand(10,10)

# create the image and save the artist
img_artist = plt.imshow(img, interpolation='nearest')

# plot a red cross to "mark" the pixel in question
plt.plot(5,5,'rx', markeredgewidth=3, markersize=10)

# get the color at pixel 5,5 (use normalization and colormap)
print img_artist.cmap(img_artist.norm(img[5,5]))

plt.axis('image')
plt.show()

rawDescription: python matplotlib, get pixel value after colormap applied

description: Python matplotlib, get pixel value after colormap applied


code:
def upload(prompt):
    filename = input(prompt) #ask for filename using the given prompt
    if(os.path.exists(filename)):
        uploadToS3(filename)
    else:
        print "The file you selected does not exist, please try again"
        upload(prompt) #Repeat this function if the use did not give valid input
print

raw_input("Press enter to transfer the files...")

upload("Select the fist file:")
upload("Select second file:")
upload("Select third file:")

rawDescription: Ask user to write the correct file name if he wrote wrong


code: print x.rjust(40) + x.ljust(40)

rawDescription: spacing issue in python

description: Spacing issue in python


code:
def g(y, z = None):
    if z is None:
        z = "default"
    print y, z

def f(y, z = None):
    g(y, z)

rawDescription: Python default values for parameters in delegated function calls


code:
from cPickle import dumps
from cookielib import CookieJar
import threading

class MyCookieJar(CookieJar):
    def __getstate__(self):
        state = self.__dict__.copy()
        del state['_cookies_lock']
        return state

    def __setstate__(self, state):
        self.__dict__ = state
        self._cookies_lock = threading.RLock()

class Person(object):
    def __init__(self, name):
        self.name = name
        self.cookies = MyCookieJar()

bob = Person("bob")
print dumps(bob)

rawDescription: How to pickle a CookieJar?

description: Pickle a CookieJar


code:
tmp = [x for x in mylist if x[2] == "Project A"]
if tmp and None not in zip(*tmp)[1]:
    print max(tmp)
else:
    print "no match"

rawDescription: max value if no values are none - python

description: Max value if no values are none - python


code:
class Server(peewee.Model):
    name = peewee.CharField() # instantiate it!

    class Meta:
        database = db

print Server.select().where(Server.name == 'postfix').sql()

rawDescription: peewee interpretes conditions in where clause

description: Peewee interpretes conditions in where clause


code:
import json
import urllib
import time
from geopy.geocoders import Nominatim
geolocator = Nominatim()
l = geolocator.geocode('94563') #enter the zip code you're interested in to get lat/long coords

longitude = l.longitude
latitude = l.latitude

resultslist = []
url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+str(latitude)+','+str(longitude)+'&radius=50000&types=store&key=<put your key here>' #construct URL, make sure to add your key without the <>
count = 0
ps= json.loads(urllib.urlopen(url).read())
for i in ps['results']:
    #parse results here
    resultslist.append(i)
    count += 1
if ps['next_page_token']:
    while True:
        time.sleep(2)
        npt = ps['next_page_token']

        url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+str(latitude)+','+str(longitude)+'&radius=50000&types=store&key=<yourkey>&pagetoken='+str(npt)

        ps= json.loads(urllib.urlopen(url).read())

        for i in ps['results']:
            resultslist.append(i)
            #parse results here
            count += 1

        try:
            ps['next_page_token']
        except:
            break

print 'results returned:',count

rawDescription: Google Maps API not retrieving all stores result