code:
import pygame
from random import randint
from itertools import repeat

pygame.init()
org_screen = pygame.display.set_mode((400, 400))
screen = org_screen.copy()
screen_rect = screen.get_rect()
player = pygame.Rect(180, 180, 20, 20)

def get_rock():
    return pygame.Rect(randint(0, 340), 0, 60, 60)

falling = get_rock()
clock = pygame.time.Clock()

# 'offset' will be our generator that produces the offset
# in the beginning, we start with a generator that
# yields (0, 0) forever
offset = repeat((0, 0))

# this function creates our shake-generator
# it "moves" the screen to the left and right
# three times by yielding (-5, 0), (-10, 0),
# ... (-20, 0), (-15, 0) ... (20, 0) three times,
# then keeps yieling (0, 0)
def shake():
    s = -1
    for _ in xrange(0, 3):
        for x in range(0, 20, 5):
            yield (x*s, 0)
        for x in range(20, 0, 5):
            yield (x*s, 0)
        s *= -1
    while True:
        yield (0, 0)

while True:
    if pygame.event.get(pygame.QUIT): break
    pygame.event.pump()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]: player.move_ip(0, -2)
    if keys[pygame.K_a]: player.move_ip(-2, 0)
    if keys[pygame.K_s]: player.move_ip(0, 2)
    if keys[pygame.K_d]: player.move_ip(2, 0)
    player.clamp_ip(screen_rect)

    falling.move_ip(0, 4)
    org_screen.fill((0, 0, 0))
    screen.fill((255,255,255))
    pygame.draw.rect(screen, (0,0,0), player)
    pygame.draw.rect(screen, (255,0,0), falling)

    if player.colliderect(falling):
        # if the player is hit by the rock,
        # we create a new shake-generator
        offset = shake()
        falling = get_rock()

    if not screen_rect.contains(falling):
        falling = get_rock()

    clock.tick(100)
    # here we draw our temporary surface to the
    # screen using the offsets created by the
    # generators.
    org_screen.blit(screen, next(offset))
    pygame.display.flip()

rawDescription: pygame shaking window when loosing lifes

description: Pygame shaking window when loosing lifes


code:
import logging
from logging.handlers import RotatingFileHandler

log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')

logFile = 'C:\\Temp\\log'

my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024,
                                 backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO)

app_log = logging.getLogger('root')
app_log.setLevel(logging.INFO)

app_log.addHandler(my_handler)

while True:
    app_log.info("data")

rawDescription: How to limit log file size in python

description: Limit log file size in python


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

# define your x and y arrays to be plotted
t = np.linspace(start=0, stop=2*np.pi, num=100)
y1 = np.cos(t)
y2 = np.sin(t)
y3 = np.tan(t)
plots = [(t,y1), (t,y2), (t,y3)]

# now the real code :)
curr_pos = 0

def key_event(e):
    global curr_pos

    if e.key == "right":
        curr_pos = curr_pos + 1
    elif e.key == "left":
        curr_pos = curr_pos - 1
    else:
        return
    curr_pos = curr_pos % len(plots)

    ax.cla()
    ax.plot(plots[curr_pos][0], plots[curr_pos][1])
    fig.canvas.draw()

fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', key_event)
ax = fig.add_subplot(111)
ax.plot(t,y1)
plt.show()

rawDescription: Scroll backwards and forwards through matplotlib plots


code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from lib import user
import guest
import authorized

def main():
    if user.isLoggedIn():
        run_wsgi_app(authorized.application)
    else:
        run_wsgi_app(guest.application)

if __name__ == "__main__":
    main()

rawDescription: Google App Engine Application Cache

description: Google App Engine Application Cache


code: np.where(np.in1d(x, y))

rawDescription: Getting indices of elements that are in another list in numpy


code:
if platform == windows:
    vars = win_vars
elif platform == posix:
    vars = lin_vars

rawDescription: A dictionary for each variable or a dictionary for all variables?


code:
_file = os.path.abspath(sys.argv[0])
path = os.path.dirname(_file)

rawDescription: Get path to exe file on py2exe

description: Get path to exe file on py2exe


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

wait = WebDriverWait(driver, 10)

while True:
    # do the scrolling
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    try:
        wait.until(EC.visibility_of_element_located((By.XPATH, "//*[. = 'Loading...']")))
    except TimeoutException:
        break  # not more posts were loaded - exit the loop

rawDescription: Stop the Scroll in Dynamic Page with Selenium in Python


rawDescription: Integer to Unique String

description: Integer to Unique String


code:
import pandas as pd
import numpy as np

maskA_str = "maskA - a: 4, 8 - b: 1, 5 - c: 1"
df = pd.DataFrame(
    {'a': np.random.randint(1, 10, 100),
     'b': np.random.randint(1, 10, 100),
     'c': np.random.randint(1, 10, 100)}
)

def create_query_str(mask_str):
    mask_name, column_conds = mask_str.split('-')[0], mask_str.split('-')[1:]
    query_str = '('
    column_strs =[]
    for cond in column_conds:
        cond_str = '('
        column, vals = cond.split(':')
        column = column.strip()
        test_strs = ['{c} == {v}'.format(c=column, v=val.strip())
                     for val in vals.split(',')]
        cond_str += ' | '.join(test_strs)
        cond_str += ')'
        column_strs.append(cond_str)
    query_str += ' & '.join(column_strs)
    query_str += ')'
    return query_str

create_query_str(maskA_str)
Out[17]: '((a == 4 | a == 8) & (b == 1 | b == 5) & (c == 1))'

# Can now be used directly in df.query()
df.query(create_query_str(maskA_str))

rawDescription: Construct Boolean masks based on unknown number of columns and values


code:
df
df1 = df.pivot(index='uid', columns='msg', values='_time').reset_index()
df1 = df1.merge(df[['uid', 'gender', 'age']].drop_duplicates(), on='uid')
df1

rawDescription: Creating new rows and new columns based on row data in pandas


code:
testsrt = 'I\'m reading a text file line by line and i want to ignore all occurrences of and , To and From and return the rest. Is there a function in python that will allow me to do that? Thanks for your help.'
ts = testsrt.split(' ')
excl = ["and", "To", "From"]
' '.join([t for t in ts if not t in excl])

rawDescription: how to read a line and ignore some words (python)

description: Read a line and ignore some words (python)


code:
import wx

class Summary(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Playing with Simple Sizers", size=(430,260))

        self.panel = wx.Panel(self, wx.ID_ANY)
        self.log = wx.TextCtrl(self.panel, wx.ID_ANY, value="input1:",size=(428,25))
        self.log2 = wx.TextCtrl(self.panel, wx.ID_ANY, value="input2:", size=(428,25))
        self.quit_button = wx.Button(self.panel, label="Quit",size=(60,25))
        self.button1= wx.Button(self.panel, label="1",)
        self.button2 = wx.Button(self.panel, label="2",size=(60,25))
        self.button3 = wx.Button(self.panel, label="3",size=(60,25))
        self.button4 = wx.Button(self.panel, label="4",size=(60,25))
        self.quit_button.Bind(wx.EVT_BUTTON, self.OnQuit)

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        hbox4 = wx.BoxSizer(wx.HORIZONTAL)

        vbox.Add(self.quit_button, 0, wx.ALL|wx.EXPAND, 1)
        hbox1.Add(self.log, 0, wx.ALL|wx.EXPAND, 1)
        hbox2.Add(self.log2, 0, wx.ALL|wx.EXPAND, 1)

        hbox3.Add(self.button1, 1, wx.ALL|wx.EXPAND, 1)
        hbox3.Add(self.button2, 2, wx.ALL|wx.EXPAND, 1)
        hbox4.Add(self.button3, 0, wx.ALL|wx.EXPAND, 1)
        hbox4.Add(self.button4, 1, wx.ALL|wx.EXPAND, 1)

        vbox.Add(hbox1, 0, wx.ALIGN_RIGHT|wx.EXPAND, 1)
        vbox.Add(hbox3, 0, wx.ALIGN_RIGHT|wx.EXPAND, 1)
        vbox.Add(hbox4, 0, wx.ALIGN_RIGHT|wx.EXPAND, 1)
        vbox.Add(hbox2, 0, wx.ALIGN_RIGHT|wx.EXPAND, 1)

        self.panel.SetSizer(vbox)
        self.Show()

    def OnQuit(self, event):
        self.Close()
# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = Summary()
    app.MainLoop()

rawDescription: How to prevent vertical sizers from expanding their children all the way downwards in wxformbuilder

description: Prevent vertical sizers from expanding their children all the way downwards in wxformbuilder


code:
import Tkinter as tk
import time

def Draw():
    global text

    frame=tk.Frame(root,width=100,height=100,relief='solid',bd=1)
    frame.place(x=10,y=10)
    text=tk.Label(frame,text='HELLO')
    text.pack()

def Refresher():
    global text
    text.configure(text=time.asctime())
    root.after(1000, Refresher) # every second...

root=tk.Tk()
Draw()
Refresher()
root.mainloop()

rawDescription: Python Tkinter Label redrawing every 10 seconds


rawDescription: python: Multiply two 1d matrices in numpy

description: Python: Multiply two 1d matrices in numpy


code:
def dehydrate(self, bundle):
    bundle.data['entry'] = bundle.obj.entry.id
    return bundle

def hydrate(self, bundle):
    bundle.data['entry'] = Entry.objects.get(id=bundle.data['entry'])
    return bundle

rawDescription: Tastypie: Don't send the whole uri of resource (just the id)


code:
notebook.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT,
                         wx.FONTWEIGHT_NORMAL,
                         wx.FONTSTYLE_NORMAL))

rawDescription: Changing tab text size in wxpython notebook


code:
DATA = [ [2,5,8], [2,4,3], [5,5,7], [9,8,4] ]
LABELS = [ "AAA", "BBB", "AAA", "CCC" ]
get_labels = {tuple(x):y for x,y in zip(DATA,LABELS)}
get_labels[5,5,7]
get_labels[9,8,4]

rawDescription: Fast way to get the label of an item x (in DATA) from a list of labels


code:
for line in f:
    mo = re.match(r'^(\S+)\s+"(.*?)"\s*$')
    if not mo: continue
    key, value = mo.groups()
    setattr(objInstance, key, value)

rawDescription: Parsing files with python

description: Parsing files with python


code:
import uno

ctx = uno.getComponentContext()
service_manager = ctx.getServiceManager()
desktop = service_manager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
document = desktop.loadComponentFromURL("file:///file.doc", "_blank", 0, ())

replace_desc = document.createReplaceDescriptor()
replace_desc.setSearchString("text_to_replace")

find_iter = document.findFirst(replace_desc)
while find_iter:
    find_iter.String = "replacement_text"
    find_iter = document.findNext(find_iter.End, replace_desc)

rawDescription: Remote control or script Open Office to edit Word document from Python


code:
import os

def get_file_path(file):
    for (root, dirs, files) in os.walk('.'):
        if file in files:
            return os.path.join(root, file)

rawDescription: Open a file without specifying the subdirectory python


code:
conmy = MySQLdb.connect(host, user, passwd, db)
cursor = conmy.cursor()
sql_query = "REPLACE INTO globalid (stub) VALUES ('a')"
cursor.execute(sql)
last_insert_id = conmy.insert_id()
conmy.close()

rawDescription: How to execute multi query in python?

description: Execute multi query in python


code:
import re

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

rawDescription: sorting list in python

description: Sorting list in python


code:
import wx
import sys

employees = [('Earl Boffo', 'Software'), ('Mildred Plotka', 'Software'), ('Sugar Kane', 'QA')]

classes = [('Python'), ('Java'), ('C#')]

class EmployeesPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        # create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.list = wx.ListCtrl(self, size=(100,100), style=wx.LC_REPORT)

        self.list.InsertColumn(0, 'Name')
        self.list.InsertColumn(1, 'Group')

        for i in employees:
            index = self.list.InsertStringItem(sys.maxint, i[0])
            self.list.SetStringItem(index, 1, i[1])

        # A button
        self.button = wx.Button(self, label="Exit")
        self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)

        mainSizer.Add(self.list, 0, wx.EXPAND|wx.ALL, 5)
        mainSizer.Add(self.button, 0, wx.ALL, 5)

        self.SetSizer(mainSizer)
        self.Show()

    def EvtComboBox(self, event):
        self.logger.AppendText('EvtComboBox: %s\n' % event.GetString())
    def OnClick(self,event):
        sys.exit(3)

app = wx.App(False)
frame = wx.Frame(None, title="Training Tracker", size=(700,500))
nb = wx.Notebook(frame)

nb.AddPage(EmployeesPanel(nb), "Employees")
frame.Show()
app.MainLoop()

rawDescription: wxListCtrl not displaying properly

description: WxListCtrl not displaying properly


code:
import functools

def execonce(f):

    @functools.wraps(f)
    def donothing(*a, **k):
        pass

    @functools.wraps(f)
    def doit(self, *a, **k):
        try:
            return f(self, *a, **k)
        finally:
            setattr(self, f.__name__, donothing)

    return doit

rawDescription: Decorator to mark a method to be executed no more than once even if called several times


code:
import os, tempfile
fd, self._undo_fname = tempfile.mkstemp(suffix='.undoredo', dir='/tmp')
os.close(fd)
self._undo_buffer = shelve.open(self._undo_fname)

rawDescription: Temporary Shelves?

description: Temporary Shelves


code:
x = numpy.random.random((3,3))
y = x[..., numpy.newaxis]
y
y.shape
x.shape

rawDescription: Numpy array of rank > 1 and one of dimensions == 0


rawDescription: smtplib sending multiple messages instead of one

description: Smtplib sending multiple messages instead of one


code:
f1 = open('someFile', 'r')
f2 = open('someFile', 'r')
hash(f1)
hash(f2)

rawDescription: What does __hash__ on a Python file object do?


code: a['foo'] = [b[el] for el in a['foo']]

rawDescription: Best way to combine two dicts, merging on values of first and keys of second

description: Combine two dicts, merging on values of first and keys of second


code:
dti = pd.DatetimeIndex(['2014-08-31', '2014-09-01'])
pdt = dti.to_pydatetime()
sdt = np.vectorize(lambda s: s.strftime('%Y%m%d'))(pdt)
idt = sdt.astype('I4')
idt

rawDescription: Convert Pandas DateTimeIndex to YYYYMMDD integer?


code:
import Tkinter as tk
import ttk

class Example(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.floater = FloatingWindow(self)

class FloatingWindow(tk.Toplevel):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.overrideredirect(True)
        self.wm_geometry("400x400")

        self.label = tk.Label(self, text="Grab the lower-right corner to resize")
        self.label.pack(side="top", fill="both", expand=True)

        self.grip = ttk.Sizegrip(self)
        self.grip.place(relx=1.0, rely=1.0, anchor="se")
        self.grip.lift(self.label)
        self.grip.bind("<B1-Motion>", self.OnMotion)

    def OnMotion(self, event):
        x1 = self.winfo_pointerx()
        y1 = self.winfo_pointery()
        x0 = self.winfo_rootx()
        y0 = self.winfo_rooty()
        self.geometry("%sx%s" % ((x1-x0),(y1-y0)))
        return

app=Example()
app.mainloop()

rawDescription: Tkinter: windows without title bar but resizable


code:
b = np.asarray(a, dtype=float)
#to get the same shape do.
b = b.reshape(-1, len(b))
#to just get one dimmension do.
b = np.asarray(a, dtype=float).reshape(len(a))

rawDescription: python: list of matrices to numpy array?

description: Python: list of matrices to numpy array


code:
from django.db.models import Q

threshold = {
    'hot': Q(post_upvotes__gt=50),
    'trending': Q(post_upvotes__range=(20,50)),
    'new': Q(post_upvotes__lt=20)
}

return Post.objects.filter(threshold[section])

rawDescription: Django orm filter is an element of dict

description: Django orm filter is an element of dict


code:
class Window(QtGui.QDialog):

    def __init__(self):
        super(Window, self).__init__()
        self.resize(600,400)

        self.mainLayout = QtGui.QVBoxLayout(self)
        self.mainLayout.setMargin(10)

        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.mainLayout.addWidget(self.scroll)

        scrollContents = QtGui.QWidget()
        self.scroll.setWidget(scrollContents)

        self.textLayout = QtGui.QVBoxLayout(scrollContents)
        self.textLayout.setMargin(10)

        for _ in xrange(5):
            text = GrowingTextEdit()
            text.setMinimumHeight(50)
            self.textLayout.addWidget(text)

class GrowingTextEdit(QtGui.QTextEdit):

    def __init__(self, *args, **kwargs):
        super(GrowingTextEdit, self).__init__(*args, **kwargs)
        self.document().contentsChanged.connect(self.sizeChange)

        self.heightMin = 0
        self.heightMax = 65000

    def sizeChange(self):
        docHeight = self.document().size().height()
        if self.heightMin <= docHeight <= self.heightMax:
            self.setMinimumHeight(docHeight)

rawDescription: A QWidget like QTextEdit that wraps its height automatically to its contents?


rawDescription: Plotting 3D surface graphs with lists

description: Plotting 3D surface graphs with lists


code:
numbers_sizes = (i*10**exp for exp in range(2, 9) for i in range(1, 10))
for n in numbers_sizes:
    test(n)

rawDescription: How to generate exponentially increasing range in Python

description: Generate exponentially increasing range in Python


code:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override","your_user_agent_string")
driver=webdriver.Firefox(profile)

rawDescription: Pass the user-agent through webdriver in Selenium


rawDescription: My re.finditer shows everything when using .group(0), but if I use .group(5) it shows an empty string (python)


code:
import inspect

def foo(arg1, arg2, arg3=None , *args, **kwargs):
    """This function is really cool."""
    return

def functionprinter(f):

    print("{}{}".format(f.__name__, inspect.signature(f)))
    print(inspect.getdoc(f))

functionprinter(foo)

rawDescription: How can I print the function head, including name, arguments, and docstring?

description: Print the function head, including name, arguments, and docstring


code:
import random
def get_num():
    return random.randrange (999,9999)

def get_user_input():
    user_input = int(input())
    return user_input

while True:
    comp_num = get_num()
    print("The computer gave: {}".format(comp_num))

    print("Your turn:")
    user_num = get_user_input()

    if user_num == comp_num:
        print("Done it!")
        break
    else:
        print("No, it's different. Try again!")
        print()

rawDescription: Python: Break statements for while blocks


code:
g = open(file,'r')
names = {}
for line in g.readlines():
    name = line.split('\t')[1] #Name is in the second tab
    names[name] = 1 #create a dictionary with the names

#names.keys() returns a list of all the names here
# change the file handle here if needed, or the original file would be overwritten.
h = open(file,'w+')
for name in names.keys():
    h.write("%s\n"%name)

rawDescription: Copying a column without repeating

description: Copying a column without repeating


code:
keyBinary = bin(int(key, 16))[2:].zfill(64)
keyBinary = [int(i) for i in keyBinary]

Kplus = permute(PC1table, keyBinary)

def permute(mapping, permuteInput):
    permuteOutput = []

    for i in range(len(mapping)):
        permuteOutput.append(permuteInput[mapping[i % 56] - 1])

    return permuteOutput

rawDescription: Permuting on a schedule python

description: Permuting on a schedule python


code:
lines = []

with open('myfile.txt') as file:
    for line_number, line in enumerate(file, start=1):
        if line_number not in [1, 6, 7]:
            lines.append(line)

with open('myfile.txt', 'w') as file:
    file.writelines(lines)

rawDescription: Python open file and delete a line

description: Python open file and delete a line


code:
import urllib2

username = 'user1'
password = '123456'

#This should be the base url you wanted to access.
baseurl = 'http://server_name.com'

#Create a password manager
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, baseurl, username, password)

#Create an authentication handler using the password manager
auth = urllib2.HTTPBasicAuthHandler(manager)

#Create an opener that will replace the default urlopen method on further calls
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)

#Here you should access the full url you wanted to open
response = urllib2.urlopen(baseurl + "/file")

rawDescription: Download a file from https with authentication


code:
def myGenerator(arg1, arg2):
    for i in arg1:
        myState = doSomeWork(i, arg2)
        yield myState

myGen = myGenerator(list1, list2)
tenthElement = expensiveOperation(next(itertools.islice(myGen,10,11)))

rawDescription: Python Generator Indexing Optimization

description: Python Generator Indexing Optimization


code:
lst  = range(1000)
id(lst)
lst = lst[::-1]
id(lst)             #id changed.
lst  = range(1000)
id(lst)
lst.reverse()
id(lst)             #same id

rawDescription: How to know if a command or method is an 'in place algorithm'?

description: Know if a command or method is an 'in place algorithm'


code:
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()

dict = r1.getheaders()
print(dict)

rawDescription: Convert http headers (string) to a python dictionary


code:
import os

FList = os.listdir(os.getcwd())
FListC = FList[1:]

m = 0
for i in FListC:
    fileExtension = os.path.splitext(i)[1]
    os.rename(i,str(m)+fileExtension)
    m = m+1

rawDescription: Rename All Files in a Directory with consecutive numbers in Python


code:
# not needed for python 3
import sip
sip.setapi('QString', 2)

from collections import defaultdict
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.tree = QtGui.QTreeWidget(self)
        self.tree.header().hide()
        for index in range(5):
            parent = QtGui.QTreeWidgetItem(self.tree, ['NUS2K%s' % index])
            if index % 3:
                parent.setCheckState(0, QtCore.Qt.PartiallyChecked)
            else:
                parent.setCheckState(0, QtCore.Qt.Unchecked)
            features = 'Loader Reports Logging'.split()
            for count, item in enumerate(features):
                child = QtGui.QTreeWidgetItem(parent, [item])
                if index % 3 and count % 3:
                    child.setCheckState(0, QtCore.Qt.Checked)
                else:
                    child.setCheckState(0, QtCore.Qt.Unchecked)
            parent.setExpanded(True)
        self.button = QtGui.QPushButton('Export', self)
        self.button.clicked.connect(self.handleExport)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.tree)
        layout.addWidget(self.button)

    def handleExport(self):
        mapping = self.exportTree()
        for machine, features in mapping.items():
            print('%s:' % machine)
            for feature in features:
                print('  %s' % feature)

    def exportTree(self):
        mapping = defaultdict(list)
        root = self.tree.invisibleRootItem()
        for index in range(root.childCount()):
            parent = root.child(index)
            if parent.checkState(0) == QtCore.Qt.PartiallyChecked:
                features = mapping[parent.text(0)]
                for row in range(parent.childCount()):
                    child = parent.child(row)
                    if child.checkState(0) == QtCore.Qt.Checked:
                        features.append(child.text(0))
        return mapping

if __name__ == '__main__':

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

rawDescription: Using QTreeWidgetItemIterator in PyQT4 to return isChecked from QTreeWidget as a dictionary (or...something)


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import time

a=np.array([35,25,24,25,27,28,30,35])

df=pd.DataFrame(index=pd.date_range("00:00", "23:00",freq="3H").time,data={'column1':a})

df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]]))

# Now we create the figure and the axes
fig,axes=plt.subplots()
axes.plot(df['column1'])  # In the x axis will appear 0,1,2,3...
axes.set_xticklabels(df.index)  # now we change the labels of the xaxis

plt.show()

rawDescription: how to plot time series where x-axis is datetime.time object in matplotlib?

description: Plot time series where x-axis is datetime.time object in matplotlib


code:
import fractions

class MyFraction:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def simplify(self):
        rtr=fractions.Fraction(self.a, self.b)
        print('"simplify({}, {})"={}'.format(self.a,self.b, rtr))
        return rtr

    #simplify, simplifies the fraction.(2/4 to 1/2)
    #add, adds two fractions and then returns the simplified fraction.
    def __repr__(self):
        return '{}/{}'.format(self.a, self.b)

    # alternatively, if you want to always print a simplified fraction:
    # def __str__(self):
        # return fractions.Fraction(self.a, self.b).__str__()

    def __add__ (self, f):
        if (self.b == f.b) :
            return MyFraction(self.a + f.a , f.b).simplify()
        else :
            pro = self.b * f.b
            return MyFraction(self.a * f.b + f.a * self.b , pro).simplify()

print(MyFraction(2,4))
# 2/4
print(MyFraction(1, 2)+MyFraction(20, 30))
# "simplify(70, 60)"=7/6
# 7/6

rawDescription: How can I call local functions inside another local function at the return statement?

description: Call local functions inside another local function at the return statement


code:
class MyModelAdmin(admin.ModelAdmin):
    fields = ("name",)

    def save_model(self, request, obj, form, change):
        if not change:
            # the object is being created, so set the user
            obj.created_by = request.user
        obj.save()

rawDescription: Django admin model field set to current user


code:
from time import strftime
import os.path
import contextlib
import cStringIO
import sys

# create a context which we can use for any block which we can use for any
# block which we do not want to print stdout
# -- taken from http://stackoverflow.com/a/2829036/217652

@contextlib.contextmanager
def nostdout():
    save_stdout = sys.stdout
    sys.stdout = cStringIO.StringIO()
    yield
    sys.stdout = save_stdout

ip = get_ipython()

ldir = ip.profile_dir.log_dir
fname = strftime('%Y-%m-%d-%H-%M-%S') + ".py"
filename = os.path.join(ldir, fname)

# stdout is now muted
with nostdout():
    ip.run_line_magic('logstart', '-o %s append' % filename)

rawDescription: How can I log IPython's output without the ugly 7 lines of logging-info on every load?

description: Log IPython's output without the ugly 7 lines of logging-info on every load


code:
def refresh(self):
    return type(self).get(self._pk_expr())

rawDescription: How to reselect record with peewee

description: Reselect record with peewee


code: from scipy.signal import convolve2d

rawDescription: cannot import scipy.signal.convolve2d

description: Cannot import scipy.signal.convolve2d


code:
from collections import defaultdict

bigdict = defaultdict(dict)
for ln in file:
    a,b,c,d,e = ln.split()
    bigdict[(a,b)][(c,d)] = e

rawDescription: Python - Read a complicated file into dictionary


code:
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.ext.declarative import declared_attr

class MessageMixIn(object):
    ttime = Column(DateTime)

    @declared_attr
    def sometable_id(cls):
        return Column(Integer, ForeignKey('sometable.id'))

    @declared_attr
    def __table_args__(cls):
        return (UniqueConstraint('sometable_id', 'ttime'), {})

rawDescription: Reusing SQLAlchemy models across projects


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableView(self)
        model =  QtGui.QStandardItemModel(rows, columns, self.table)
        for row in range(rows):
            for column in range(columns):
                item = QtGui.QStandardItem('(%d, %d)' % (row, column))
                item.setTextAlignment(QtCore.Qt.AlignCenter)
                model.setItem(row, column, item)
        self.table.setModel(model)
        self.buttonPrint = QtGui.QPushButton('Print', self)
        self.buttonPrint.clicked.connect(self.handlePrint)
        self.buttonPreview = QtGui.QPushButton('Preview', self)
        self.buttonPreview.clicked.connect(self.handlePreview)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.table, 0, 0, 1, 2)
        layout.addWidget(self.buttonPrint, 1, 0)
        layout.addWidget(self.buttonPreview, 1, 1)

    def handlePrint(self):
        dialog = QtGui.QPrintDialog()
        if dialog.exec_() == QtGui.QDialog.Accepted:
            self.handlePaintRequest(dialog.printer())

    def handlePreview(self):
        dialog = QtGui.QPrintPreviewDialog()
        dialog.paintRequested.connect(self.handlePaintRequest)
        dialog.exec_()

    def handlePaintRequest(self, printer):
        document = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(document)
        model = self.table.model()
        table = cursor.insertTable(
            model.rowCount(), model.columnCount())
        for row in range(table.rows()):
            for column in range(table.columns()):
                cursor.insertText(model.item(row, column).text())
                cursor.movePosition(QtGui.QTextCursor.NextCell)
        document.print_(printer)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(25, 2)
    window.resize(300, 400)
    window.show()
    sys.exit(app.exec_())

rawDescription: Printing Pyside QTableView

description: Printing Pyside QTableView


code:
depth = glReadPixels(self.mouseX, self.height()-self.mouseY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT)
z = 2*depth -1

mouseWorld = (self.viewport*self.matProj*self.matView*self.matModel).I*np.matrix([[self.mouseX, self.mouseY, z, 1]]).T

rawDescription: From mouse coordinates to world coordinates through glUnproject


code:
import subprocess
cmd = [r"c:\program files\adobe\combiner"]
cmd.extend(file_list)
p = subprocess.Popen(cmd)

rawDescription: Python programming. Accessing Windows right click menu options


rawDescription: Print over Current Line in Python Shell

description: Print over Current Line in Python Shell


code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

class ExampleHandler(webapp.RequestHandler):
    def get(self, name="default"):
        self.response.out.write('Hello %s!' % name)

def main():
    application = webapp.WSGIApplication([('/example/(\w+)', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)

rawDescription: How to create the subpaths that exactly match to the users’ name

description: Create the subpaths that exactly match to the users’ name


code:
import subprocess
io = subprocess.Popen('ls', stdout=subprocess.PIPE).stdout
for line in io: print(line.strip())

rawDescription: How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls?

description: Translate Ruby's IO.popen calls into Python's subprocess.Popen calls


code:
txt = "Today it's \t07.May 2011. Or 2.999."
p = re.compile(r"\d+|[-'a-z]+|[ ]+|\s+|[.,]+|\S+", re.I)
slice_starts = [m.start() for m in p.finditer(txt)] + [None]
[txt[s:e] for s, e in zip(slice_starts, slice_starts[1:])]

rawDescription: RegEx Tokenizer: split text into words, digits, punctuation, and spacing (do not delete anything)


code: json.dumps([dict(mpn=pn) for pn in lst])

rawDescription: Python: Convert a list of python dictionaries to an array of JSON objects


code:
strs= "Hello world"
[y for x in strs.split() for y in (x[:i] for i in  xrange(2,len(x)+1)) ]

rawDescription: Python : parse string to sub string for searching


code:
import numpy as np

x = np.random.normal(size=(206,11,11))
y = np.random.normal(size=(206,11,11))
complx = x + 1j*y

# takes only the diagonal part of all the 11x11 matrices
complx_diag = np.diagonal(complx,0,1,2)

# do the calc
zn = np.abs(complx_diag)**(-0.5)

for n in xrange(a):
    z = zn[n]
    # do your stuff

rawDescription: speed up looping over three axis' in numpy

description: Speed up looping over three axis' in numpy


code:
SPECIALS = {"0": 10, "J": 11, "Q": 12, "K": 13, "A": 14}

def getCardValue(inputVal):
    special = inputVal[:-1]
    return SPECIALS.get(special, int(special))

def score_phase(bids, tricks, deck_top):
    # Unwrap tricks
    tricks = tricks[0]

    # Convert to a high score list.
    result = [0 if deck_top[-1] != x[-1] else getCardValue(x)
              for x
              in tricks]
    best = max(result)

    winners = [i for i in range(len(result)) if result[i] == best]
    print('Winner(s) by index: {}'.format(', '.join(str(winner)
                                                    for winner
                                                    in winners)))

    def score(i):
        if bids[i] > 0:
            if result[i] == best:
                return 11
            else:
                return 0
        else:
            if result[i] == best:
                return 1
            else:
                return 10

    return [score(i) for i in range(len(bids))]

if __name__ == '__main__':
    print(score_phase((0, 0, 0, 0), (('9D', '9S', '3S', '0D'),), '2D'))

rawDescription: Update a defaultdict when iterating through a tuple during a trick in a poke game


code:
def dotproduct(vec1, vec2):
    return sum(imap(operator.mul, vec1, vec2))
dis.dis(dotproduct)
def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
    return sum(imap(mul, vec1, vec2))
dis.dis(dotproduct)

rawDescription: Setting local variables to a function instead of using globals optimize the function


code:
attrname = 'itemprop'
attrvalue = 'price'
search = {attrname: attrvalue}

priceele = soup.find(**search).string.strip()

rawDescription: Pass variable in soup.find() method - Beautifulsoup Python


code:
content = []
filename='foo.txt'
with open(filename, 'r') as read_file:
    content = read_file.readlines()

with open(filename, 'w') as write_file:
    for line in content:
        write_file.write(line.replace("red", "RED"))

rawDescription: Replace certain words in a text file

description: Replace certain words in a text file


code:
ax = kmf.plot()
ax.get_figure().savefig("myfigure.png")

rawDescription: how to save the pic that lifelines module plot

description: Save the pic that lifelines module plot


code:
MyForm(initial={
    'my_multi': ['a', 'b', 'c']
})

rawDescription: How to make pre-selected checkbox in django?

description: Make pre-selected checkbox in django


code:
import re

soup = BeautifulSoup(htm, "html.parser")

pattern = re.compile(r"\(([A-Z]+)\)$")
for item in soup.select(".company-list .list-group-item"):
    match = pattern.search(item.get_text())
    if match:
         print(match.group(1))

rawDescription: How to parse nested items with BeautifulSoup?

description: Parse nested items with BeautifulSoup


code:
tar = tarfile.open("/backup/output_filename.tar.gz", "w:gz")
tar.add(input)
tar.close()

rawDescription: Specify destination for tarfile

description: Specify destination for tarfile


code:
def print_diff_files(dirs):
    for name in dirs.diff_files:
        diff_files.append(os.path.join(dirs.left, name))
        diff_files.append(os.path.join(dirs.right, name))
    for file_left in dirs.left_only:
        only_left.append(os.path.join(dirs.left, file_left))
    for file_right in dirs.right_only:
        only_right.append(os.path.join(dirs.right, file_right))
    for same_files in dirs.same_files:
        same_files_list.append(os.path.join(dirs.left, same_files))
        same_files_list.append(os.path.join(dirs.right, same_files))
    for sub_dirs in dirs.subdirs.values():
        print_diff_files(sub_dirs)

DirCompare = filecmp.dircmp('old', 'new')
print_diff_files(DirCompare)

rawDescription: Recursive compare directories by Python 3


code:
import re

pat = re.compile(r'*.certain_string.*', re.I)
db.collection.find({'Url': {'$regex': pat}})

rawDescription: How to translate contains condition statement in mongodb query using pymongo to get data in pandas dataframe?

description: Translate contains condition statement in mongodb query using pymongo to get data in pandas dataframe


code:
from scrapy.conf import settings
from scrapy.contrib.exporter import CsvItemExporter

class CSVkwItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        kwargs['fields_to_export'] = settings.getlist('EXPORT_FIELDS') or None
        kwargs['encoding'] = settings.get('EXPORT_ENCODING', 'utf-8')

        super(CSVkwItemExporter, self).__init__(*args, **kwargs)

        self._join_multivalued = settings.get('MY_CSV_DELIMITER', ',')

rawDescription: How to override join_multivalued option of CsvItemExporter

description: Override join_multivalued option of CsvItemExporter


code:
import json

with open('text.json') as f:
    obj = json.load(f)

rawDescription: JSON Python Evaluation

description: JSON Python Evaluation


code:
import tkinter as tk
import customfunc

def run():
    root = tk.Tk()
    s_var = tk.StringVar()
    tk.Label(root, textvariable = s_var).pack()

    def update_time():
        s_var.set(customfunc.func())
        root.after(1000, update_time)

    update_time()
    root.mainloop()

if __name__ == "__main__":
    run()

rawDescription: Python/Tkinter: Update button from every second


code:
from PIL import ImageOps

img = Image.open("")
back = Image.new('RGBA', img.size)
back.paste(img)
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.rectangle([(10,10),(100,100)],
          fill=(255,255,255,200))
inverted_poly = ImageOps.invert(poly)
back.paste(poly, (0,0), mask=inverted_poly)
back.show()

rawDescription: Python PIL: Make pixels outside a polygon transparent


code:
text = 'column'
parsed = re.search(r'(\w+)(?:{(\w+)})?', text)
parsed.groups()

rawDescription: Capture group inside non-capturing group


code:
import wx

class Example(wx.Frame):
    def __init__(self, parent, title):
        ##super(Example, self).__init__(parent, title=title,
        ##                                size=(500,  #width
        ##                                      300)) #height
        wx.Frame.__init__(self, None, size=(900,270))
        self.InitUI()
        self.Centre()
        self.Show()

    #define User Interface
    def InitUI(self):
        self.sizer = wx.BoxSizer() # Main window sizer

        self.panel1 = wx.Panel(self, -1)
        self.sizer.Add(self.panel1, 1, flag=wx.EXPAND)

        #Menu bar
        menubar = wx.MenuBar()
        filem = wx.Menu()
        editm = wx.Menu()
        helpm = wx.Menu()

        menubar.Append(filem, '&File')
        menubar.Append(editm, '&Edit')
        menubar.Append(helpm,'&help')
        self.SetMenuBar(menubar)

        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        #buttons
        b1 = wx.Button(self.panel1, label='button', size=(300,30), pos=(0,0))
        self.hbox.Add(b1)
        b1.Bind(wx.EVT_BUTTON, self.OnB1)
        self.panel1.SetSizer(self.hbox)

        #panel2
        self.panel2 = wx.Panel(self, -1)
        self.sizer.Add(self.panel2, 1, flag=wx.EXPAND)
        self.panel2.Hide()
        self.vbox = wx.BoxSizer(wx.HORIZONTAL)
        b2 = wx.Button(self.panel2, label='button2', size=(300,30), pos=(0,0))
        self.vbox.Add(b2)
        self.panel2.SetSizer(self.vbox)

        self.SetSizer(self.sizer) # Set main window sizer

    def OnB1(self, event):
        self.panel2.Show()
        self.panel1.Hide()
        self.sizer.Layout() # Force the main window sizer to recalculate

if __name__ == '__main__':
    app = wx.App(False)
    Example(None, title='')
    app.MainLoop()

rawDescription: wxpython can't switch panel

description: Wxpython can't switch panel


code:
for item in myLines:
   Resultfile.write(item)

rawDescription: delete row in an html doc using python

description: Delete row in an html doc using python


code:
import re
s = 'A Dirty Shame (2004)'
pattern = r'(?P<year>\d{4})'
r = re.search(pattern, s)
n = int(r.group('year'))

rawDescription: How can I extract that number from string?

description: Extract that number from string


rawDescription: Python .split()[] <- brackets?

description: Python .split()[] <- brackets


code:
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from tcgplayer1.items import Tcgplayer1Item

class MySpider(BaseSpider):
    name = "tcg"
    allowed_domains = ["http://www.tcgplayer.com/"]
    start_urls = ["http://store.tcgplayer.com/magic/journey-into-nyx?PageNumber=1"]

    def parse(self, response):
        hxs = Selector(response)
        titles = hxs.xpath("//div[@class='magicCard']")
        for title in titles:
            item = Tcgplayer1Item()
            item["cardname"] = title.xpath(".//li[@class='cardName']/a/text()").extract()[0]

            vendor = title.xpath(".//tr[@class='vendor ']")
            item["price"] = vendor.xpath("normalize-space(.//td[@class='price']/text())").extract()
            item["quantity"] = vendor.xpath("normalize-space(.//td[@class='quantity']/text())").extract()
            yield item

rawDescription: Scraping with scrapy

description: Scraping with scrapy


code:
viewport_rect = QRect(QPoint(0, 0), self.view.viewport().size())
for row in range(0, self.model.rowCount()):
  rect = self.view.visualRect(self.model.index(row, 0))
  is_visible = viewport_rect.intersects(rect)

rawDescription: PySide - Get list of all visible rows in a table


code:
prefix = 'dkss.%s.' % stationName
for direntry in scandir(path='.'):
  if direntry.name.startswith(prefix):
    pass # do whatever work you want with this file here.

rawDescription: Why does it take so long to load filenames from a directory?


code:
import RPi.GPIO as GPIO
import time
import csv
import strftime

GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)

def MOTION(PIR_PIN):
    print ("Motion Detected")

    print ("PIR Module Test (CTRL+C to exit)")

    row = [strfttime("%a, %d %b %Y %H:%M:%S"), 'motion_detected']
    with open('datalog.csv', 'a') as f:
        w = csv.writer(f)
        w.writerow(row)

    time.sleep(2)
    print ("Ready")

try:
    GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
    while 1:
        time.sleep(100)

except KeyboardInterrupt:
    print("Quit")
    GPIO.cleanup()

rawDescription: Sensor data log csv in python

description: Sensor data log csv in python


code:
which = vec[matrix.row] != 0

rows = matrix.row[which]
cols = matrix.col[which]
data = matrix.data[which]

for row, col, val in itertools.izip(rows, cols, data):
    s += vec[row] * val

rawDescription: Optimizing iteration using itertools.izip


code:
from glob import glob
import fileinput

filenames = glob('halo_track*.dat')
inputs = (line.split(None, 1) for line in fileinput.input(filenames))
right_stuff = [col[1] for col in inputs if col[0] == '1.0015']

rawDescription: Reading all the files in a directory in Python


code:
ncols = 2
nrows = 2

inset_hfrac = .3
inset_vfrac = .3

inset_hfrac_offset = .6
inset_vfrac_offset = .6

top_pad = .1
bottom_pad = .1
left_pad = .1
right_pad = .1

hspace = .1
vspace = .1

ax_width = (1 - left_pad - right_pad - (ncols - 1) * hspace) / ncols
ax_height = (1 - top_pad - bottom_pad - (nrows - 1) * vspace) / nrows

fig = figure()

ax_lst = []
for j in range(ncols):
    for k in range(nrows):
        a_bottom = bottom_pad + k * ( ax_height + vspace)
        a_left = left_pad + j * (ax_width + hspace)

        inset_bottom = a_bottom + inset_vfrac_offset * ax_height
        inset_left = a_left + inset_hfrac_offset * ax_width

        ax = fig.add_axes([a_left, a_bottom, ax_width, ax_height])
        ax_in = fig.add_axes([inset_left, inset_bottom, ax_width * inset_hfrac, ax_height *  inset_vfrac])
        ax_lst.append((ax,ax_in))

rawDescription: Matplotlib: Insets in subplots

description: Matplotlib: Insets in subplots


code:
import wnck
screen = wnck.screen_get_default()
# BUG: There needs to be a small delay between the previous line and the next;
# otherwise get_windows returns an empty list.
windows = screen.get_windows()
panel = windows[1] # For example
panel_xid = panel.get_xid()

import gtk
window = gtk.Window()
window.show_all()
window.window.set_transient_for(gtk.gdk.window_foreign_new(panel_xid))

rawDescription: How to REALLY put a window above all others -- Linux PyGTK


code:
def rootAlphaBeta(self, board, rules, ply, player):
    """ Makes a call to the alphaBeta function. Returns the optimal move for a player at given ply. """
    best_move = None
    max_eval = float('-infinity')

    move_list = board.generateMoves(rules, player)
    alpha = float('infinity')
    for move in move_list:
        board.makeMove(move, player)
        alpha = -self.alphaBeta(board, rules, float('-infinity'), alpha, ply - 1, board.getOtherPlayer(player))
        board.unmakeMove(move, player)

        if alpha > max_eval:
            max_eval = alpha
            best_move = move

    return best_move

rawDescription: Alpha-beta pruning python algorithm

description: Alpha-beta pruning python algorithm


code:
import wx
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin

class TextDropTargetListCtrl(wx.TextDropTarget):
    def __init__(self, object, parent):
        wx.TextDropTarget.__init__(self)
        self.object = object
        self.parent = parent
    def OnDropText(self, x, y, data):
        _x,_y = self.parent.listctrl_right.GetPosition()
        _w,_h = self.parent.listctrl_right.GetSize()
        # print _x, _w
        # if self.parent.hovering:
        if _x < x < _x+_w:
            self.object.InsertStringItem(0, data)
    def OnDragOver(self, x, y, d):
        return wx.DragCopy

class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
    def __init__(self, parent, style):
        wx.ListCtrl.__init__(self, parent, -1, style=style)
        ListCtrlAutoWidthMixin.__init__(self)

class MainApp(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="",  size=(500, 800))
        self.SetBackgroundColour('white')
        self.GridBagSizer = wx.GridBagSizer()

        self.listctrl_left = AutoWidthListCtrl(self, style = wx.LC_REPORT|wx.LC_VRULES)
        self.listctrl_left.InsertColumn(0, "Source")
        self.listctrl_left.InsertStringItem(0, "apple")
        self.listctrl_left.InsertStringItem(1, "pear")
        self.listctrl_left.InsertStringItem(2, "watermelon")

        self.listctrl_right = AutoWidthListCtrl(self, style = wx.LC_REPORT)
        self.listctrl_right.InsertColumn(0, "Destination")

        # self.listctrl_right.Bind(wx.EVT_ENTER_WINDOW, self.OnHoverEnter)
        # self.listctrl_right.Bind(wx.EVT_LEAVE_WINDOW, self.OnHoverLeave)
        # self.hovering = False

        self.GridBagSizer.Add(self.listctrl_left, pos=(0, 0),span = (1, 1),
                              flag = wx.EXPAND|wx.ALL, border = 15)
        self.GridBagSizer.Add(self.listctrl_right, pos=(0, 1),span = (1, 1),
                              flag = wx.EXPAND|wx.ALL, border = 15)

        self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.OnDragInit)
        self.DropTarget = TextDropTargetListCtrl(self.listctrl_right, self)

        self.GridBagSizer.AddGrowableCol(0)
        self.GridBagSizer.AddGrowableCol(1)
        self.GridBagSizer.AddGrowableRow(0)
        self.SetSizer(self.GridBagSizer)

    # def OnHoverEnter(self, event):
    #     self.hovering = True
    # def OnHoverLeave(self, event):
    #     self.hovering = False

    def OnDragInit(self, evt):
        text = self.listctrl_left.GetItemText(evt.GetIndex())
        tdo = wx.TextDataObject(text)
        tds = wx.DropSource(self.listctrl_left)
        tds.SetData(tdo)
        tds.DoDragDrop(True)
        # evt.Skip()

if __name__ == "__main__":
    app = wx.App()
    MainFrame = MainApp()
    MainFrame.Show()
    MainFrame.Centre()
    app.MainLoop()

rawDescription: wxpython drag and drop: drop only if the cursor is inside the target listctrl object

description: Wxpython drag and drop: drop only if the cursor is inside the target listctrl object


code: c.InlineBackend.close_figures = False

rawDescription: Manipulate inline figure in IPython notebook


code:
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import numpy as np

def generate_panel(img):
    plt.figure()
    ax = plt.gca()
    fig = plt.gcf()
    implot = ax.imshow(img)
    # When a colour is clicked on the image an event occurs
    cid = fig.canvas.mpl_connect('button_press_event', onclick)
    plt.show(block=True)

def onclick(event):
    if event.xdata is not None and event.ydata is not None:
        circle = plt.Circle((event.xdata,
                             event.ydata), 2, color='r')
        fig = plt.gcf()
        fig.gca().add_artist(circle)
        plt.draw()
        # Change the contents of the plt window here

if __name__ == "__main__":
    plt.ion()
    img = np.ones((600, 800, 3))
    generate_panel(img)

rawDescription: Pyplot: Refreshing an imshow() Window

description: Pyplot: Refreshing an imshow() Window


code:
from Tkinter import Tk
from tkFileDialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

rawDescription: Choosing a file in Python with simple Dialog


code:
import numpy
import numpy.random

f = open('2014-07-17-1M_testdata_1Mx500.csv', 'w', 50000000)

for i in range(1000):
    m = numpy.random.random_integers(0, 1000000, (1000, 500))
    numpy.savetxt(f, m, delimiter=',')

f.close()

rawDescription: Speed up creation of random data

description: Speed up creation of random data


code:
class SomeClass (ISomeInterface):
    def SomeMethod(self, parameter):
        pass

rawDescription: How do you implement an interface in IronPython?

description: Implement an interface in IronPython


code:
from datetime import date
import random

start_date = date.today().replace(day=1, month=1).toordinal()
end_date = date.today().toordinal()
random_day = date.fromordinal(random.randint(start_date, end_date))

rawDescription: Python select random date in current year


code:
from PySide import QtCore, QtGui

class MyLabel(QtGui.QLabel):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.installEventFilter(self)
        self.single_click_timer = QtCore.QTimer()
        self.single_click_timer.setInterval(200)
        self.single_click_timer.timeout.connect(self.single_click)

    def single_click(self):
        self.single_click_timer.stop()
        print('timeout, must be single click')

    def eventFilter(self, object, event):
        if event.type() == QtCore.QEvent.MouseButtonPress:
            self.single_click_timer.start()
            return True
        elif event.type() == QtCore.QEvent.MouseButtonDblClick:
            self.single_click_timer.stop()
            print('double click')
            return True

        return False

app = QtGui.QApplication([])

window = MyLabel('Click me')
window.resize(200, 200)
window.show()

app.exec_()

rawDescription: How to read double click with eventFilter?

description: Read double click with eventFilter


rawDescription: Transposing an irregular matrix without truncating it


code:
class PublicationAdmin(admin.ModelAdmin):
    list_display = ('title',)
    search_fields = ('tags__title',)

rawDescription: Reverse Relation Search Django Admin Interface


code:
import asyncio
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import threading

queue = asyncio.Queue()
loop = asyncio.get_event_loop()

fig = plt.figure()
img = mpimg.imread('1970_0101_1015_47_1.jpg')
plt.imshow(img)

def onclick(event):
    loop.call_soon_threadsafe(queue.put_nowait, (event.x,event.y))
    print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
        event.button, event.x, event.y, event.xdata, event.ydata))
cid = fig.canvas.mpl_connect('button_press_event', onclick)

@asyncio.coroutine
def consume():
    while True:
        value = yield from queue.get()
        print("Consumed", value)

def start_async_stuff():
    print('lets async!')
    loop.create_task(consume())
    loop.run_forever()

threading.Thread(target=start_async_stuff).start()
plt.show()

rawDescription: react to mouse click events in matplotlib using asyncio

description: React to mouse click events in matplotlib using asyncio


code:
s='abc'
n=1
{c:{e for e in[s[i-n:i],c,s[i+1:i+1+n]] if e} for i, c in enumerate(s)}

rawDescription: add current position+1 or -1 dict value to dict python

description: Add current position+1 or -1 dict value to dict python


code:
a = 1
x0 = 1
xopt = fmin(f, x0, xtol=1e-8, args=(a,))

rawDescription: Using scipy to minimize a function that also takes non variational parameters


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

mydata = np.random.random((10,10))

im = plt.imshow(mydata,interpolation='bilinear', aspect='auto',
                origin='lower', extent=[0, 1, 0, 1])
plt.colorbar(im, orientation='vertical')
plt.show()

rawDescription: matplotlib change Axis scale

description: Matplotlib change Axis scale


code:
from string import punctuation
punctuation
strs = "fo@#$%sf*&"
re.sub(r'[{}]'.format(punctuation),'',strs)
strs.translate(None,punctuation)

rawDescription: Regular expression that makes a string not contain punctuated/special characters, such as * $ < , > ? ! % [ ] | \?


rawDescription: Python: parsing and extracting op-codes from asm


code:
first=str(center_nodes[0])[0] #Get the first figure of element 0 of center_nodes
grid_coord=None
if len(str(center_nodes[0]))==1: #Check if center_nodes[0] is in the 0-9 range
    grid_coord=int(first)
    print('Grid coord for center giant comp is: '+str(grid_coord))
elif len(str(center_nodes[0]))==2: #Check if center_nodes[0] is in the 10-99 range
    grid_coord=int(center_nodes[0])+int(first)
    print('Grid coord for center giant comp is: '+str(grid_coord))

rawDescription: Python: variable initialization and for loop


code:
def variableDataFrame(*args):
    """I'm assuming the last argument is the data argument.
    Everything else gets put into an index.
    If you want these as columns instead of rows,
    put a ".T" at the end of the return argument."""

    return pd.DataFrame(args[-1], index=pd.MultiIndex.from_arrays(args[:-1]))

    # Optional return if you want columns instead
    # return pd.DataFrame(args[-1], index=pd.MultiIndex.from_arrays(args[:-1])).T

rawDescription: Python pandas creating data frame with variable number of inputs


rawDescription: list of strings into a list of tuples of ints

description: List of strings into a list of tuples of ints


rawDescription: Pandas DataFrame - delete rows that have same value at a particular column as a previous row


code:
def normalize(arr):
    arr=arr.astype('float32')
    if arr.max() > 1.0:
        arr/=255.0
    return arr

rawDescription: Normalize numpy arrays from various "image" objects


code:
from fabric.api import execute, task
@task
def internaltask():
    execute("deploy", alias=dp)

rawDescription: Fabric get task attributes

description: Fabric get task attributes


code:
import random
import itertools
import collections
c = collections.Counter({'a': 2, 'b': 1})
i = random.randrange(sum(c.values()))
next(itertools.islice(c.elements(), i, None))

rawDescription: How can I get a weighted random pick from Python's Counter class?

description: Get a weighted random pick from Python's Counter class


code:
prev = None
with open('infile.txt','r') as fi:
    with open('outfile.txt','w') as fo:
        for line in fi:
            if prev is not None:
                fo.write(prev if prev != line else "SECTION : MISSING\n")
            prev = line
        fo.write(prev)

rawDescription: Identifying two consecutive identical lines and replace the first one


code:
import pygal

class CustomLine(pygal.Line):

    def __init__(self, *args, **kwargs):
        super(CustomLine, self).__init__(*args, **kwargs)

    def _x_axis(self):
        pass

    def _y_axis(self):
        pass

chart = CustomLine()
chart.add('Series 1', [0, 0.005, 0.002])
chart.render_response()

rawDescription: Render pygal charts without borders

description: Render pygal charts without borders


code:
import sys
if sys.hexversion < 0x3000000:
    input = raw_input

rawDescription: Issue with accepting user inputs in Jython script


code:
libc = ctypes.cdll.LoadLibrary('libc.so.6')
content = 'My new content'
bufcontent = ctypes.create_string_buffer(content)
libc.memcpy(buffer. newcontent, min(len(content) + 1, bufferlen))

rawDescription: Adding data to a C buffer passed to a Python Ctypes callback


code:
#! C:\python34\python
import print # imports print.pyc

#now you can use the pyc as a module.
DoSomething()

rawDescription: Calling python compiled files in Python 3


code: indices = np.argwhere(overlap.any(-1))

rawDescription: NumPy: indices where third dimension is non-zero (image masking)


code:
for row in range(model.rowCount()):
    for col in range(model.columnCount()):
        value = model.index( row, col, QModelIndex() ).data( Qt.DisplayRole ).toString()
        #write v, add separator...
    #finish row...

rawDescription: Pyqt - get CSV from model

description: Pyqt - get CSV from model


code:
log = logging.getLogger(name)
while some_condition:
    try:
        handler = make_handler(filename)
        log.addHandler(handler)
        # do something and log

    finally:
        log.removeHandler(handler)
        handler.close()

rawDescription: Pythonic way to log specific things to a file?


code:
a = ['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
a[0].split(":")[0] # returns NEW

rawDescription: Accessing elements of a python list separated by a special character


code:
for row in doc.cssselect('tr'):
    cells = [ cell.text_content() for cell in row.cssselect('td') ]
    if any(cells):
        sys.stdout.write('\t'.join(cells) + '\n')

rawDescription: Pythonic way to conditionally iterate over items in a list


code:
from subprocess import call
call(["ls", "-l"])

rawDescription: Can I run a shell function from a python script?

description: Run a shell function from a python script


code:
import os

def matlab_installed():
    for path in os.environ["PATH"].split(";"):
        if os.path.isfile(os.path.join(path, "matlab.exe")):
            return True
    return False

rawDescription: python check for matlab installation

description: Python check for matlab installation


code:
from networkx import *
import matplotlib.pyplot as plt
G = Graph()
G.add_node(1)
# Need to specify a layout when calling the draw functions below
# spring_layout is the default layout used within networkx (e.g. by `draw`)
pos = spring_layout(G)
nodes = draw_networkx_nodes(G, pos)
# Set edge color to red
nodes.set_edgecolor('r')
draw_networkx_edges(G, pos)
# Uncomment this if you want your labels
## draw_networkx_labels(G, pos)
plt.show()

rawDescription: How can one modify the outline color of a node In networkx?


code:
def root(n, r=4):
    from numpy import roots
    return roots([1]+[0]*(r-1)+[-n])
print(root(12))

rawDescription: The fourth root of (12) or any other number in Python 3


code:
import csv
from ftplib import FTP
from cStringIO import StringIO

...
ftp = FTP(host, user, passwd)
ftp.login()
output = StringIO()
data = csv.writer(output)
data.writerow(["data"] * 5)
output.seek(0)
ftp.storbinary("STOR data.txt", output)
...

rawDescription: Create a CSV file directly on an FTP server


code:
from multiprocessing import Pool

def get_data(i):
    r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
    a = r1.json()
    pid = a['results'][0]['place_id']
    r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
    b = r2.json()
    phone = b['result']['formatted_phone_number']
    name = b['result']['name']
    website = b['result']['website']
    return ' '.join((phone, name, website))

if __name__ == '__main__':
    terms = input("input places separated by comma").split(",")
    with Pool(5) as p:
        print(p.map(get_data, terms))

rawDescription: How to speed up API requests?

description: Speed up API requests


code:
from my_website import app

# hackish way to apply WSGI's url decoding in Passenger
import urllib2
def application(environ, start_response):
    environ["PATH_INFO"] = urllib2.unquote(environ["PATH_INFO"])
    return app(environ, start_response)

rawDescription: Passenger+flask and URL escaping

description: Passenger+flask and URL escaping


code:
for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

rawDescription: Python variables as keys to dict

description: Python variables as keys to dict


code: file_p = open(file_path, "ab")

rawDescription: updating on a csv file using python

description: Updating on a csv file using python


code:
self.VDBenchSlot1.Bind(wx.EVT_BUTTON, lambda event: self.VDBenchSlot_clicked(event, 1))

def VDBenchSlot_clicked(self, event, position):
    if position == 1:
        text_slot = self.TextSlot1
    elif position == 2:
        text_slot = self.TextSlot2
    elif position == 3:
        text_slot = self.TextSlot3
    elif position == 4:
        text_slot = self.TextSlot4
    global diskchange
    if diskchange[position] == 'No Disk':
        text_slot.AppendText("No Disk is currently in the slot so you cannot run this! \n")
    else:
        # Open the file startDisk#VD.sh that has the setup to start running VDBench
        os.system("echo pcieRocks | sudo -S gnome-terminal --profile=VDbench --working-directory=/home/pciedev3ubuntu/Documents -e './vdbench -f disk%dVDscript.txt -vr' &" %diskchange[position])

rawDescription: Shortening GUI code by passing parameters to definitions


code:
import numpy as np
a = [0, 1, 2, 3, 4, 5]
np.cumsum(a)

rawDescription: Summing a List in Python Based on the Index of a Loop


code:
class MyButton(wx.PyControl):

    def __init__(self, parent, id, bmp, text, **kwargs):
        wx.PyControl.__init__(self,parent, id, **kwargs)

        self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self._onMouseUp)
        self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave)
        self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter)
        self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground)
        self.Bind(wx.EVT_PAINT,self._onPaint)

        self._mouseIn = self._mouseDown = False

    def _onMouseEnter(self, event):
        self._mouseIn = True

    def _onMouseLeave(self, event):
        self._mouseIn = False

    def _onMouseDown(self, event):
        self._mouseDown = True

    def _onMouseUp(self, event):
        self._mouseDown = False
        self.sendButtonEvent()

    def sendButtonEvent(self):
        event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
        event.SetInt(0)
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

    def _onEraseBackground(self,event):
        # reduce flicker
        pass

    def _onPaint(self, event):
        dc = wx.BufferedPaintDC(self)
        dc.SetFont(self.GetFont())
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        # draw whatever you want to draw
        # draw glossy bitmaps e.g. dc.DrawBitmap
        if self._mouseIn:
            pass# on mouserover may be draw different bitmap
        if self._mouseDown:
            pass # draw different image text

rawDescription: How to make custom buttons in wx?

description: Make custom buttons in wx


code:
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines

import random

deltas = [4, 6, 13, 18, 15, 14, 10, 13, 9, 6, 15, 9, 6, 1, 1, 2, 4, 4, 4, 4, 10, 11, 16, 17, 12, 10, 12, 15, 17, 16, 11, 10, 9, 9, 7, 10, 7, 16, 8, 12, 10, 14, 10, 15, 15, 16, 12, 8, 15, 16]
bases = [46, 49, 45, 45, 44, 49, 51, 52, 56, 58, 53, 57, 62, 63, 68, 66, 65, 66, 63, 63, 62, 61, 61, 57, 61, 64, 63, 58, 56, 56, 56, 60, 59, 54, 57, 54, 54, 50, 53, 51, 48, 43, 42, 38, 37, 39, 44, 49, 47, 43]

def rand_pt(bases, deltas):
    return [random.randint(base, base + delta) for base, delta in zip(bases, deltas)]

# randomly assign opening and closing prices
openings = rand_pt(bases, deltas)
closings = rand_pt(bases, deltas)

# First we draw the bars which show the high and low prices
# bottom holds the low price while deltas holds the difference
# between high and low.
width = 0
ax = plt.axes()
rects1 = ax.bar(np.arange(50), deltas, width, color='r', bottom=bases)

# Now draw the ticks indicating the opening and closing price
for opening, closing, bar in zip(openings, closings, rects1):
    x, w = bar.get_x(), 0.2

    args = {
    }

    ax.plot((x - w, x), (opening, opening), **args)
    ax.plot((x, x + w), (closing, closing), **args)

plt.show()

rawDescription: Financial Charts / Graphs in Ruby or Python


code:
test = {"test": 1}
def update(dictionary,key,value):
    dictionary[key] = value

update(test, "test", 2)
test

rawDescription: updating an input dictionary in python

description: Updating an input dictionary in python


rawDescription: What are the differences between swap in C++ and Python?


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

x = np.linspace(-10,10)
y = np.exp(x)

plt.close('all')

fig,ax = plt.subplots(1,1)
ax.plot(x,y,'bo')
ax.set_yscale('log')

#Placed the import/function definitions here to emphasize
#the working lines of code for this particular task.
from matplotlib.ticker import FuncFormatter

def labeller(x, pos):
    """
    x is the tick value, pos is the position. These args are needed by
    FuncFormatter.
    """

    if x < 1:
        return '0.'+'0'*(abs(int(np.log10(x)))-1)+\
                format(x/10**(np.floor(np.log10(x))),'.0f')
    else:
        return format(x,'.0f')

#FuncFormatter class instance defined from the function above
custom_formatter = FuncFormatter(labeller)

ax.yaxis.set_major_formatter(custom_formatter)
plt.show()

rawDescription: On matplotlib logarithmic axes labels

description: On matplotlib logarithmic axes labels


code:
d = {}
d['test'] = "foo"
locals().update(d)
test

rawDescription: How to turn a dictionary into attribute = value

description: Turn a dictionary into attribute = value


code:
from sympy import Symbol
np.diag([Symbol(x) for x in ['a','b','c','d','e']])

rawDescription: python list of value to metric , how to?

description: Python list of value to metric , how to


code:
from boto.cloudsearch2.layer2 import Layer2

layer2 = Layer2()
domain = layer2.lookup('my-domain')
search = domain.get_search_service()
results = search.search(q='matchall', parser='structured', size=0)
return results.hits

rawDescription: Boto CloudSearch Searchable documents count


code:
class foo(object):
    def __init__(self, obs=None):
        if obs is None:  # provide a default if no list was passed in.
            obs = []
        self.data = obs
        self.max = max(obs)
        self.min = min(obs)
        self._data_len = len(obs)

    def __len__(self):
        return self._data_len

rawDescription: Using len() and def __len__(self): to build a class


code:
@ndb.tasklet
def do_something(key):
  x = yield key.get_async()
  x.do_something()

futs = []
for key in key_list:
  futs.append(do_something(key))

ndb.Future.wait_all(futs)

rawDescription: GAE/P: Efficiently fetching large number of entities by key


code:
import os
import pandas as pd
import re

directory = "/Folder/on/Drive/"

docs = os.listdir(directory)
match=[]
for filename in docs:
    if filename.lower().endswith(".pdf"):
        match.extend(re.findall("\D{2}\d{10}", filename))
df = pd.DataFrame(match, columns=["Match"])
df.to_csv(directory + "match.csv", index=False, delimiter=",")

rawDescription: Pandas DataFrame from re.findall list

description: Pandas DataFrame from re.findall list


rawDescription: Python iterate over array of arrays special way


code:
from multiprocessing.pool import ThreadPool

n_threads = 5
pool = ThreadPool(processes=n_threads)

threads = [pool.apply_async(some_function, args=(arg1,)) for arg1 in args]

pool.close()
pool.join()

results = [result.get() for result in threads]

rawDescription: Read a file and do something, multithreading


code: subset = objects[(param1>10) & (param2-param3>5) & (param2-param3<6) & (param4==1)]

rawDescription: Python: get subset of list avoiding list comprehension


code:
for y, line in enumerate(ascii_art.splitlines(), 2):
    w.addstr(y, 2, line)

rawDescription: Python Curses - Printing Ascii Art

description: Python Curses - Printing Ascii Art


code:
import itertools
import functools

old1 = [[1,2],[3,4,5],[6,7,8],[9]]
old2 = [[1,2,3],[4,5,7],[6,8,10]]

unique1 = functools.reduce(lambda a,b: set(a).union(set(b)),old1)
unique2 = functools.reduce(lambda a,b: set(a).union(set(b)),old2)
new = [list(set(a).intersection(set(b))) for a,b in itertools.product(old1,old2) if len(set(a).intersection(set(b))) != 0]
new.extend([x] for x in unique1.symmetric_difference(unique2))

new

rawDescription: Python - Greatest Common Intersection of lists


code:
@app.context_processor
def inject_test():
    return {'test': 'Available to all'}

rawDescription: Flask - return items to base.html

description: Flask - return items to base.html


code:
result_dict = {}
items = str1.split(';')
for item in items:
    key, value = item.strip().split('=')
    result_dict[key] = value

rawDescription: converting variable like string content to real variable in python

description: Converting variable like string content to real variable in python


code:
for a in soup.find_all('a', {"style": "display:inline; position:relative;"}, href=True):
    href = a['href'].strip()
    href = "http://example.com" + href
print(href)

'http://example.com/aems/file/filegetrevision.do?fileEntityId=8120070&cs=LU31NT9us5P9Pvkb1BrtdwaCrEraskiCJcY6E2ucP5s.xyz'

rawDescription: Couldn't extract out the href values form the <a> tags using BS4


code:
from bs4 import BeautifulSoup
data = """

    <title>Test</title>

        First Link
        Second Link
        Third Link

"""
soup = BeautifulSoup(data)
soup.find_all('a')
soup.find('a')

rawDescription: grabbing only the first link in a row

description: Grabbing only the first link in a row


code:
class SetItemRelationship(models.Model):
    container = models.ForeignKey(SetContainer)
    item = models.ForeignKey(SetItem)
    data = models.PositiveSmallIntegerField()

    class Meta(object):
        unique_together = (("container", "item"), )

    def __unicode__(self):
        return "{:s} contains {:s}".format(self.container.label, self.item.text)

rawDescription: How to create a Django Model with relationships allowing items from a set to be used just once within a container for that set

description: Create a Django Model with relationships allowing items from a set to be used just once within a container for that set


code:
def stripNs(el):
  '''Recursively search this element tree, removing namespaces.'''
  if el.tag.startswith("{"):
    el.tag = el.tag.split('}', 1)[1]  # strip namespace
  for k in el.attrib.keys():
    if k.startswith("{"):
      k2 = k.split('}', 1)[1]
      el.attrib[k2] = el.attrib[k]
      del el.attrib[k]
  for child in el:
    stripNs(child)

rawDescription: Suppress namespace in ElementTree

description: Suppress namespace in ElementTree


code:
from scipy.interpolate import spline

xnew = np.linspace(T.min(),T.max(),300)

power_smooth = spline(T,power,xnew)

plt.plot(xnew,power_smooth)
plt.show()

rawDescription: Plot smooth line with PyPlot

description: Plot smooth line with PyPlot


code: draw.text((20,10), "count: %s" % x, fill=1)

rawDescription: Python PIL with variable

description: Python PIL with variable


code:
from Tkinter import *
import tkFileDialog
import csv

class Application(Frame):
    def __init__(self, master = None):
        Frame.__init__(self,master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        top = self.winfo_toplevel()
        self.menuBar = Menu(top)
        top["menu"] = self.menuBar
        self.subMenu = Menu(self.menuBar)
        self.menuBar.add_cascade(label = "File", menu = self.subMenu)
        self.subMenu.add_command( label = "Read Data",command = self.readCSV)

    def readCSV(self):
        self.filename = tkFileDialog.askopenfilename()
        f = open(self.filename,"rb")
        read = csv.reader(f, delimiter = ",")
        buttons = read.next()
        print
        for btn in buttons:
            new_btn = Button(self, text=btn, command=self.btnClick)
            new_btn.pack()

    def btnClick(self):
        pass

app = Application()
app.master.title("test")
app.mainloop()

rawDescription: Tkinter Gui to read in csv file and generate buttons based on the entries in the first row


rawDescription: Django filtering with query with many objects


code:
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
               data={'track': keyword}, auth=(USER,PW),
               config={'keep_alive':False})

rawDescription: Change POST request parameters when using Twitter's Streaming API


code:
def ordinal(n):
    if n == 1:
        return "first"
    elif n == 2:
        return "second"
    elif n == 3:
        return "third"
    else:
        return str(n)+"th"

rawDescription: how to add number suffixes to the words in my array

description: Add number suffixes to the words in my array


code:
import re
out_info = "value is approximately 34p55"
re.sub(r'(\d+)p(\d+)', r'\1.\2', out_info)

rawDescription: Python - how to replace 'p' in a number(4p5) with '.' (4p5->4.5)?


code:
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE

LogEntry.objects.log_action(
            user_id=request.user.id,
            content_type_id=ContentType.objects.get_for_model(model_object).pk,
            object_id=object.id,
            object_repr=unicode(object.title),
            action_flag=ADDITION if create else CHANGE)

rawDescription: Adding a Log entry for an action by a user in a Django App


code:
sdk_object = myclass_instance.sdk_object
sdl_object.attribute_name = 10

rawDescription: python accessing objects attributes inside of another object

description: Python accessing objects attributes inside of another object


code:
class MyTestClass(unittest.TestCase):
    def setUp(self):
        self.my_obj = MyClass()
        self.my_obj_mock = flexmock(self.my_obj)

    def my_test_case(self):
        self.my_obj_mock.should_receive('other_method').and_return(1).and_return(2).and_return(3)
        self.my_obj.method_to_test()

rawDescription: Python - Mocking an object's attribute with multiple values?


code:
MyList = [{1: 'one'}, 'blarg', 964]
sorted(MyList, key=lambda x: len(str(x)), reverse=True)

rawDescription: How do I reverse the effects of str() Method in Python?

description: Reverse the effects of str() Method in Python


code:
def show_time(hour, minutes):
    if hour >= 12:
        suffix = "pm"
        if hour != 12:
            hour -= 12
    else:
        suffix = "am"
        if hour == 0:
            hour = 12
    return "{0}:{1:02}{2}".format(hour, minutes, suffix)

rawDescription: Developing a function to show time without imports


code:
from subprocess import call
call(["path/to/openmpi/mpirun", "-machinefile machine.file -np 256 /path/to/excecutable </dev/null &> output.out &"])

rawDescription: Python Subprocess with Complex Command

description: Python Subprocess with Complex Command


code:
plt.annotate('', xy = (0.6, 0.33),  xycoords = 'axes fraction', \
    xytext = (0.8, 0.33), textcoords = 'axes fraction', fontsize = 7, \
    color = '#303030', arrowprops=dict(edgecolor='black', arrowstyle = '<->', shrinkA = 0, shrinkB = 0))

rawDescription: How to get arrow heads tip to start/end at specified coordinates in Python?

description: Get arrow heads tip to start/end at specified coordinates in Python


code:
c_users.find_one()
thing2 = {'name': 'fruit', 'color': 'darkgreen', 'types': 'mango'}
c_users.update({'name': thing2['name']}, {'$addToSet': {'types': thing2.pop('types')}, '$set': thing2})
c_users.find_one()

rawDescription: addToSet and set in same update using PyMongo and MongoDB

description: AddToSet and set in same update using PyMongo and MongoDB


code: foobar._vel = -1

rawDescription: Way to encapsulate instance fields in Python


code: start = len(listData) - listData[::-1].index(datum)

rawDescription: index() of last occurrence in list in python

description: Index() of last occurrence in list in python


code:
import json
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')

rawDescription: What's the best data structure for output that's processed by Python?


code:
import matplotlib.pyplot as plt

fig, host = plt.subplots()
fig.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

# move the spine of the second axes outwards
par2.spines["right"].set_position(("axes", 1.2))

p1, = host.plot([0, 1, 2], [0, 1, 2], 'r-', label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], 'g-', label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], 'b-', label="Velocity")

host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

lines = [p1, p2, p3]
host.legend(lines, [l.get_label() for l in lines])

for ax in [par1, par2]:
    ax.set_frame_on(True)
    ax.patch.set_visible(False)

    plt.setp(ax.spines.values(), visible=False)
    ax.spines["right"].set_visible(True)

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())

par1.spines["right"].set_edgecolor(p2.get_color())
par2.spines["right"].set_edgecolor(p3.get_color())

host.tick_params(axis='y', colors=p1.get_color())
par1.tick_params(axis='y', colors=p2.get_color())
par2.tick_params(axis='y', colors=p3.get_color())

rawDescription: Matplotlib: Colour multiple twinx() axes


code:
import pygame
from PIL import Image
import ImageTk
import Tkinter

# load image in pygame
pygame.init()
surf = pygame.image.load('bridge.png')

# export as string / import to PIL
image_str = pygame.image.tostring(surf, 'RGB')         # use 'RGB' to export
w, h      = surf.get_rect()[2:]
image     = Image.fromstring('RGB', (w, h), image_str) # use 'RGB' to import

# create Tk window/widgets
root         = Tkinter.Tk()
tkimage      = ImageTk.PhotoImage(image) # use ImageTk.PhotoImage class instead
canvas       = Tkinter.Canvas(root)

canvas.create_image(0, 0, image=tkimage)
canvas.pack()
root.mainloop()

rawDescription: Load image in tkinter from pygame surface in python 3


code:
if Counter == 1:
        ArrayDisplay1 = (Counter,)
        self.labelVariableArray3.set(ArrayDisplay1)
else:
        ArrayDisplay1 +=(Counter,)
        self.labelVariableArray3.set(''.join(str(i)+',' for i in ArrayDisplay1)[:-1])

rawDescription: Removing curly brackets from a tuple in python


code:
def cycle(s, n):
    return s[-n:] + s[:-n]

rawDescription: shifting numbers in python code

description: Shifting numbers in python code


code:
def f(x): x.append('u')
mylist = []
f(mylist)
mylist

rawDescription: Pass by reference in python: Pass list and add characters?


rawDescription: Set of dict values

description: Set of dict values


code:
from threading import Timer

def delayed(seconds):
    def decorator(f):
        def wrapper(*args, **kargs):
            t = Timer(seconds, f, args, kargs)
            t.start()
        return wrapper
    return decorator

@delayed(1)
def foo():

    print('foo')

foo()
print('dudee')

rawDescription: python decorator that call a function with delay

description: Python decorator that call a function with delay


code:
my_string= raw_input("Enter a string: ")
result={}
result_list = my_string.split("when compared to")
if(len(result_list)==2):
    result['dignostic']=result_list[0]
    result['comparison']=result_list[1]

else:
    result['dignostic']=result_list[0]
    result['comparison']='no comparison made'
result

rawDescription: split a string by key word and return a dictionary

description: Split a string by key word and return a dictionary


rawDescription: How can I pad and/or truncate a vector to a specified length using numpy?

description: Pad and/or truncate a vector to a specified length using numpy


code:
result = []
for i in range(len(text)):
    temp = []
    for t in text[i]:
        word_modified = t
        #making some operations with each element in the nested list.
        #using if-statements here
        temp.append(word_modified)
    result.append(temp)
result

rawDescription: operations with nested lists in python

description: Operations with nested lists in python


code:
class Connection(object):
    def __init__(self, sock):
        self.socket = sock

    def fileno(self):
        return self.socket.fileno()

rawDescription: store variable to socket in python

description: Store variable to socket in python


code:
from sklearn.utils.testing import all_estimators

estimators = all_estimators()

for name, class_ in estimators:
    if hasattr(class_, 'predict_proba'):
        print(name)

rawDescription: How to list all scikit-learn classifiers that support predict_proba()

description: List all scikit-learn classifiers that support predict_proba()


code:
type(u'hello world')
type('hello world')

rawDescription: Invalid JSON objects from Twitter API in Python


rawDescription: Python Flask set cookie for both example.com and www.example.com


code:
# f is a file object
# n1 is how many lines to read
lines = [f.readline() for i in range(n1)]

rawDescription: Python how to grab certain number of lines after match


code:
class Myclass:
    def do_x(self):
        pass

class My_child(Myclass):
    def do_x(self):
        print("I am the chile class")

class My_2nd_child(Myclass):
    def do_x(self):
        print("I am the 2nd child")

rawDescription: How to create multiple class with same function

description: Create multiple class with same function


code: B = globals().__setitem__('A', A + 1) or C

rawDescription: Assignment within expression in Python

description: Assignment within expression in Python


rawDescription: Panda's DataFrame double transpose changes numeric types to object


code:
def check_fermat(a, b, c, n):
    if n > 2 and (a**n + b**n == c**n):
        print("Holy smokes, Fermat was wrong!")
    else:
        print("No, that doesn’t work.")

def check_numbers():
    a = int(input("Choose a number for a: "))
    b = int(input("Choose a number for b: "))
    c = int(input("Choose a number for c: "))
    n = int(input("Choose a number for n: "))
    return check_fermat(a, b, c, n)

check_numbers()

rawDescription: How can I test cases of Fermat's Last Theorem in Python

description: Test cases of Fermat's Last Theorem in Python


code:
from time import sleep

do_task()
sleep(60)
do_task()

rawDescription: How to run a task in Python after 60 second but only one time

description: Run a task in Python after 60 second but only one time


code:
class Notebook(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600, 600))
        menubar = wx.MenuBar()
        file = wx.Menu()
        file.Append(101, 'Quit', '' )
        menubar.Append(file, "&File")
        self.SetMenuBar(menubar)
        wx.EVT_MENU(self, 101, self.OnQuit)
        nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
        self.sheet1 = MySheet(nb)
        self.sheet2 = MySheet(nb)
        self.sheet3 = MySheet(nb)
        nb.AddPage(self.sheet1, "Sheet1")
        nb.AddPage(self.sheet2, "Sheet2")
        nb.AddPage(self.sheet3, "Sheet3")
        self.sheet1.SetFocus()
        self.StatusBar()
        # new code begins here:
        # add your text ctrl:
        self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
        # create a new sizer for both controls:
        sizer = wx.BoxSizer(wx.VERTICAL)
        # add notebook first, with size factor 2:
        sizer.Add(nb, 2)
        # then text, size factor 1, maximized
        sizer.Add(self.text, 1, wx.EXPAND)
        # assign the sizer to Frame:
        self.SetSizerAndFit(sizer)

rawDescription: wxPython: displaying multiple widgets in same frame

description: WxPython: displaying multiple widgets in same frame


code: pd.get_dummies(df, prefix=['A', 'D'], columns=['A', 'D'])

rawDescription: how to create dummies for certain columns by pandas get_dummies() method?

description: Create dummies for certain columns by pandas get_dummies() method


code:
keyword = 'whatever'
with open ('filename.txt', 'rt') as myfile:
    for filename in (line.strip() for line in myfile):
        with open(filename, 'rt') as file:
            for line in file:
                if keyword in line:
                    print(line, end='')

rawDescription: Windows 7 Python 3 find keyword in file show filename and path


code:
artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
    artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')

rawDescription: replace spaces with dash and remove prefix from string

description: Replace spaces with dash and remove prefix from string


code: [CountObject(amount=a, type=i) for i, a in enumerate(counts)]

rawDescription: How to use the list index in a for loop?

description: Use the list index in a for loop


code:
import multiprocessing
from Queue import Empty

class _Popen(multiprocessing.forking.Popen):
    def __init__(self, *args, **kw):
        if hasattr(sys, 'frozen'):
            os.putenv('_MEIPASS2', sys._MEIPASS)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(sys, 'frozen'):
                os.unsetenv('_MEIPASS2')

class Process(multiprocessing.Process):
    _Popen = _Popen

def _start():
    while True:
        try:
            command = queue.get_nowait()
        # ... and some more code to actually interpret commands
        except Empty:
            time.sleep(0.015)

def start():
    process = Process(target=_start, args=args)
    process.start()
    return process

rawDescription: PyInstaller-built Windows EXE fails with multiprocessing


rawDescription: Fix first element, shuffle the rest of a list/array


code:
df.pivot_table(values='result', cols='test', rows='date')
df.pivot_table(values='result', cols='test', rows='date') * 100

rawDescription: How to efficiently re-arrange pass/fail as a pass percentage by day in Pandas and NumPy?

description: Efficiently re-arrange pass/fail as a pass percentage by day in Pandas and NumPy


code:
with open('out-file.txt', 'w') as f:
    subprocess.call(['program'], stdout=f)

rawDescription: How do I redirect stdout to a file when using subprocess.call in python?

description: Redirect stdout to a file when using subprocess.call in python


code: [a + b for a in Sites for b in PurchaseTypes]

rawDescription: Multiple list of strings together

description: Multiple list of strings together


code: [",".join(line.split(" ", 1)) for line in lines]

rawDescription: Replacing first whitespace in every line with a comma


code:
from shapely.geometry import *

def getExtrapoledLine(p1,p2):
    'Creates a line extrapoled in p1->p2 direction'
    EXTRAPOL_RATIO = 10
    a = p1
    b = (p1[0]+EXTRAPOL_RATIO*(p2[0]-p1[0]), p1[1]+EXTRAPOL_RATIO*(p2[1]-p1[1]) )
    return LineString([a,b])

line=LineString([(3,0),(3,5),(7,9.5)])
box=Polygon([(0,0),(0,10),(10,10),(10,0)])

box_ext = LinearRing(box.exterior.coords) #we only care about the boundary intersection
l_coords = list(line.coords)
long_line = getExtrapoledLine(*l_coords[-2:]) #we use the last two points

if box_ext.intersects(long_line):
    intersection_points = box_ext.intersection(long_line)
    new_point_coords = list(intersection_points.coords)[0] #
else:
    raise Exception("Something went really wrong")

l_coords.append(new_point_coords)
new_extended_line = LineString(l_coords)

# To see the problem:
import pylab
x, y = box.exterior.xy
pylab.plot(x,y)
l_coords = list(line.coords)
x = [p[0] for p in l_coords]
y = [p[1] for p in l_coords]
pylab.plot(x,y)
longl_coords = list(long_line.coords)
x = [p[0] for p in longl_coords]
y = [p[1] for p in longl_coords]
pylab.plot(x,y)
pylab.plot(new_point_coords[0], new_point_coords[1], 'o')
pylab.show()

# To see the solution:
x, y = box.exterior.xy
pylab.plot(x,y)
l_coords = list(new_extended_line.coords)
x = [p[0] for p in l_coords]
y = [p[1] for p in l_coords]
pylab.plot(x,y)
pylab.show()

rawDescription: Shapely Extending Line Feature

description: Shapely Extending Line Feature


code:
def generate_values(f):
    buf = "" # a buffer of data read from the file
    pos = 0  # the position of our buffer within the file

    while True: # loop until we return at the end of the file
        new_data = f.read(4096) # read up to 4k bytes at a time

        if not new_data: # quit if we got nothing
            if buf:
                yield pos, buf.split(",") # handle any data after last newline
            return

        buf += new_data
        line_start = 0 # index into buf

        try:
            while True: # loop until an exception is raised at end of buf
                line_end = buf.index("\n", line_start) # find end of line
                line = buf[line_start:line_end] # excludes the newline

                if line: # skips blank lines
                    yield pos+line_start, line.split(",") # yield pos,data tuple

                line_start = line_end+1
        except ValueError: # raised by `index()`
            pass

        pos += line_end + 1
        buf = buf[line_end + 1:] # keep left over data from end of the buffer

rawDescription: How can I know where the file pointer is so I can identify a starting position in a file

description: Know where the file pointer is so I can identify a starting position in a file


code: begin = re.search("begin .+?;;;", line)

rawDescription: Python re.search first accordance in the result


code:
import sqlite3
conn = sqlite3.connect("test.sqlite")

data = ("a", None)
conn.execute('INSERT INTO "foo" VALUES(' + ','.join("?" * len(data)) + ')', data)

list(conn.execute("SELECT * FROM foo"))      # -> [("a", None)]

rawDescription: Python Write a number of columns to sqlite


code:
result = {}
for key1, middle_dict in my_dict.items():
    for key2, inner_dict in middle_dict.items():
        for key3, value in inner_dict.items():
            result.setdefault(key3, {}).setdefault(key1, {})[key2] = value

rawDescription: reconstruct a python dictionary

description: Reconstruct a python dictionary


code:
#Zip the list
sort_year = list(zip(values, labels))
#Sortig the list
sort_year.sort()
#pitfall: the list will be in reversed order
values, labels = zip(*sort_year)

rawDescription: Sorting corresponding lists

description: Sorting corresponding lists


code:
_illegal_unichrs = [(0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F),
                        (0x7F, 0x84), (0x86, 0x9F),
                        (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)]
if sys.maxunicode >= 0x10000:  # not narrow build
        _illegal_unichrs.extend([(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF),
                                 (0x3FFFE, 0x3FFFF), (0x4FFFE, 0x4FFFF),
                                 (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
                                 (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF),
                                 (0x9FFFE, 0x9FFFF), (0xAFFFE, 0xAFFFF),
                                 (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
                                 (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF),
                                 (0xFFFFE, 0xFFFFF), (0x10FFFE, 0x10FFFF)])

_illegal_ranges = ["%s-%s" % (unichr(low), unichr(high))
                   for (low, high) in _illegal_unichrs]
_illegal_xml_chars_RE = re.compile(u'[%s]' % u''.join(_illegal_ranges))

rawDescription: Fast way to filter illegal xml unicode chars in python?


code:
from matplotlib import pyplot, lines
import numpy

x = numpy.linspace(0,10,100)
y = numpy.sin(x)*(1+x)

fig = pyplot.figure()
ax = pyplot.subplot(111)
ax.plot(x,y,label='a')

# new clear axis overlay with 0-1 limits
ax2 = pyplot.axes([0,0,1,1], axisbg=(1,1,1,0))

x,y = numpy.array([[0.05, 0.1, 0.9], [0.05, 0.5, 0.9]])
line = lines.Line2D(x, y, lw=5., color='r', alpha=0.4)
ax2.add_line(line)

pyplot.show()

rawDescription: How to draw a line outside of an axis in matplotlib (in figure coordinates)?

description: Draw a line outside of an axis in matplotlib (in figure coordinates)


code:
import os
find_str = "ERROR"
error = False
# Open file with 'b' to specify binary mode
with open(file_directory, 'rb') as file:
    file.seek(-1024 * 1024, os.SEEK_END)  # Note minus sign
    if find_str in file.read():
        error = True

rawDescription: How to read the last MB of a very large text file

description: Read the last MB of a very large text file


code:
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.utils import simplejson

def upload_view(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            result = {'success': True}
            return HttpResponse(simplejson.dumps(result), mimetype='application/json')
        else:
            return HttpResponseBadRequest()
    else:
       return HttpResponseNotAllowed(['POST'])

rawDescription: How to save an image using django imageField?

description: Save an image using django imageField


rawDescription: CSRF verification failing for post or preview using {% render_comment_form for ... %}


code:
from PySide import QtGui

app = QtGui.QApplication([])

table = QtGui.QTableWidget(4, 2)
table.show()

for i in range(0, 4):
    item = QtGui.QTableWidgetItem('Text')
    item.setBackground(QtGui.QColor(i*50, i*30, 200-i*40))
    table.setVerticalHeaderItem(i, item)

# print(QtGui.QStyleFactory.keys())
table.verticalHeader().setStyle(QtGui.QStyleFactory.create('CleanLooks'))

app.exec_()

rawDescription: Is it possible to change the colour of a QTableWidget row label?


code:
regex = re.compile(r'(?<=\[\]\(#STARTTABLE\)\n).*?(?=\n\[\]\(#ENDTABLE\)|$)', re.S)
sidebar = regex.sub(md, sidebar)

rawDescription: Python's Re.Sub Changes Nothing When Regex Matches


code: title = text.encode('utf8')

rawDescription: Utf8 encoding with MySQLdb on non-utf symbols


code:
def rgb_to_hex(rgb):
    strValue = '%02x%02x%02x' % rgb
    iValue = int(strValue, 16)
    return iValue

xl.ActiveSheet.Cells(row, column).interior.color = rgb_to_hex((255,255,0))

rawDescription: Setting a cell's fill RGB color with pywin32 in excel?


code:
import numpy as np

def order_bydict(ids,values,master_order_ids):
    """ Using a dict to order ``master_order_ids`` """

    dd = dict([(k,v) for k,v in zip(ids, values)])  # create the dict
    ordered_values = [dd.get(m, 0) for m in master_order_ids]  # get() return 0 if key not found

    return np.asarray(ordered_values)  # return a numpy array instead of a list

rawDescription: Re-order numpy array based on where its associated ids are positioned in the `master_order` array


code:
with open('in.csv') as fin, open('out.csv', 'wb') as fout:
   csvin = csv.reader(fin)
   csvout = csv.writer(fout)
   try:
       header = next(csvin)
       csvout.writerow(header)
   except StopIeration as e:
       pass # empty file - either handle, or we'll just continue and drop out of loop

   for row in csvin:
       csvout.writerow(row) # do some real work here...

rawDescription: Python csv: preserve headers when writing to file


code:
groups = reversed(range(5000000))
ages = [random.randrange(0, 120) for x in groups]
names = ['foobar-%d' % random.randrange(0, 5000) for x in groups]

columns = dict(names=names,ages=ages,groups=groups)

def sort_on(col):
    idxs = range(len(columns[col]))
    idxs.sort(key=lambda x:columns[col][x])
    return idxs

rawDescription: python argsort indices based on multiple arrays

description: Python argsort indices based on multiple arrays


code:
book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
sheet = book.add_sheet('namelist', cell_overwrite_ok = True)

for i, each_file in enumerate(line_in_list):
    page = open(each_file)
    soup = BeautifulSoup(page.read())

    all_texts = soup.find_all("td")

    for j, a_t in enumerate(all_texts):
        a = a_t.renderContents()
        sheet.write(i, j, a)

book.save("C:\\details.xls")

rawDescription: Pick up texts from a batch of files, and write them into an Excel file


code:
import cmd

class MyCmd(cmd.Cmd):
    def do_command(self, line):
        'do_command: [parametre[1,2]=xxx]'

    def complete_command(self, text, line, begidx, endidx):
        return [i
                for i in ('parametre1=', 'parametre2=')
                if i.startswith(text)]

    def do_EOF(self, line):
        'exit the program. Use  Ctrl-D (Ctrl-Z in Windows) as a shortcut'
        return True

if __name__ == "__main__":
    myCmd = MyCmd()
    myCmd.cmdloop("Welcome! What is your command?")

rawDescription: Python CMD autocomplete

description: Python CMD autocomplete


code:
# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

rawDescription: How to create a timer using tkinter?

description: Create a timer using tkinter


code:
if __name__ == "__main__":
    the_function_I_think_of_as_main()

rawDescription: After breaking a python program into functions, how do I make one the main function?


code: set(column_1_vals) & set(column_2_vals) & set(column_3_vals)

rawDescription: Python - Identify Common Values

description: Python - Identify Common Values