code:
class UserModelAdmin(ModelAdmin):
    def get_urls(self):
        urls = super(UserModelAdmin, self).get_urls()
        info = self.model._meta.app_label, self.model._meta.module_name
        select_list_url = patterns('',
            url(r'^selectlist/$', self.selectlist_view,
                name='%s_%s_select' % info)
        )
        return select_list_url + urls

    def selectlist_view(self, request, extra_context=None):
        temp_list_display_links = self.list_display_links
        self.list_display_links = (None, )
        response = self.changelist_view(request, extra_context)
        self.list_display_links = temp_list_display_links
        return response

rawDescription: Django admin: What is the best way to add a custom list view?


code:
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

import uuid

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Company.uuid'
        db.add_column(u'facebookapp_company', 'uuid',
                      self.gf('django.db.models.fields.CharField')(max_length=32, null=True),
                      keep_default=False)

        # Adding field 'GiftBase.uuid'
        db.add_column(u'facebookapp_giftbase', 'uuid',
                      self.gf('django.db.models.fields.CharField')(max_length=32, null=True),
                      keep_default=False)

        # Adding field 'Purchase.uuid'
        db.add_column(u'facebookapp_purchase', 'uuid',
                      self.gf('django.db.models.fields.CharField')(max_length=32, null=True),
                      keep_default=False)

        for model in (orm.Company, orm.GiftBase, orm.Purchase):
            for obj in model.objects.all():
                obj.uuid = uuid.uuid4().hex
                obj.save()

        db.alter_column(u'facebookapp_company', 'uuid',
                self.gf('django.db.models.fields.CharField')(max_length=32, unique=True, null=False))
        db.create_unique(u'facebookapp_company', ['uuid'])

        db.alter_column(u'facebookapp_giftbase', 'uuid',
                self.gf('django.db.models.fields.CharField')(max_length=32, unique=True, null=False))
        db.create_unique(u'facebookapp_giftbase', ['uuid'])

        db.alter_column(u'facebookapp_purchase', 'uuid',
                self.gf('django.db.models.fields.CharField')(max_length=32, unique=True, null=False))
        db.create_unique(u'facebookapp_purchase', ['uuid'])

    def backwards(self, orm):
        # Deleting field 'Company.uuid'
        db.delete_column(u'facebookapp_company', 'uuid')

        # Deleting field 'GiftBase.uuid'
        db.delete_column(u'facebookapp_giftbase', 'uuid')

        # Deleting field 'Purchase.uuid'
        db.delete_column(u'facebookapp_purchase', 'uuid')

rawDescription: Django field with lambda as default value and unique = True


code:
def path_to_tree(p):
    elems = p.split(':')
    head = None
    for elem in reversed(elems):
        head = {'title': elem, 'children': [] if head is None else [head]}
    return head

rawDescription: Creating nested python dictionary for Dynatree


code:
def login(request):
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        # Assuming the fields in your `User` model are labeled the same
        user = authenticate(email=email, password=password)
    else:
        context = RequestContext(request, {})
        return render(request, 'login.html', context)

rawDescription: Check user submitted password in database


code:
# Reverse direction of every second row
unsnaked_array       = np.array(inp_array)
unsnaked_array[1::2] = inp_array[1::2, ::-1]

# Change to one long array
unsnaked_array = unsnaked_array.ravel()
unsnaked_array &= 0x7    # Extra safety :)

# Sum every pair of elements (with first element rolled) and add required bit
result_array = (unsnaked_array[::2]<<3) + unsnaked_array[1::2] + (1<<6)

rawDescription: Creating new numpy array from existing array efficiently


code:
s = paramiko.SSHClient()
s.load_system_host_keys()
s.connect(hostname, port, username, password)
cmd = "echo 'while true; do date >> ~/file.txt; sleep 1; done &' >run.sh"
(stdin, stdout, stderr) = s.exec_command(cmd)
cmd = "bash run.sh </dev/null >>/dev/null 2>&1"
(stdin, stdout, stderr) = s.exec_command(cmd)
s.close()

rawDescription: Run Infinite Bash loop in background with Paramiko


code:
keyword2func = {
    "word1": function_word1,
    "word2": function_word2,
}

word = input("")
keyword2func[word]()

rawDescription: Reproduce a C function pointer array in Python


code:
import os
import re
import urllib
import urllib2

from BeautifulSoup import BeautifulSoup

websites = [
    'http://cdn.superantispyware.com/SUPERAntiSpyware.exe'
    'http://support.kaspersky.com/downloads/utils/tdsskiller.exe'
    'http://www.bleepingcomputer.com/download/malwarebytes-anti-malware/dl/7/?1'
    'http://www.simplysup.com/tremover/download.html'
]

download_links = []

for url in websites:
    connection = urllib2.urlopen(url)
    soup = BeautifulSoup(connection)
    connection.close()

    for link in soup.findAll('a', {href: re.compile(r'\.exe$')}):
        download_links.append(link['href'])

for url in download_links:
    urllib.urlretrieve(url, r'C:\_VirusFixes', os.path.basename(url))

rawDescription: Downloading files from multiple websites.


rawDescription: pandas groupby without turning grouped by column into index

description: Pandas groupby without turning grouped by column into index


code:
def merge(source, destination):
    """
    run me with nosetests --with-doctest file.py

    >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
    >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
    >>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
    True
    """
    for key, value in source.items():
        if isinstance(value, dict):
            # get node or create one
            node = destination.setdefault(key, {})
            merge(value, node)
        else:
            destination[key] = value

    return destination

rawDescription: Python deep merge dictionary data

description: Python deep merge dictionary data


code:
#suppose category model looks like this
class Category(models.Model):
    category = models.CharField(max_length=255)

#main model
class MainModel(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, null=True, default=None)

    def save(self):
        for c in Category.objects.all():
            if c.category in self.name:
               self.category = c
               break
        super().save(*args, **kwargs)

rawDescription: Automatically write to field in django model based on lookup in another model


code:
import time, twitter

api = twitter.Api(consumer_key='CONSUMER_KEY_HERE', consumer_secret='CONSUMER_SECRET_HERE', access_token_key='ACCESS_TOKEN_HERE', access_token_secret='ACCESS_TOKEN_SECRET_HERE')

i = 0
while True:
    api.UpdateProfile(name=str(i))
    i += 1
    time.sleep(60 * 60 * 24) # 1 day

rawDescription: How can I change a user's Twitter name with a bot?

description: Change a user's Twitter name with a bot


rawDescription: Unpacking List of Tuples of List(s)

description: Unpacking List of Tuples of List(s)


code:
#non_mem_macs is my dictionary
for idx in non_mem_macs:
    non_mem_macs_len += len(hexlify(idx))
    non_mem_macs_len += len(hexlify(non_mem_macs[idx]))

rawDescription: get size of populated dictionary

description: Get size of populated dictionary


code:
file_names = []  # Renamed
MJD = []
wavelength = []
flux = []

f = open("original.txt","r")
for line in f:
    file_names.append(str(line.split()[0]))
    MJD.append(float(line.split()[1]))
f.close()

# FOR MULTIPLE OUTPUT FILES

for x in range(len(file_names)):
    input_file = open('%s' % file_names[x])
    date = MJD[x]
    output_file = open(file_names[x].replace('.txt', '') + "_t.txt", 'w')
    for line in input_file:
         wavelength = float(line.split()[0])
         flux = float(line.split()[1])
         output_file.write("%0.3f  %0.3f   %0.3f\n" % (wavelength,flux,date))
    input_file.close()
    output_file.close()

# FOR A SINGLE OUTPUT FILE

main_output = open('outputs.txt', 'w')

for x in range(len(file_names)):
    input_file = open('%s' % file_names[x])
    date = MJD[x]
    for line in input_file:
        wavelength = float(line.split()[0])
        flux = float(line.split()[1])
        main_output.write("%0.3f  %0.3f   %0.3f\n" % (wavelength,flux,date))
    input_file.close()
main_output.close()

rawDescription: Python writing data to files

description: Python writing data to files


code:
import os
paths
[next(part for part in path.split(os.path.sep) if part) for path in paths]

rawDescription: First element of a path in python

description: First element of a path in python


code:
class MyDecorator(object):
    def __call__(self, func):
      def wrapper(that, *args, **kwargs):
        ## you can access the "self" of func here through the "that" parameter
        ## and hence do whatever you want
        return func(that, *args, **kwargs)
      return wrapper

rawDescription: Python: How do I access an decorated class's instance from inside a class decorator?


code:
def circular_orbit(center, radius, speed, t):
    theta = math.fmod(t * speed, math.PI * 2)
    c = math.cos(theta)
    s = math.sin(theta)
    return center[0] + radius * c, center[1] + radius * s

rawDescription: Making smooth orbits in pygame

description: Making smooth orbits in pygame


code:
import csv
import io

fruit_mess = [['watermelon,0,1.0\n'], ['apple,0,1.0\n'], ['"pineapple",0,1.0\n'], ['"strawberry, banana",0,1.0\n'], ['peach plum pear,0,1.0\n'], ['"orange, grape",0,1.0\n']]

# flatten the list of lists into a string:
data='\n'.join(item[0].strip() for item in fruit_mess)
reader=csv.reader(io.BytesIO(data))
neat_fruit=[[fruit,int(num1),float(num2)] for fruit,num1,num2 in reader]

print(neat_fruit)
# [['watermelon', 0, 1.0], ['apple', 0, 1.0], ['pineapple', 0, 1.0], ['strawberry, banana', 0, 1.0], ['peach plum pear', 0, 1.0], ['orange, grape', 0, 1.0]]

rawDescription: cleanup nested list

description: Cleanup nested list


code:
autoclickers=0 # start autoclickers at 0

def purchaseAutoClickerCommand():
    global click
    global autoclickers # declare global
    if click < 7:
        print("Not enough clicks!")
        blankLine()
    else:
        click -= 7 # pay for an autoclicker
        print("Auto clicker purchased!")
        autoclickers += 1 # receive an autoclicker

def autoclick():
    global master
    global click
    global autoclickers
    click += autoclickers # get clicks from autoclickers
    master.after(1000, autoclick) # do this again 1 second later

autoclick() # start benefiting from all existing autoclickers

rawDescription: Python Clicker Game

description: Python Clicker Game


code:
for i in range(0,3):
    driver.find_element_by_link_text('Download Search Results').click()
    for j in range(0,101):
        f_exists = os.path.isfile('/Users/jeff/downloaded.csv')
        if not f_exists:
            print(j, 'file DOES NOT exist')
            time.sleep(.05)
        else:
            print(i, 'file exists')
            return

rawDescription: download a file, validate the download, attempt again if not downloaded

description: Download a file, validate the download, attempt again if not downloaded


code:
g = re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", user_input)
if g:
    team1 = g.group(1)
    team1_score = g.group(2)
    team2_score = g.group(3)
    team2 = g.group(4)

rawDescription: extracting football score from user input

description: Extracting football score from user input


code:
while num > 1:
    factorial = factorial * num
    num = num - 1

rawDescription: Write factorial with while loop python

description: Write factorial with while loop python


code:
def func(mylist):
    return [elem for elem in mylist if elem > 0]

onlyPositives = [func(e) for e in myintlist]

rawDescription: Python: how to get only positive numbers of nested int list with resonable performance


code:
user_count_dict = {str(int(year))+'/'+str(int(month)): total for total, month, year in users_count}
# get(x) returns None if a key not in the dict
data = [user_count_dict.get(x) for x in all_months_necessary]

rawDescription: Insert None while iterating list of months


rawDescription: Converting Float to Dollars and Cents

description: Converting Float to Dollars and Cents


code:
fruit = {'apple','banana','orange','pear'}
d = {'fruit': 'apple'}
d['fruit'] if 'fruit' in d and d['fruit'] in fruit else ''
d['fruit'] = 'watermellon'
d['fruit'] if 'fruit' in d and d['fruit'] in fruit else ''

rawDescription: Testing whether a value is in a set and assigning variable


code:
np.save('test.npy',{'one':1})
x=np.load('test.npy')
x
x[0]
x[()]
x.item()
x.item()['one']

rawDescription: Save scipy object to file

description: Save scipy object to file


rawDescription: Print Data in Dictionary in Python

description: Print Data in Dictionary in Python


code:
from collections import Counter
a = { (1,2):3, (1,3):5, (2,1):6 }

Counter(j for k in a for j in k)

rawDescription: Count how many times a part of a key appears in a dictionary python


code: axHistogram.plot(np.NaN, np.NaN, label='AGN', color='b', linewidth=1)

rawDescription: Legend stylings

description: Legend stylings


code:
import os
import time
from config import *

def func():

    os.system("killall -9 chromium-browser");
    with open(PROXIES_FILE) as f: proxies=f.read().split('\n')
    proxies=[proxy.strip() for proxy in proxies if proxy.strip()]
    seconds_slept = 0
    for i in range(NUM):
        if len(proxies)<=i: break
        os.system('nohup chromium-browser --proxy-server="http://{proxy}" --disable-popup-blocking -new-window --user-data-dir=~/tmp/f{i} {url}&'.format(url=URL, i=i, proxy=proxies[i]))
        time.sleep(5)
        seconds_slept += 5
    print('%s browsers opened successfully!'%(i+1))
    return seconds_slept

while True:
    time.sleep(2*60*60 - func())

rawDescription: is it possible to codein that after every 2 hours this script restarts?

description: Is it possible to codein that after every 2 hours this script restarts


code:
def on_doctree_read(app, doctree):
    for node in doctree.traverse(graphviz):
        code = re.sub('\];', ', color = red];', node['code'])  # change color of nodes and edges
        node['code'] = code

def setup(app):
    app.connect('doctree-read', on_doctree_read)

rawDescription: Extending sphinx.ext.graphviz with additional extension


code:
import lxml.etree as ET
import pprint

def fast_iter(context, func, *args, **kwargs):
    """
    http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ (Liza Daly)
    See also http://effbot.org/zone/element-iterparse.htm
    """
    for event, elem in context:
        func(elem, *args, **kwargs)
        # It's safe to call clear() here because no descendants will be
        # accessed
        elem.clear()
        # Also eliminate now-empty references from the root node to elem
        # (ancestor loop added by unutbu)
        for ancestor in elem.xpath('ancestor-or-self::*'):
            while ancestor.getprevious() is not None:
                del ancestor.getparent()[0]
    del context

def process_element(elem, namespaces):
    memelements = elem.findall('.//root:mem', namespaces=namespaces)
    pprint.pprint(memelements)

if __name__ == '__main__':
    xmlns = "http://www.ibm.com/j9/verbosegc"
    namespaces = {'root': xmlns}
    with open('small.xml', "r+") as xmlf:
        context = ET.iterparse(xmlf, events=('end', ),
                               tag='{{{}}}gc-start'.format(xmlns))
        fast_iter(context, process_element, namespaces)

rawDescription: lxml element.clear() and access childelements

description: Lxml element.clear() and access childelements


code:
from django.core import serializers
data = serializers.serialize('json', SomeModel.objects.all())

# it's pretty useful and quick.
data = serializers.serialize('json', SomeModel.objects.all(), fields=('foo','bar'))

rawDescription: How can I quickly dump a query result set into JSON?

description: Quickly dump a query result set into JSON


code:
import networkx as nx
import matplotlib.pyplot as plt

G1 = nx.balanced_tree(2,1)
G2 = nx.balanced_tree(2,2)

elarge1 =[(u,v) for (u,v,d) in G1.edges(data=True)]
elarge2 =[(u,v) for (u,v,d) in G2.edges(data=True)]

pos1=nx.spring_layout(G1)
pos2=nx.spring_layout(G2)

for k,v in pos2.items():
    # Shift the x values of every node by 10 to the right
    v[0] = v[0] +10

nx.draw_networkx_nodes(G1,pos1,node_size=30,node_color='b')
nx.draw_networkx_edges(G1,pos1,edgelist=elarge1,width=1,style='solid')

nx.draw_networkx_nodes(G2,pos2,node_size=50)
nx.draw_networkx_edges(G2,pos2,edgelist=elarge2,width=1)

plt.show() # display
plt.draw()

rawDescription: Draw Two Graph in Different Positions in NetworkX


code:
connection.execute("""
CREATE TABLE ...
""")

rawDescription: Use raw SQL to create tables in SQLAlchemy, after which use ORM


code:
from Tkinter import*

root = Tk()
root.geometry('500x500+100+100')

image1 = PhotoImage(file = 'Image.gif')

canvas = Canvas(root, width = 500, height = 400, bg = 'white')
canvas.pack
imageFinal = canvas.create_image(300, 300, image = image1)

def move():
    canvas.move(imageFinal, 0, 22)
    canvas.update()

button = Button(text = 'move', height = 3, width = 10, command = move)
button.pack(side = 'bottom', padx = 5, pady = 5)

root.mainloop()

rawDescription: Change position of label in Tkinter window


rawDescription: How to create new dictionary with reversed keys?

description: Create new dictionary with reversed keys


code:
product_change_url = reverse("admin:content_product_change", args=[str(obj.id)])
return "%s" % (product_change_url, obj.product_name)

rawDescription: Use Django Reverse for multiple args

description: Use Django Reverse for multiple args


code:
import subprocess

long_array = []
for i in xrange(1000):
    line = 'Line text number {0}'.format(i)
    long_array.append(line)
output_string = '\n'.join(long_array)  # can be anything you want as long as it is a string

proc = subprocess.Popen('less', stdin=subprocess.PIPE)
proc.communicate(output_string)

rawDescription: Handle large output - Python

description: Handle large output - Python


rawDescription: Find largest difference between adjacent floats in ordered array


code:
# leave var1 as default
a = item(var2='hello')

# leave var2 as default
a = item(var1='hey')

# overwrite both var1 and var2
a = item(var1='hey', var2='hello')

# use both defaults
a = item()

rawDescription: multiple default values for function arguments Python

description: Multiple default values for function arguments Python


code:
def pig_latinify(word):
    """
    takes input from user
    check IF there is a vowel at beginning
        do this
    ELSE
        do this
    print result

    :param :
    :return:
    :raises:

    """
    if word.isalpha() == False:
        return AssertionError
    elif word[0] in ("a", "e", "i", "o", "u"):
        result = word + "yay"
    else:
        while word[0] not in ("a", "e", "i", "o", "u"):
            word = word[1:] + word[0]
            result = word + "ay"
    return result

#pig_latinify()

word_starting_with_vowel = ["apple"]
word_starting_with_consonant = ["scratch"]
word_containing_alphanumeric = ["HE90LLO"]

def test_word_starting_with_vowel():
    for item in word_starting_with_vowel:
        assert pig_latinify("apple") == "appleyay"

def test_word_starting_with_vowel_2():
    for item in word_starting_with_vowel:
        assert pig_latinify("is") == "isyay"

def test_word_starting_with_consonant():
    for item in word_starting_with_consonant:
        assert pig_latinify("scratch") == "atchscray"

def test_word_containing_alphanumeric():
    for item in word_containing_alphanumeric:
        try:
            pig_latinify("HE90LLO")
        except AssertionError:
            assert True

if __name__ == "__main__":
    test_word_starting_with_vowel()
    test_word_starting_with_vowel_2()
    test_word_starting_with_consonant()
    test_word_containing_alphanumeric()

rawDescription: Python test case does not run at all, returns nothing


code:
import timeit as tt

lst_size = 10**5

# Set the percentages of input tried by user.
percentages = {'ints': .10,
               'floats': .10,
               'strings': .80}
assert 1 - sum(percentages.values()) < 0.00000001

ints_floats_strings = {k: int(v*lst_size) for k, v in percentages.items()}

setup = """
import ast

def f(x):
    try:
        float(x)
    except:
        pass

def g(x):
    try:
        ast.literal_eval(x)
    except:
        pass

l = [str(i) for i in range({ints})]
l += [str(float(i)) for i in range({floats})]
l += [']9' for _ in range({strings}//2)] + ['a' for _ in range({strings}//2)]
""".format(**ints_floats_strings)

stmt1 = """
for i in l:
    f(i)
"""

stmt2 = """
for i in l:
    g(i)
"""

reps = 10**1
t1 = tt.timeit(stmt1, setup, number=reps)
t2 = tt.timeit(stmt2, setup, number=reps)

print(t1)
print(t2)

print(t2/t1)

rawDescription: When to use ast.literal_eval

description: When to use ast.literal_eval


code:
import uuid

unique_filename = uuid.uuid4()

rawDescription: Python: How to create a unique file name?


code: pylab.semilogy(xaxis, pq_averages, 'ks-', markerfacecolor='white', label='DCTCP-PQ47.5')

rawDescription: how to make hollow square marks with matplotlib in python

description: Make hollow square marks with matplotlib in python


code:
ax = rawdat.plot(x='ts', y=['bid','ask'], marker='.', lw=0)
plot.hold()
rawdat.plot(x='lastTrade', y='last', marker='x', lw=0, ax=ax)
plt.show()

rawDescription: How do I plot multiple series with different x-values in Pandas?

description: Plot multiple series with different x-values in Pandas


code:
import numpy as np

full = np.array([
    [0, 0, 3],
    [1, 0, 1],
    [2, 1, 0]
])

assignments = np.array([0, 1, 0, 2, 1, 1, 0, 0])

res = np.zeros((np.max(assignments) + 1,) + full.shape, dtype=int)

r, c = np.nonzero(full)
n = full[r, c]

r = np.repeat(r, n)
c = np.repeat(c, n)

np.add.at(res, (assignments, r, c), 1)

print(res)

rawDescription: Faster way to "distribute" values of an ndarray into other ndarrays based on assignments?


code:
def get_token(self):
    '''Returns the next token and the part of input_string it matched.
       The returned token is None if there is no next token.
       The characters up to the end of the token are consumed.
       Raise an exception by calling no_token() if the input contains
       extra non-white-space characters that do not match any token.'''
    self.skip_white_space()
    # find the longest prefix of input_string that matches a token
    token, longest = None, ''
    for (t, r) in Token.token_regexp:
        match = re.match(r, self.input_string[self.current_char_index:])
        if match and match.end() > len(longest):
            token, longest = t, match.group()

    self.current_char_index += len(longest)
    if token == None and self.current_char_index < len(self.input_string):
        self.no_token()
    return (token, longest)

rawDescription: How to check for a sequence of characters that do not match a Regex

description: Check for a sequence of characters that do not match a Regex


code:
for line in fileinput.input(['thefile.txt'], inplace=True):
    print(line.replace('old stuff', 'shiny new stuff'))

rawDescription: String replacement on a whole text file in Python 3.x?


code: [x for i in np.arange(3) for x in [f1(i), f2(i)]]

rawDescription: Create a Python List with Multiple Elements per Iteration


code:
from Tkinter import *

class TrafficLights:

    def __init__(self):

        window = Tk()
        window.title("Traffic Light")

        frame = Frame(window)
        frame.pack()

        self.color = StringVar()

        radio_red = Radiobutton(frame, text="Red", bg="red", variable=self.color, value="R", command=self.on_RadioChange)
        radio_red.grid(row=10, column=1)

        radio_yellow = Radiobutton(frame, text="Yellow", bg="yellow", variable=self.color, value="Y", command=self.on_RadioChange)
        radio_yellow.grid(row = 10, column = 2)

        radio_green = Radiobutton(frame, text="Green", bg="green", variable=self.color, value="G", command=self.on_RadioChange)
        radio_green.grid(row = 10, column = 3)

        self.canvas = Canvas(window, width=450, height=300, bg="white")
        self.canvas.pack()

        self.oval_red = self.canvas.create_oval(10, 10, 110, 110, fill="white")
        self.oval_yellow = self.canvas.create_oval(120, 10, 220, 110, fill="white")
        self.oval_green = self.canvas.create_oval(230, 10, 330, 110, fill="white")

        self.color.set('R')
        self.canvas.itemconfig(self.oval_red, fill="red")

        window.mainloop()

    def on_RadioChange(self):
        color = self.color.get()

        if color == 'R':
            self.canvas.itemconfig(self.oval_red, fill="red")
            self.canvas.itemconfig(self.oval_yellow, fill="white")
            self.canvas.itemconfig(self.oval_green, fill="white")
        elif color == 'Y':
            self.canvas.itemconfig(self.oval_red, fill="white")
            self.canvas.itemconfig(self.oval_yellow, fill="yellow")
            self.canvas.itemconfig(self.oval_green, fill="white")
        elif color == 'G':
            self.canvas.itemconfig(self.oval_red, fill="white")
            self.canvas.itemconfig(self.oval_yellow, fill="white")
            self.canvas.itemconfig(self.oval_green, fill="green")

TrafficLights()

rawDescription: creating a traffic light using python

description: Creating a traffic light using python


code:
import pandas as pd
import urllib2
link = 'http://www.econ.yale.edu/~shiller/data/chapt26.xls'
socket = urllib2.urlopen(link)
xd = pd.ExcelFile(socket)
xd.sheet_names
df = xd.parse(xd.sheet_names[-1], header=None)
df

rawDescription: sheets of Excel Workbook from a URL into a `pandas.DataFrame`

description: Sheets of Excel Workbook from a URL into a `pandas.DataFrame`


rawDescription: How do i change milliseconds to seconds in python?

description: Change milliseconds to seconds in python


code: count_vect.fit_transform(t[0] for t in res)

rawDescription: Python: converting a tuple iterable to a string iterable


rawDescription: Truncating values before the decimal point


code:
def mycopy(obj):
    if isinstance(obj, list):
        return [mycopy(i) for i in obj]
    if isinstance(obj, tuple):
        return tuple(mycopy(i) for i in obj)
    if isinstance(obj, dict):
        return dict(mycopy(i) for i in obj.iteritems())
    return obj

rawDescription: Python deepcopy.. kind of

description: Python deepcopy.. kind of


code: from .utilities import function_name

rawDescription: General purpose Python functions in Django views.py


rawDescription: Distribution-type graphs (histogram/kde) with weighted data


code:
import itertools

def containsPythagoreanTriple(a):
    squares = {x*x for x in a} # set comprehension
    return any(x+y in squares for x,y in itertools.combinations(squares))

rawDescription: Pythagorean Triples Efficiency

description: Pythagorean Triples Efficiency


code:
from django.core.exceptions import ObjectDoesNotExist

class Cars(models.Model):
    image_file = models.ImageField(upload_to=upload_to_cars, null=True, blank=True)
    name = models.CharField(max_length=200)

    def save(self, *args, **kwargs):
        try:
            this = Cars.objects.get(id=self.id)
            if this.image_file:
                this.image_file.delete()
        except ObjectDoesNotExist:
            pass
        super(Cars, self).save(*args, **kwargs)

rawDescription: replacing a file while uploading in django

description: Replacing a file while uploading in django


code:
import re
import csv
import datetime

def getage(now, dob):
    years = now.year - dob.year
    months = now.month - dob.month
    if now.day < dob.day:
        months -= 1
        while months < 0:
            months += 12
            years -= 1
    return '%sy%smo'% (years, months)

with open('inputfile.csv','r') as fin, open('outputfile.csv','w') as fout:
    reader = csv.DictReader(fin)
    writer_clinics = csv.DictWriter(fout, reader.fieldnames, dialect="excel")
    writer_clinics.writeheader()

    for data in reader:
        today = datetime.date.today()
        DOB = datetime.datetime.strptime(data["DOB"], "%m-%d-%Y").date()
        data["Age"] = getage(today, DOB)
        writer_clinics.writerow(data)

rawDescription: Finding out Age in Months and Years given DOB in a CSV using python


rawDescription: Pythonista way of extracting elements from an array


code:
# Migrate all many to many references from alias object to primary object.
for related_many_object in alias_object._meta.get_all_related_many_to_many_objects():
    alias_varname = related_many_object.get_accessor_name()
    obj_varname = related_many_object.field.name

    # Treatment depends on if the many_to_many field is created through another model
    if getattr(alias_object, alias_varname).through._meta.auto_created:
        if alias_varname is not None:
            # standard case
            related_many_objects = getattr(alias_object, alias_varname).all()
        else:
            # special case, symmetrical relation, no reverse accessor
            related_many_objects = getattr(alias_object, obj_varname).all()
        for obj in related_many_objects.all():
            getattr(obj, obj_varname).remove(alias_object)
            getattr(obj, obj_varname).add(primary_object)
    else:
        related_many_objects = getattr(alias_object, alias_varname).all()

        through_model = getattr(alias_object, alias_varname).through
        through_field_name = None
        for f in through_model._meta.fields:
            if isinstance(f, ForeignKey):
                if f.rel.to == primary_class :
                # f is the field in our 'through' model which points to an instance of primary_class
                    through_field_name = f.name

        for obj in related_many_objects.all():
            kwargs = {
                through_field_name: obj,
            }
            for through_obj in through_model.objects.filter(**kwargs):
                setattr(through_obj, through_field_name, primary_object)
                through_obj.save()

rawDescription: Best way to merge duplicates in Django 1.3?

description: Merge duplicates in Django 1.3


code:
import datetime
from datetime import timedelta
from django.db import models
import __main__

# http://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

class_list = []
for each_date in daterange(datetime.date(2012, 1, 1), datetime.date.today()):
    date_string = each_date.strftime('%Y_%m_%d')
    setattr(__main__,
        'report_' + date_string,
        type('report_' + date_string, (), {'name': models.CharField(max_length=50), 'Meta': type('Meta', (), {'managed': False, 'db_table': 'report_' + date_string})})
        )

rawDescription: Dynamic table in django

description: Dynamic table in django


code: l = [ k for (k,v) in args.items() if v ]

rawDescription: Checking if variable exists in Namespace


rawDescription: get information about pytables metadata

description: Get information about pytables metadata


code:
import pandas as pd

pre_defined_list = ['foo', 'bar', 'baz']
good_data = []
for chunk in pd.read_csv('large_file.csv', chunksize=10**6):
    chunk = chunk[chunk['column_to_check'].isin(pre_defined_list)]
    good_data.append(chunk)

df = pd.concat(good_data)

rawDescription: Pandas / odo / bcolz selective loading of rows from a large CSV file


code:
from collections import defaultdict

x = defaultdict(list)
x['Key1'].append((1.000,2.003,3.0029))

rawDescription: How do you add multiple tuples(lists, whatever) to a single dictionary key without merging them?

description: Add multiple tuples(lists, whatever) to a single dictionary key without merging them


code:
import itertools
with open('test.txt') as f:
    lines = list(itertools.islice(f, 3000, 3500))

rawDescription: Python - Loadtext with specific lines for huge file


code:
from subprocess import Popen, PIPE

control_f4_sequence = '''keydown Control_L
key F4
keyup Control_L
'''

shift_a_sequence = '''keydown Shift_L
key A
keyup Shift_L
'''

def keypress(sequence):
    p = Popen(['xte'], stdin=PIPE)
    p.communicate(input=sequence)

keypress(shift_a_sequence)
keypress(control_f4_sequence)

rawDescription: Simulate keystroke in Linux with Python

description: Simulate keystroke in Linux with Python


rawDescription: creating flat list from two lists

description: Creating flat list from two lists


rawDescription: Python 3 Float Decimal Points/Precision

description: Python 3 Float Decimal Points/Precision


code:
import numpy as np
from numpy import subtract as s
fancy_indices = np.absolute(s.outer(frame[:,0],trTab[0,:])).argmin(axis=1)
frame[:,0] = trTab[1,:][fancy_indices]

rawDescription: numpy: find all occurences of elements from one table in another

description: Numpy: find all occurences of elements from one table in another


code:
df.loc['Diff'] = df.loc['RECL_LCC'] - df.loc['RECL_PI']
df

rawDescription: Pandas subtract 2 rows from same dataframe


code:
colormap = pdb.gimp_image_get_colormap(timg)[1]
colormap = (255,255,255) + colormap[3:]
pdb.gimp_image_set_colormap(timg, len(colormap), colormap)

rawDescription: Gimp, Script-Fu: How can I set a value in the colormap directly


rawDescription: merge a list of 2 lists or use a queryset?

description: Merge a list of 2 lists or use a queryset


code:
import os
from mercurial import commands,ui
os.mkdir("/repos/foo")
commands.init(ui.ui(),"/repos/foo")

rawDescription: Provisioning mercurial server

description: Provisioning mercurial server


rawDescription: Previous group match in Python regex

description: Previous group match in Python regex


code:
# s is the string to parse
loadavg = [float(x) for x in s.rsplit('load average: ', 1)[1].split(', ')]

rawDescription: What is the best way to extract load average float values from a string in Python?


code:
# doc string, top-level comments, imports, __all__ =

import warnings
warnings.warn("the spam module is deprecated", DeprecationWarning,
              stacklevel=2)

# normal module code

rawDescription: How to declare a module deprecated in python

description: Declare a module deprecated in python


code:
from gi.repository import Gtk, GdkPixbuf
store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, bool)

rawDescription: Python & GTK3: How to create a Liststore


code:
# example in the docs
Entry.objects.order_by('?')[:20]

rawDescription: How do I get 20 random records in Django?

description: Get 20 random records in Django


rawDescription: How to get a list of all indexes in python-elasticsearch

description: Get a list of all indexes in python-elasticsearch


code: sorted(a,key=lambda key:key[2]['mm'])

rawDescription: Sorting a nested list in python

description: Sorting a nested list in python


code:
import os
import stat

st = os.stat('somefile')
os.chmod('somefile', st.st_mode | stat.S_IEXEC)

rawDescription: How do you do a simple "chmod +x" from within python?

description: Do a simple "chmod +x" from within python


code:
from functools import partial

def setTrigger(self, pushButton,value):
    pushButton.setText(value)
    #other actions

def uiConfig(self):
    ##triggerbutton configuration
    self.ui.triggerButton.setText("Software")
    self.ui.triggerButton.setMenu(menu)

    menu = QtGui.QMenu()
    menu.addAction('Software', partial(self.setTrigger, self.ui.triggerButton, 'Software'))
    menu.addAction('Hardware', lambda: self.setTrigger(self.ui.triggerButton, 'Hardware'))

rawDescription: Qt4, QMenu addAction, connect function with arguments


code:
sites = hxs.select('//div[@id="pagination_contents"]/div[2]/div[a]')
for site in sites:
    ## This loop will run 33 times in my test.
    ## Access to each link:
    item['link'] = site.select('./a[2]/@href').extract()

rawDescription: not able to scrape product url using scrapy in python

description: Not able to scrape product url using scrapy in python


code:
fo=open("pi.txt", "wb")

def make_pi(num_digits):
    q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
    j = 0
    while True:
        if 4 * q + r - t < m * t:
            fo.write(str(m))
            yield m
            q, r, t, k, m, x = 10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x
            j += 1
            if j % 1000 == 0:
                print("Count status: %s" % j)
        else:
            q, r, t, k, m, x = q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2
        if j >= num_digits:
            break

for i in make_pi(50000):
    pass

fo.close()

rawDescription: Python write() doesn't write full file

description: Python write() doesn't write full file


code:
title, author, news_id
hi   ,    max,       1
hello,    max,       1
world,     me,       1
sup  ,     me,       2

rawDescription: Multiple field names in appengine search


code: iterparse(self, source, events=("start", "end",), tag="item")

rawDescription: Parsing Large XML file with Python lxml and Iterparse


code:
import pylab
fig = pylab.figure()
figlegend = pylab.figure(figsize=(3,2))
ax = fig.add_subplot(111)
lines = ax.plot(range(10), pylab.randn(10), range(10), pylab.randn(10))
figlegend.legend(lines, ('one', 'two'), 'center')
fig.show()
figlegend.show()
figlegend.savefig('legend.png')

rawDescription: Get legend as a separate picture in Matplotlib


code: tuple([10*x for x in img.size])

rawDescription: Multiplying a tuple by a scalar

description: Multiplying a tuple by a scalar


code:
mapping = {
    'A': 'Adam',
    'B': 'Bale',
    'Z': 'Talking'
    # etc...
}

name = mapping[your_string[0]]

rawDescription: Mapping string based on first letter

description: Mapping string based on first letter


code:
print("Location:http://newurl.com/foobar")
print # to end the CGI response headers.

rawDescription: How to do simple http redirect using Python?

description: Do simple http redirect using Python


code:
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = plt.figure(figsize=(10, 6)).add_subplot(111)
df.plot(ax=ax, kind='bar', legend=False)

bars = ax.patches
hatches = ''.join(h*len(df) for h in 'x/O.')

for bar, hatch in zip(bars, hatches):
    bar.set_hatch(hatch)

ax.legend(loc='center right', bbox_to_anchor=(1, 1), ncol=4)

rawDescription: How do I plot hatched bars using pandas?

description: Plot hatched bars using pandas


code:
AllocationSet(
    Alloc( name="some name", value=1.23 ),
    Alloc( name="another name", value=2.34 ),
    Alloc( name="yet another name", value=4.56 ),
)

rawDescription: Python method arguments with spaces

description: Python method arguments with spaces


code:
class T(tuple):
    def __add__(self, other):
        return T(x + y for x, y in zip(self, other))
    def __rmul__(self, other):
        return T(other * x for x in self)
a = T((1, 2))
b = T((3, 4))
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)

rawDescription: Overloading + to support tuples

description: Overloading + to support tuples


code:
df2
df1
df2.comb
df2.combine_first(df1)

rawDescription: join or merge with overwrite in pandas

description: Join or merge with overwrite in pandas


code:
def _get_last_message(self):
    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login(MAIL_USERNAME, MAIL_PASSWORD)
    mail.select("inbox")
    result, data = mail.search(None, "ALL")
    latest_email_id = data[0].split()[-1]
    result, data = mail.fetch(latest_email_id, "(RFC822)")
    raw_email = data[0][1]
    return raw_email

rawDescription: Doing functional tests on login process

description: Doing functional tests on login process


rawDescription: Remove a string (filename) from a bigger string (the whole path)


code:
def calc_adoption(ts):
    true_index = ts[ts].index
    if len(true_index) == 0:
        return 0
    first_true_index = true_index[0]
    false_index = ts.index.difference(true_index)
    false_index = false_index[false_index > first_true_index]
    if len(false_index) == 0:
        return 14 - first_true_index
    return false_index[0] - first_true_index

adopted_weeks = {k: calc_adoption(v) for k, v in weeks_adopted.iteritems()}

rawDescription: How to iterate through a dictionary pandas where values are tuples, and find first True and False values

description: Iterate through a dictionary pandas where values are tuples, and find first True and False values


code:
import xml.etree.cElementTree as cET

# ...

def rename_xml_files(directory):
    xml_files = [xml_file for xml_file in os.listdir(directory) ]

    for filename in xml_files:
        filename = filename.strip()
        full_filename = directory + "/" +filename
        print(full_filename)
        parsed = cET.parse(full_filename)
        del parsed

rawDescription: Reading 1000s of XML documents with BeautifulSoup


code: from itertools import groupby

rawDescription: Converting this loop to a list comprehension


rawDescription: slicing numpy array into two parts

description: Slicing numpy array into two parts


code:
import glob

id_set = set()
for filename in glob.glob('C://Folder_with_all_txt_files/*'):
    with open(filename) as f:
        ids = f.read().split()
        id_set.update(ids)

rawDescription: How to get a set of unique values from many lists efficiently (Python)

description: Get a set of unique values from many lists efficiently (Python)


code:
from nltk.corpus.reader import XMLCorpusReader
reader = XMLCorpusReader(dir, file)

rawDescription: How to use the Spanish Wordnet in NLTK?

description: Use the Spanish Wordnet in NLTK


code: [sub for i in range(1, 4) for sub in (2*i, -2*i)]

rawDescription: Comprehensions: multiple values per iteration


code:
A = np.cos(U)[:,None]*np.sin(V)
B = np.sin(U)[:,None]*np.sin(V)
C = np.repeat(np.cos(V)[None,:],U.size,0)
CP = np.dstack([a1*A, a2*B, a3*C])

SN = np.dstack([2*A/a1, 2*B/a2, 2*C/a3])

DA1 = (a1*a2*np.cos(V)*np.sin(V))**2
DA2 = a3*a3*np.sin(V)**4
DA3 = (a2*np.cos(U))**2 + (a1*np.sin(U))**2
DA = DA1 + DA2 * DA3[:,None]
DA = np.sqrt(DA)*(np.pi**2 / (2*Nu*Nv))

D = np.dot(CP, plane_normal)
S = np.sign(D-d)

F1 = np.dot(np.dot(SN, mat2.T), plane_normal)
F = F1 * DA
#F = F * S # apply sign
Vsum = F[S>0].sum()
Usum = F[S<=0].sum()

rawDescription: Slow computation: could itertools.product be the culprit?


code:
d = {}
d.setdefault('Key1',[]).append((1,2))
d
d['Key1'].append((1, 3))
d
d.setdefault('Key2',[]).append((4,2))
d

rawDescription: How to add a pair to a dictionary in python?

description: Add a pair to a dictionary in python


code: repaired_by = models.ForeignKey(User, null=True)

rawDescription: Making a list off all users in Django

description: Making a list off all users in Django


code:
df
xf = df.groupby(level=0)['amount'].agg(['sum', 'count'])
xf
pd.rolling_sum(xf['sum'], 3, 0) / pd.rolling_sum(xf['count'], 3, 0)

rawDescription: Apply rolling mean function on data frames with duplicated indices in pandas


code:
class Scores(base):
    __tablename__ = 'center_master'
    id = Column(Integer(), primary_key=True)
    email = Column(String(255), index=True)

rawDescription: Poor MySQL performance on EC2 Micro instance


code:
def ancestor_list_validator(l):
  if len(l) != len(set(l)):
    raise Exception("Repeated values in ancestor list!")

class Post(db.Model):
  # ...
  ancestors = db.ListProperty(db.Key, validator=ancestor_list_validator)

rawDescription: Appengine Model SelfReferenceProperty and parent child relationship


rawDescription: Django: Create a queryset

description: Django: Create a queryset


code:
old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]

rawDescription: Finding last occurence of substring in string, replacing that


code:
from PyQt4 import QtGui, QtCore

class TabBar(QtGui.QTabBar):
    def __init__(self, parent):
        QtGui.QTabBar.__init__(self, parent)
        self._editor = QtGui.QLineEdit(self)
        self._editor.setWindowFlags(QtCore.Qt.Popup)
        self._editor.setFocusProxy(self)
        self._editor.editingFinished.connect(self.handleEditingFinished)
        self._editor.installEventFilter(self)

    def eventFilter(self, widget, event):
        if ((event.type() == QtCore.QEvent.MouseButtonPress and
             not self._editor.geometry().contains(event.globalPos())) or
            (event.type() == QtCore.QEvent.KeyPress and
             event.key() == QtCore.Qt.Key_Escape)):
            self._editor.hide()
            return True
        return QtGui.QTabBar.eventFilter(self, widget, event)

    def mouseDoubleClickEvent(self, event):
        index = self.tabAt(event.pos())
        if index >= 0:
            self.editTab(index)

    def editTab(self, index):
        rect = self.tabRect(index)
        self._editor.setFixedSize(rect.size())
        self._editor.move(self.parent().mapToGlobal(rect.topLeft()))
        self._editor.setText(self.tabText(index))
        if not self._editor.isVisible():
            self._editor.show()

    def handleEditingFinished(self):
        index = self.currentIndex()
        if index >= 0:
            self._editor.hide()
            self.setTabText(index, self._editor.text())

class Window(QtGui.QTabWidget):
    def __init__(self):
        QtGui.QTabWidget.__init__(self)
        self.setTabBar(TabBar(self))
        self.addTab(QtGui.QWidget(self), 'Tab One')
        self.addTab(QtGui.QWidget(self), 'Tab Two')

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt: Editable Tab Labels

description: PyQt: Editable Tab Labels


code:
def capitalize_nth(s, n):
    return s[:n].lower() + s[n:].capitalize()

rawDescription: Python How to capitalize nth letter of a string


code:
with open('in.txt', 'r') as fin, open('out.txt', 'w') as fout:
    for line in fin:
        if line.startswith('00000'):
            fout.write(line)

rawDescription: How to find string in a file which start with 00000 and copy it in another file

description: Find string in a file which start with 00000 and copy it in another file


code:
import csv
import sys

def rows(lst):
    it = iter(lst)
    while True:
        row = list(iter(it.next, '\n'))  # it.__next__ in Python 3.x
        if not row:
            break
        yield row

lista = ["a","b","c","\n","d","e","f","\n","g","h","i","\n"]
writer = csv.writer(sys.stdout)  # Replace sys.stdout with file object
writer.writerows(rows(lista))

rawDescription: CSV Module to write new line data in list


code:
from os.path import join, expanduser
join(expanduser('~'), '.config') # You could have something more funky if you want to.

rawDescription: python os.path.expanduser() Is this always true

description: Python os.path.expanduser() Is this always true


rawDescription: Best way to format integer as string with leading zeros?

description: Format integer as string with leading zeros


code:
L = [1,2,3,4,5,6,7,8,9,0]
a = np.random.ranint(0,50,(35,10))

# identify location of value in array that are in L
ix = np.in1d(a.ravel(), L).reshape(a.shape)

rawDescription: Python: fast way to get position of all the element in a list in different lists given


code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import transforms

theta = np.linspace(0, 2 * np.pi, 13, endpoint=True)
fig, axes = plt.subplots(1, 4, figsize=(5, 2), subplot_kw=dict(polar=True))

for aa in axes.flat:
    aa.hold(True)
    r = np.random.rand(12)
    r = np.r_[r, r[0]]
    aa.plot(theta, r, '-sb')
    aa.set_rlim(0, 1)
    aa.set_yticklabels([])

factor = 1.1
d = axes[0].get_yticks()[-1] * factor
r_tick_labels = [0] + axes[0].get_yticks()
r_ticks = (np.array(r_tick_labels) ** 2 + d ** 2) ** 0.5
theta_ticks = np.arcsin(d / r_ticks) + np.pi / 2
r_axlabel = (np.mean(r_tick_labels) ** 2 + d ** 2) ** 0.5
theta_axlabel = np.arcsin(d / r_axlabel) + np.pi / 2

# fixed offsets in x
offset_spine = transforms.ScaledTranslation(-100, 0, axes[0].transScale)
offset_ticklabels = transforms.ScaledTranslation(-10, 0, axes[0].transScale)
offset_axlabel = transforms.ScaledTranslation(-40, 0, axes[0].transScale)

# apply these to the data coordinates of the line/ticks
trans_spine = axes[0].transData + offset_spine
trans_ticklabels = trans_spine + offset_ticklabels
trans_axlabel = trans_spine + offset_axlabel

# plot the 'spine'
axes[0].plot(theta_ticks, r_ticks, '-_k', transform=trans_spine,
             clip_on=False)

# plot the 'tick labels'
for ii in xrange(len(r_ticks)):
    axes[0].text(theta_ticks[ii], r_ticks[ii], "%.1f" % r_tick_labels[ii],
                 ha="right", va="center", clip_on=False,
                 transform=trans_ticklabels)

# plot the 'axis label'
axes[0].text(theta_axlabel, r_axlabel, '$r$', fontsize='xx-large',
             ha='right', va='center', clip_on=False, transform=trans_axlabel)

fig.savefig('test.png', bbox_inches='tight')

rawDescription: Polar plot with a 'floating' radial axis


code:
def validate(connection):
    cursor = connection.cursor()
    cursor.execute('PRAGMA table_info(table)')
    columns = cursor.fetchall()
    cursor.close()
    return (len(columns) == 2
            and columns[0][1:3] == ('A', 'TEXT')
            and columns[1][1:3] == ('B', 'TEXT'))

rawDescription: SQLite - Check table format on CREATE and drop if needed


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

fig, ax = plt.subplots()
x = np.linspace(1, 11, 100)
y = np.sin(x)
ax.plot(x, y)
ax.set_xscale('log')
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_major_locator(ticker.FixedLocator([1, 3, 6, 10]))
ax.set_xlim(0, 11)
plt.show()

rawDescription: how to make a particular axis which isn't linear or log?

description: Make a particular axis which isn't linear or log


code:
from __future__ import print_function

def transform_format_args(*args, **kwargs):
    num_args = kwargs['num_args']  # required
    filler = kwargs.get('filler', '')  # optional; defaults to ''

    if len(args) < num_args:  # If there aren't enough args
        args += (filler,) * (num_args - len(args))  # Add filler args
    elif len(args) > num_args:  # If there are too many args
        args = args[:num_args]  # Remove extra args

    return args

args1 = transform_format_args('cool', num_args=2)
print("This is {} code {}.".format(*args1))  # This is cool code .

args2 = transform_format_args('bird', 'worm', 'fish', num_args=2)
print("The {} ate the {}.".format(*args2))  # The bird ate the worm.

args3 = transform_format_args(num_args=3, filler='thing')
print("The {} stopped the {} with the {}.".format(*args3))
# The thing stopped the thing with the thing.

rawDescription: python: variable string formatting

description: Python: variable string formatting


code:
def custom_input(question):
    answer = input(question).lower()
    if answer == 'quit':
        sys.exit() # or whatever you want to do
    return answer

rawDescription: How can I write an always-on "Quit" option in Python?

description: Write an always-on "Quit" option in Python


code:
indices
zones, inv = unique(indices, return_inverse=True)
zones
new_indices = inv.reshape(indices.shape)
new_indices

rawDescription: Fast replacement of numpy values

description: Fast replacement of numpy values


code:
import thread, time

def foo():
  while True:
    blocking_function() #Actually waiting for a message on a socket

def run():
  thread.start_new_thread(foo, ())

run()
while True:
  #Keep the main thread alive
  time.sleep(1)

rawDescription: Python threading - blocking operation - terminate execution


code:
import itertools

it0, it1 = tee(f)   # no need for splitlines, just use the file object as an iterator

next(it1)   # throw away the first value from one of the iterators

for val0, val1 in zip(it0, it1):   # iterate in parallel
    if "some_string" in val0 and val1 == "some_value":
        do_stuff()

rawDescription: rewind iter(f.splitlines) one line back

description: Rewind iter(f.splitlines) one line back


code:
# convert to rectangular
x = r*numpy.cos(theta)
y = r*numpy.sin(theta)
z = z

rawDescription: Plotting a 3D Cylindrical Surface plot in Python


code:
test='HELIX 2 2 CYS A 97'
test.split()
test.split()[3]

rawDescription: How to extract specific columns from a space separated file in Python?

description: Extract specific columns from a space separated file in Python


code:
class Widget:
    def __init__(self):
        self.x = 1

    def sleep(self):
        os.sleep(self.x)

rawDescription: Python GIL: Do all participants in an expression have ref count incremented for the duration of the expression?


code:
import numpy as np
import pylab as pl

y, x = np.ogrid[-1:1:50j, -1:1:100j]
z = np.sqrt(x*x + y*y)

im = pl.imshow(z)
img = im.make_image()
h, w, s = img.as_rgba_str()
a = np.fromstring(s, dtype=np.uint8).reshape(h, w, 4)
pl.imsave("tmp.png", a)

rawDescription: How to save an array as an image in PyQt

description: Save an array as an image in PyQt


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({ 'A' : 1.,
                    'B' : pd.Timestamp('20130102'),
                    'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
                    'D' : np.array([3] * 4,dtype='int32'),
                    'E' : pd.Categorical(["test","train","tot","toast"]),
                    'F' : 'foo' })

elms=['test','train']

df[df.E.isin(elms)]

rawDescription: Finding matches in Panda DataFrame by matching a Panda DataFrame


code:
def get_queryset(self, request):
    qs = super(FilterUserAdmin, self).get_queryset(request)
    if request.user.is_superuser:
        return qs
    return qs.filter(user=request.user)

rawDescription: Django queryset filtering not working

description: Django queryset filtering not working


code: X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)

rawDescription: Stratified Train/Test-split in scikit-learn


code:
from shelve import DbfilenameShelf

class AutoSyncShelf(DbfilenameShelf):
    # default to newer pickle protocol and writeback=True
    def __init__(self, filename, protocol=2, writeback=True):
        DbfilenameShelf.__init__(self, filename, protocol=protocol, writeback=writeback)
    def __setitem__(self, key, value):
        DbfilenameShelf.__setitem__(self, key, value)
        self.sync()
    def __delitem__(self, key):
        DbfilenameShelf.__delitem__(self, key)
        self.sync()

my_shelf = AutoSyncShelf("myshelf")

rawDescription: Python 'shelve' that writes itself to disk after each operation


code:
from PIL import Image

mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32,
               'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}

i = Image.open('warty-final-ubuntu.png')
h, w = i.size

n_pixels = h * w
bpp = mode_to_bpp[data.mode]
n_bytes = n_pixels * bpp / 8

rawDescription: Is there a way to measure the memory consumption of a PNG image?


code:
class B(A):

    def copy(self):
        # this method is what I am confused about
        new_parent = self.a.copy()  # change 'a' with appropriate attribute name
        obj = self
        obj.pk = None
        # set obj's parent model to 'new_parent'
        obj.a = new_parent
        obj.save()
        return obj

rawDescription: Django multi table inheritance: Find and change parent model


code:
for person in people.find({'Father.First Name': 'Gunnar'}):
    print(person)

rawDescription: PyMongo Look up Dictionary Value when Value is in Sub-dictionary


code: workbook = xlsxwriter.Workbook(filename, {'strings_to_urls': False})

rawDescription: How can I get around Excel's URL Limitation?

description: Get around Excel's URL Limitation


rawDescription: Adding alphabetically items to QComboBox using PySide


code:
bill = int(input("Restaurant bill total: "))

fifteen = (bill * 0.15)

twenty = (bill * 0.20)

print("Your Actual bill : ", bill)
print("Bill with 15% additional charge : ", bill+fifteen)
print("Bill with 20% additional charge : ", bill+twenty)

input("\n\nPress the enter key to exit.")

rawDescription: 'int' object is not callable for python 3.2


code:
# Grades dictionnary
letter_grades = {
    'A' : 4.0,
    'A-' : 3.7,
    'B+' : 3.3,
    'B' : 3.0,
    'B-' : 2.7,
    'C+' : 2.3,
    'C' : 2.0,
    'C-' : 1.7,
    # and so on...
}

# Total grades
grades_number = 3
# List of grades
grades = []

print("This program calculates grade point average.")
for i in range(grades_number):
    grade = input("Enter course {} grade -> ".format(i+1))
    grades.append(grade)

try:
    # We try to sum the grades, but if a given one is wrong, then a KeyError with be thrown
    sum = sum([letter_grades[i] for i in grades])
    print ("Your GPA for last semester was -> ", sum / len(grades))
except KeyError:
    print("You entered a wrong grade.")

rawDescription: New to Python.. Gradepoint AVG?

description: New to Python.. Gradepoint AVG


code:
mycursor.execute("""
    INSERT INTO
        sensors
    VALUES
        ('$datetime', %s, %s)""", (temp, hum))

rawDescription: How to insert values of variables using python 2.7 into mysql?

description: Insert values of variables using python 2.7 into mysql


code:
import json
from subprocess import Popen, PIPE

json_data = json.dumps({"key":"value"})
p = subprocess.Popen("closure-execution", stdout=PIPE, stdin=PIPE, sterr=PIPE)
# stuff some data into the pipe and wait for the process to end:
stdout, sterr = p.communicate(json_data)

rawDescription: What is the simplest way for Clojure and Python programs to share information?


code:
import django
from django.conf import settings
settings.configure()
django.setup()
# Now you can use your models
from store.models import Store

rawDescription: django - "AppRegistryNotReady" message when I try to import csv file

description: Django - "AppRegistryNotReady" message when I try to import csv file


code: subprocess.Popen(['./script.sh ' + variable] , shell=True, stdout=subprocess.PIPE,  stderr=subprocess.STDOUT)

rawDescription: Why is my variable not be included in my subprocess.Popen?


code:
jsonValidateReturn = simplejson.dumps({'jsonValidateReturn': array_to_js})
return HttpResponse(jsonValidateReturn, mimetype='application/json')

rawDescription: Python | How to send a JSON response with name assign to it


code:
counts = numpy.histogram(data[:,2], bins=range(3))[0]
sums0 = numpy.histogram(data[:,2], bins=range(3), weights=data[:,0])[0]
sums1 = numpy.histogram(data[:,2], bins=range(3), weights=data[:,1])[0]

rawDescription: Subtotals in numpy

description: Subtotals in numpy


rawDescription: numpy 3D-image array to 2D

description: Numpy 3D-image array to 2D


code:
class Test(object):
    def __init__(self):
        self.lists = []

    def bind(self, value):
        self.lists.append(value)

rawDescription: misunderstanding web.py application

description: Misunderstanding web.py application


code:
import os, csv
path = r'I:\ARC\WIP\KevinWIP\Risk\Data\PythonGui'
os.chdir(path)
DistProb_LUT = [{} for i in range(7)]
with open('DispersalKernal10m.csv', mode = 'r') as infile:
    reader = csv.reader(infile)
    for row in reader:
        DistProb_LUT[0][row[0]] = row[1]
        DistProb_LUT[1][row[0]] = row[2]
        DistProb_LUT[2][row[0]] = row[3]
        DistProb_LUT[3][row[0]] = row[4]
        DistProb_LUT[4][row[0]] = row[5]
        DistProb_LUT[5][row[0]] = row[6]
        DistProb_LUT[6][row[0]] = row[7]

print(DistProb_LUT)

rawDescription: Create Multiple Python dictionaries from CSV using same column as key


code:
from yourAPI import PluginRegistry

def plugin_function():
    ... # your implementation

registry = PluginRegistry.get_instance()
registry.register("myplugin", plugin_function)

rawDescription: Python: auto detect new files and expose functions as a service


code:
import pandas as pd

import matplotlib.pyplot as plt

from sklearn import decomposition

# use your data file path here
demo_df = pd.read_csv(file_path)
demo_df.set_index('Unnamed: 0', inplace=True)

target_names = demo_df.index.values
tran_ne = demo_df.values

pca = decomposition.PCA(n_components=4)
pcomp = pca.fit_transform(tran_ne)
pcomp1 = pcomp[:,0]

fig, ax = plt.subplots()
ax.scatter(x=pcomp1[0], y=0, c='r', label=target_names[0])
ax.scatter(x=pcomp1[1], y=0, c='g', label=target_names[1])
ax.scatter(x=pcomp1[2], y=0, c='b', label=target_names[2])
ax.scatter(x=pcomp1[3], y=0, c='k', label=target_names[3])
ax.legend(loc='best')

rawDescription: Principal component analysis using sklearn and panda


code:
def invert_tag(self, start, end=None, tag=SEL, w=None):
    if w==None:
        w=self.cur_scroll() #This is my current text widget
    i=0
    while w.compare(start+"+"+str(i)+"c", "<", end):
        if "sel" in w.tag_names(start+"+"+str(i)+"c"):
            w.tag_remove(tag, start+"+"+str(i)+"c")
        else:
            w.tag_add(tag, start+"+"+str(i)+"c")
        i+=1

rawDescription: Tkinter: inverting what text has a tag in a range of two indexes


code:
import os

partition = input("Which drive do you want to search? ")
dirname = "XXX"
subdirname = "YYY"
for root, dirs, _fnames in os.walk(partition):
    if os.path.basename(root) != dirname: continue
    if not os.path.isdir(os.path.join(root, subdirname)): continue
    print("Found required folder:", root)
    break

rawDescription: Find a specified folder within a whole partition


code:
outputStream = StringIO.StringIO()
output.write(outputStream) #write merged output to the StringIO object

fname = 'filename'
self.response.headers['Content-Disposition'] = 'attachment; filename=' + fname + '.pdf'
self.response.write(outputStream.getvalue())

rawDescription: Uploading a file from python application to appengine


code:
class ClassA(object):
    def __init__(self, *args, **kwargs):
        pass

class ClassB(ClassA):

    def __init__(self, *args, **kwargs):
        self.a=kwargs.pop('a', 'A')
        self.b=kwargs.pop('b', 'B')
        self.c=kwargs.pop('c', 'C')
        super(ClassA, self).__init__(*args, **kwargs)

rawDescription: How do I add keyword arguments to a derived class's constructor in Python?

description: Add keyword arguments to a derived class's constructor in Python


code:
from numpy import sum
g_2 = sum(r) - g_1
comp = g_1 <= g_2

rawDescription: Array with 4 elements: need to compare max+min and the other 2 elements


code:
class CommandMetaclass(type):
    def __new__(mcl, name, bases, dct):
        # start with the option_list in the class we're creating
        # use set() to avoid duplicates
        option_list = set(dct.get('option_list', tuple()))

        # add the options from each base class
        for base in bases:
            option_list.update(base.__dict__.get('option_list', tuple()))

        # replace the original option_list with our combined version
        dct['option_list'] = tuple(option_list)

        return type.__new__(mcl, name, bases, dct)

class MyCommand(MyCommonOptionMixin, MyOtherCommonOptionMixin, BaseCommand):
    __metaclass__ = CommandMetaclass

    option_list = (
        # Local defined options.
    )

rawDescription: Python mixin to extend class property

description: Python mixin to extend class property


code:
"select * from students where school={schoolArg} and age={ageArg}".format(**{"schoolArg": "some school", "ageArg": 10})
"select * from teachers where class={classArg}".format(**{"classArg": "history"})

rawDescription: Dynamic String Replacement in Python using Format()


code:
from operator import itemgetter

def sortLinesPoints(data):
    if isinstance(data, dict):
        if 'children' in data:
            sortLinesPoints(data['children'])
    else:
        for elem in data:
            sortLinesPoints(elem)
        data.sort(key=itemgetter('type'))

rawDescription: Sorting multidimensional JSON objects in python


code:
declaration = """
file           := header, content
header         := shebang, version
shebang        := '#!', ts, word, ('-',[a-zA-Z0-9]+)?,'\n'
version        := 'version', ts, [0-9], '.', [0-9], ts, 'v', [0-9], '\n'

content        := node*
node           := word, ts, '{\n', nodecontent*, ts, '}', '\n'*
nodecontent    := ts, knobname, ts, knobvalue, '\n'
knobname       := word
knobvalue      := word / string / multiknobgroup / knobgroup
knobgroup      := '{', (word / string)*, ts, '}'
multiknobgroup :=  '{\n', (ts, knobgroup, '\n')*, ts, '}'
string         := '"', word*, '"'
word           := ([a-zA-Z0-9-_()/\~.<>?;:])+,ts
ts             := [ \t]*
"""

rawDescription: Parsing a nuke script with simpleparse EBNF


code: response = self.client.get('/contact/', follow=True)

rawDescription: Django: set cookie on test client?

description: Django: set cookie on test client


code:
import time
endTime = time.time() + 60
for t in threads:
    t.join(endTime - time.time())
    t.event.set()

rawDescription: How to wait for a list of threads to finish? (Python)

description: Wait for a list of threads to finish? (Python)


code:
datetimes = [ ... ]

# subtracting datetimes gives timedeltas
timedeltas = [datetimes[i-1]-datetimes[i] for i in range(1, len(datetimes))]

# giving datetime.timedelta(0) as the start value makes sum work on tds
average_timedelta = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)

rawDescription: Average timedelta in list

description: Average timedelta in list


rawDescription: Matches of array indexs Python

description: Matches of array indexs Python


code:
from django.forms.models import model_to_dict

order = Order.objects.get(pk=1)
dictionary = model_to_dict(order)
form = OrderEditForm(dictionary)

rawDescription: Pass an entire inital object in an edit form (data pre-population) in Django


code:
import os
import sys
import re
import fileinput

def sub_callback(match):
    func,args=match.groups()
    fargs=','.join('f({a})'.format(a=a) for a in args.split(','))
    return ('''\
#if def LOL
    {func}_new({fa})
#else
    {func}({a})
#endif
'''.format(func=func,a=args,fa=fargs))

for root, dirs, files in os.walk('.'):
    for line in fileinput.input(
        (os.path.join(root,name) for name in files),
        inplace=True,
        backup='_bak'
        ):
        line=re.sub(r'\b([A-C])\((.*?)\)',sub_callback,line)
        sys.stdout.write(line)

rawDescription: Recursively traverse directory and replace function calls


rawDescription: returning matches from an unknown number of python lists

description: Returning matches from an unknown number of python lists


code:
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtGui.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        login_widget = LoginWidget(self)
        login_widget.button.clicked.connect(self.login)
        self.central_widget.addWidget(login_widget)
    def login(self):
        logged_in_widget = LoggedWidget(self)
        self.central_widget.addWidget(logged_in_widget)
        self.central_widget.setCurrentWidget(logged_in_widget)

class LoginWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(LoginWidget, self).__init__(parent)
        layout = QtGui.QHBoxLayout()
        self.button = QtGui.QPushButton('Login')
        layout.addWidget(self.button)
        self.setLayout(layout)
        # you might want to do self.button.click.connect(self.parent().login) here

class LoggedWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(LoggedWidget, self).__init__(parent)
        layout = QtGui.QHBoxLayout()
        self.label = QtGui.QLabel('logged in!')
        layout.addWidget(self.label)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

rawDescription: Replace CentralWidget in MainWindow

description: Replace CentralWidget in MainWindow


code: { success: false, msg: 'Failed to save record' }

rawDescription: extjs ajax response with python bottle

description: Extjs ajax response with python bottle


code:
class POC(Entity):
  # ...
  #declare the one-to-many relationships
  csas = OneToMany('SSP')
  actions = OneToMany('SSP')
  # ...

class SSP(Entity):
  # ...
  #Tell Elixir how to disambiguate POC/SSP relationships by specifying
  #the inverse explicitly.
  csa = ManyToOne('POC', colname = 'idPOCCSA', inverse='csas')
  action = ManyToOne('POC', colname = 'idPOCAction', inverse='actions')
  # ...

rawDescription: Python SQLAlchemy/Elixer Question

description: Python SQLAlchemy/Elixer Question


code:
import maya.cmds as cmds

# Will return EVERYTHING selected
all_selected = cmds.ls(sl=True)

# Will filter out and return just the verts
# from everything selected
just_the_selected_verts = cmds.filterExpand(sm=31)

rawDescription: Maya Python - How do I query the selection to check if only polyVerts or different?


code:
#!/usr/bin/env python
from glob import glob
from multiprocessing.pool import ThreadPool
import serial

def get_response(path):
    try:
        s = serial.Serial(path, 9600, timeout=2)
        s.write('XXXdeviceCommandToReadValue XXXX\r\n')
        return path, s.readlines(), None
    except Exception as e:
        return path, None, e

paths = glob('/dev/serial/by-id/usb-XXXXdevNAME*')
results = ThreadPool(min(len(paths), 20)).imap_unordered(get_response, paths)
for path, lines, error in results:
    print(path, lines, error) # handle results here

rawDescription: Python readlines Api takes long time while accessing from serial port


code:
event.route.coords
event.route.x
event.route.y
event.route.json

rawDescription: GeoDjango - LineStringField - how to use it? Where do I find documentation?


code:
with open('youFile.txt','r') as fp:
    linesList = fp.readlines()
    # get the first
    first = linesList[0]
    # get the last
    last = linesList[-1]

rawDescription: How to get the first and the last date in a file

description: Get the first and the last date in a file


code:
import re

s = "heLLo hOw are you toDay"
pattern = re.compile("[A-Z]")
start = -1
while True:
    m = pattern.search(s, start + 1)
    if m == None:
        break
    start = m.start()
    print(start)

rawDescription: find index number of uppercase character in a string

description: Find index number of uppercase character in a string


code:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
        (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
        (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
        (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]

x = [date2num(date) for (date, value) in data]
y = [value for (date, value) in data]

fig = plt.figure()

graph = fig.add_subplot(111)

# Plot the data as a red line with round markers
graph.plot(x,y,'r-o')

# Set the xtick locations to correspond to just the dates you entered.
graph.set_xticks(x)

# Set the xtick labels to correspond to just the dates you entered.
graph.set_xticklabels(
        [date.strftime("%Y-%m-%d") for (date, value) in data]
        )

plt.show()

rawDescription: How to plot data against specific dates on the x-axis using matplotlib

description: Plot data against specific dates on the x-axis using matplotlib


code:
import glob
import os
import xlrd
import csv

ROOTDIR = r'C:\Users\username\Desktop\Mults'
wb_pattern = os.path.join(ROOTDIR, '*.xlsx')

workbooks = glob.glob(wb_pattern)

with open('out.csv', 'wb') as outcsv:
    writer = csv.writer(outcsv)
    for wb in workbooks:
        book_path = os.path.join(ROOTDIR, wb)
        book =  xlrd.open(book_path)
        sheet = book.sheet_by_index(0)
        for row_num in xrange(sheet.nrows):
           row = sheet(row_num)
           writer.writerow(row)

rawDescription: Python/Excel - Merge .xlsx workbooks from file into .csv


code:
in_parens=False
buffer=''
for char in my_string:

    if char =='(':
       in_parens=True
    elif char==')':
       in_parens = False
       my_list.append(buffer)
       buffer=''
    elif in_parens:
       buffer+=char
    else:
       my_list.append(char)

rawDescription: Split a string in Python having parenthesis (multiple splitters)


code: input("Press Enter to exit")

rawDescription: Exit on click x python

description: Exit on click x python


code: {{ banana.peel | safe }}

rawDescription: Returning HTML from class property in Python jinja2


code:
import urllib

url = 'http://www.example.com/'
data = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
}
headers = {
    'Overriden-Header': 'Overriden Header Value'
}

## Update the url and make the actual requests
url = '%s?%s' % (url, urllib.urlencode(data))
response = urllib.urlopen(url, headers=headers)

rawDescription: use Python urllib.urlopen to send data accurately

description: Use Python urllib.urlopen to send data accurately


rawDescription: What is the equivalent of x[i:] in Scala?


code:
pure_rating = int(rating_as_num)
decimal_part = rating_as_num - pure_rating
final_score = "+" * pure_rating
if decimal_part >= 0.75:
   final_score += "+"
elif decimal_part >= 0.25:
   final_score += "-"

rawDescription: Create a command line star rating with full and half stars from a float? Python 3


code:
import re
def open_delimited(filename, delimiter, chunksize=1024, *args, **kwargs):
    with open(filename, *args, **kwargs) as infile:
        remainder = ''
        for chunk in iter(lambda: infile.read(chunksize), ''):
            pieces = re.split(delimiter, remainder+chunk)
            for piece in pieces[:-1]:
                yield piece
            remainder = pieces[-1]
        if remainder:
            yield remainder

for line in open_delimited("log.txt", delimiter='/'):
    print(repr(line))

rawDescription: Change delimiter on "for each" loops on Strings in python


code:
print((str(unique_emails[x]) + ": ").ljust(20) +
      str(my_emails.count(unique_emails[x])).rjust(4))

rawDescription: How to do GOOD right justify in python? the string before str.rjust() has various length

description: Do GOOD right justify in python? the string before str.rjust() has various length


code:
from Tkinter import *
import cv2
from PIL import Image, ImageTk

isrunning = 0

def start():
    global isrunning
    if isrunning == 0:
        global cap
        cap = cv2.VideoCapture(0)
        isrunning = 1
        lmain.grid(row = 1,column = 1)
        def show_frame():
            _, frame = cap.read()
            frame = cv2.flip(frame, 1)
            frame = cv2.resize(frame, (800,600))
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            img = Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=img)
            lmain.imgtk = imgtk
            lmain.configure(image=imgtk)
            if isrunning == 1:
                lmain.after(10, show_frame)
            else:
                cap.release()
    show_frame()

def Stop():
    global isrunning
    isrunning = 0
    lmain.grid_forget()

def main():
    Stop()
    #Reset.invoke()
    #stopFunc.invoke()

root = Tk()
lmain = Label(root, width = 800, height = 600, bg = "blue")
stopFunc = Button(root, text = "stop", command = Stop)
Reset = Button(root, text = "Reset", command = start)
Main = Button(root, text = "Stop", command = main)
Start = Button(root, text = "Start", command = start)
Start.grid(row = 0, column = 0)
Main.grid(row = 0, column = 1)

root.mainloop()

rawDescription: Python Tkinter OpenCV PIL image resize to fit label


code:
from pydub import AudioSegment
from pydub.utils import make_chunks

def match_target_amplitude(sound, target_dBFS):
    change_in_dBFS = target_dBFS - sound.dBFS
    return sound.apply_gain(change_in_dBFS)

def sound_slice_normalize(sound, sample_rate, target_dBFS):
    def max_min_volume(min, max):
        for chunk in make_chunks(sound, sample_rate):
            if chunk.dBFS < min:
                yield match_target_amplitude(chunk, min)
            elif chunk.dBFS > max:
                yield match_target_amplitude(chunk, max)
            else:
                yield chunk

    return reduce(lambda x, y: x + y, max_min_volume(target_dBFS[0], target_dBFS[1]))

sound = AudioSegment.from_mp3("vanilla_sky.mp3")
normalized_db = min_normalized_db, max_normalized_db = [-32.0, -18.0]
sample_rate = 1000
normalized_sound = sound_slice_normalize(sound, sample_rate, normalized_db)

rawDescription: Can pydub set the maximum/minimum volume?


code:
env = dict(os.environ)
env['http_proxy'] = proxies[random.randrange(0, len(proxies))]
env['https_proxy'] = proxies[random.randrange(0, len(proxies))]

rawDescription: Flask gevent when downloading url do through proxy


code: [my_list[x:x+num] for x in range(0, len(my_list), num)]

rawDescription: pythonic way to split list?

description: Pythonic way to split list


rawDescription: Merge two python pandas data frames of different length but keep all rows in output data frame


code:
list(map(''.join, combinations_with_replacement(["a","b","c"],2)))
list(map(''.join, combinations_with_replacement(["a","b","c"],3)))
list(map(''.join, combinations_with_replacement(alphabet,4))) == orig(alphabet)

rawDescription: Variable number of predictable for loops in Python


code:
import ctypes

notepad_handle = ctypes.windll.user32.FindWindowW(None, "Untitled - Notepad")
ctypes.windll.user32.ShowWindow(notepad_handle, 6)

notepad_handle = ctypes.windll.user32.FindWindowW(u"Notepad", None)
ctypes.windll.user32.ShowWindow(notepad_handle, 6)

rawDescription: Is there a way to minimize a window in Windows 7 via Python 3?


code:
def runCommand(cj):
    return cj.runCommand()

l = executor.map(runCommand, self.parent_job.child_jobs)

rawDescription: trouble invoking concurrent.futures job in parallel

description: Trouble invoking concurrent.futures job in parallel


code:
x, y = my_function() #get x,y returned from my_function()
# append x to array1; append y to array2
array1.append(x)
array2.append(y)

rawDescription: Appending to 2 lists simultaneously

description: Appending to 2 lists simultaneously


rawDescription: "Like" condition instead of an "isin" in pandas


code:
# CreateTree
tree=scipy.spatial.KDTree(numpy.array(points)) # better give it a copy?
# Create random subsample of points
n_repr=1000
shuffled_points=numpy.array(points)
numpy.random.shuffle(shuffled_points)
shuffled_points=shuffled_points[:n_repr]
# Query the tree
(dists,points)=tree.query(shuffled_points,k=2,p=1)
# Get _extimate_ of average distance:
avg_dists=numpy.average(dists)
print('average distance Manhattan with nearest neighbour is:',avg_dists)

rawDescription: Interpolate unstructured X,Y,Z data on best grid based on nearest neighbour distance for each points


code:
import wx

#----------------------------------------------------------------------
class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)

        sizer = wx.FlexGridSizer(0, 3, 5, 5)
        sizer.AddGrowableCol(1)
        box = wx.BoxSizer(wx.VERTICAL)
        fs = self.GetFont().GetPointSize()
        bf = wx.Font(fs+4, wx.SWISS, wx.NORMAL, wx.BOLD)

        t = wx.StaticText(self, -1, "StandardPaths")
        t.SetFont(bf)
        box.Add(t, 0, wx.CENTER|wx.ALL, 4)
        box.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)

        # get the global (singleton) instance of wx.StandardPaths
        sp = wx.StandardPaths.Get()

        # StandardPaths will use the value of wx.App().GetAppName()
        # for some of the stnadard path components.  Let's set it to
        # something that makes that obvious for the demo.  In your own
        # apps you'll set it in to something more meaningfull for your
        # app in your OnInit, (or just let it default.)
        wx.GetApp().SetAppName("AppName")

        self.help = {}

        # Loop through all of the getters in wx.StandardPaths and make
        # a set of items in the sizer for each.
        def makeitem(name, *args):
            func = getattr(sp, name)
            sizer.Add(wx.StaticText(self, -1, "%s%s:" %(name, repr(args))),
                      0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            sizer.Add(wx.TextCtrl(self, -1, func(*args),
                                  size=(275,-1), style=wx.TE_READONLY),
                      0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)

            btn = wx.Button(self, wx.ID_HELP)
            sizer.Add(btn)
            self.help[btn] = func.__doc__

        for x in ['GetConfigDir',
                  'GetUserConfigDir',
                  'GetDataDir',
                  'GetLocalDataDir',
                  'GetUserDataDir',
                  'GetUserLocalDataDir',
                  'GetDocumentsDir',
                  'GetPluginsDir',
                  'GetInstallPrefix',
                  'GetResourcesDir',
                  'GetTempDir',
                  'GetExecutablePath',
                  ]:
            makeitem(x)

        # this one needs parameters
        makeitem('GetLocalizedResourcesDir', 'en',
                 wx.StandardPaths.ResourceCat_Messages )

        self.Bind(wx.EVT_BUTTON, self.OnShowDoc, id=wx.ID_HELP)

        box.Add(sizer, 0, wx.CENTER|wx.EXPAND|wx.ALL, 20)
        self.SetSizer(box)

    def OnShowDoc(self, evt):
        doc = self.help[evt.GetEventObject()]

        # trim the whitespace from each line
        lines = []
        for line in doc.split('\n'):
            lines.append(line.strip())
        doc = '\n'.join(lines)
        wx.TipWindow(self, doc, 500)

#----------------------------------------------------------------------
class MyFrame(wx.Frame):
    """"""

    def __init__(self):
        wx.Frame.__init__(self, None, title="Standard Paths",
                          size=(800,600))
        panel = TestPanel(self)
        self.Show()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: Is there a cross-platform convention/location for storing desktop app settings?


rawDescription: Handle pagination in python scrapy

description: Handle pagination in python scrapy


code:
import sys
import time

for i in range(10):
    time.sleep(0.5)
    sys.stdout.write('*')
    sys.stdout.flush()    # <-- this is the key
sys.stdout.write('\n')

rawDescription: Python sys.stdout.write() strange behavior in Mac terminal


code:
TEXT = '["kiarix moreno","116224357500406255237","z120gbkosz2oc3ckv23bc10hhwrudlcjy04",1409770337,"com.youtube.www/watch?v\u003dp1JPKLa-Ofc:https","es"]'
import json, ast, re
json.loads(TEXT)
ast.literal_eval(TEXT)
re.search(r'\["(?P<name>[^"]*)","(?P<number1>[^"]*)","(?P<data>[^"]*)",(?P<number2>\d*),"(?P<website>[^"]*)","(?P<language>[^"]*)"\]', TEXT).groupdict()

rawDescription: Regex to extract multiple fields from pattern


code:
import subprocess
import sys
child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
while True:
    out = child.stderr.read(1)
    if out == '' and child.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

rawDescription: Capture subprocess output

description: Capture subprocess output


code:
total = 0
for line in f:
    data = length(line)
    total += data
print(total)

rawDescription: How to count the number of characters in a file (not using the len function)?

description: Count the number of characters in a file (not using the len function)


rawDescription: How do I convert a Django QuerySet into list of dicts?

description: Convert a Django QuerySet into list of dicts


code:
def newrange(min_range, max_range, answer, inputtext):
  if answer > min_range and answer < max_range:
    return min_range, max_range, answer
  else:
    answer = 0
    min_range = input("Set a min range for conversion: ")
    max_range = input("Set a max range for conversion: ")
    answer = input(inputtext)
    return min_range, max_range, answer

def currency_convert():
  min_range = input("min range: ")
  max_range = input("max range: ")

  inputtext = "How many dollars to convert: "
  answer = input(inputtext)
  min_range, max_range, answer = newrange(min_range, max_range, answer, inputtext)

  sek = answer * 3
  print("%d is the same as" % (sek))

rawDescription: Python converter - I'm stuck

description: Python converter - I'm stuck


rawDescription: dataframe boolean selection along columns instead of row

description: Dataframe boolean selection along columns instead of row


code: sum((m - r + 1) * (n - r + 1) for r in xrange(1,n+1))

rawDescription: Sum() in python

description: Sum() in python


code: m = csr_matrix(dense_rot_matrix)

rawDescription: Sparse Rotation Matrix Python SciPy

description: Sparse Rotation Matrix Python SciPy


code:
statements = [ ... ]

obj = open( "some.py", "w+" )

for s in statements:
    obj.write( s.to_str() )

obj.close()

rawDescription: Using Python's basic I/O to manipulate or create Python Files?


code:
sys.stdin = subprocess.Popen(my_cmd, stdout=subprocess.PIPE, shell=True).stdout
s = pysam.Samfile("-", "rb")
sys.stdin = sys.__stdin__ # restore original stdin

rawDescription: using Python subprocess to redirect stdout to stdin?

description: Using Python subprocess to redirect stdout to stdin


code:
import datetime
datetime.datetime.strptime(date + ' ' + hour + ':' + minutes + ':' + seconds, '%m/%d/%Y %H:%M:%S')

rawDescription: app engine: string to datetime?

description: App engine: string to datetime


rawDescription: Select values in arrays

description: Select values in arrays


code:
import contextlib
import sqlite3

DATABASE = 'VOL_HOURS.db'
OUTPUT = 'VHOURS.nmf'
COLUMNS = ('BOB', 'DAVE', 'CAROL', 'ANDY', 'CARL', 'DANNY', 'CHERYL',
           'CYNTHIA', 'TARA', 'SCOTT', 'ASHLEY', 'CRYSTAL')

def main():
    with open(OUTPUT, 'w') as file:
        for row in from_volunteers():
            file.write(str(VolunteerList.new(row)))

def from_volunteers():
    with sqlite3.connect(DATABASE) as connection:
        with contextlib.closing(connection.cursor()) as cursor:
            query = 'SELECT {} FROM VOLUNTEERS'.format(', '.join(COLUMNS))
            cursor.execute(query)
            return cursor.fetchall()

class VolunteerList:

    @classmethod
    def new(cls, row):
        obj = cls()
        for key, value in zip(COLUMNS, row):
            obj[key] = value
        return obj

    def __init__(self):
        self.__data = [''] * len(COLUMNS)

    def __setitem__(self, key, value):
        self.__data[COLUMNS.index(key.upper())] = value

    def __str__(self):
        return ','.join(['VLIST'] + self.__data + ['\n'])

if __name__ == '__main__':
    main()

rawDescription: sqlite query in python writes only last row to file using objects

description: Sqlite query in python writes only last row to file using objects


code:
def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

rawDescription: How to load a model from an HDF5 file in Keras?

description: Load a model from an HDF5 file in Keras


code:
for author, attribs in ca_graph:
    # somehow calculate a year_value
    ca_graph.node[author]['year'] = year_value

rawDescription: How to add column with dates by using Corpus.slice

description: Add column with dates by using Corpus.slice


code:
import re
def action(matchObj):
    return str(float(matchObj.group(0)) * 2)

re.sub('\d+\.\d+', action, "[bezierPath moveToPoint: CGPointMake(7.98, 6.11)];")

rawDescription: What's the best way to search a number and replace it after calculation in a string by Python?


code:
import matplotlib.pyplot as plt

trianglex = [ 1, 10, 7, 1 ]
triangley = [ 2, 8, 4, 2 ]
triangle2x = [ 13, 25, 21, 13]
triangle2y = [ 5,  7 , 14, 5 ]

plt.figure('Triangles')
for i in range(3):
    plt.plot(trianglex, triangley, 'o-')
plt.fill(trianglex, triangley)

for i in range(3):
    plt.plot( triangle2x, triangle2y, 'o-')
plt.fill(triangle2x, triangle2y)

plt.show()

rawDescription: matplotlib: use fill_between to make coloured triangles

description: Matplotlib: use fill_between to make coloured triangles


code:
from BeautifulSoup import BeautifulSoup

html = open("products.html").read()
soup = BeautifulSoup(html)

product_codes = [tag.parent.findNextSiblings('font')[0].contents[0]
                 for tag in
                 soup.findAll(text='Product Code#')]

rawDescription: Help retrieving product code from HTML using Beautiful Soup


code:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'PAGINATE_BY': 10
}

rawDescription: Running the Django REST framework quickstart tutorial


code:
sys.version
sys.version_info
sys.winver   # Windows
os.uname()   # Unix
win32api.GetVersion()   # Windows
win32api.GetVersionEx() # Windows
sys.version_info >= (2, 6)
map(int, '4.3.8'.split('.')) >= [4, 2]
map(int, '4.3.8'.split('.')) >= [4, 4]
from distutils.version import StrictVersion
StrictVersion("4.3.8") < StrictVersion("4.4")

rawDescription: Is there exist in Python built-in entity to represent version?


code:
import ntpath
[ntpath.basename(entry.split('\n')[0]) for entry in mylist]

rawDescription: Regex to match varying strings in a list


code:
fs = [(lambda y: lambda x: x + y)(i) for i in xrange(10)]
[f(0) for f in fs]

rawDescription: How does a lambda function refer to its parameters in python?


code:
from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
fox.save_screenshot('screenshot.png') # saves screenshot of entire page
fox.quit()

im = Image.open('screenshot.png') # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']

im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

rawDescription: selenium cannot screenshot a web element

description: Selenium cannot screenshot a web element


code:
import requests
...
headers = ... # set up auth
...
params = { 'list' : 'true' }
response = requests.get('https://api.dropbox.com/1/metadata/dropbox/<directory>', params=params, headers=headers)
subdirs = [d['path'] for d in response.json()['contents'] if d['is_dir'] == True]
print(subdirs)

rawDescription: Dropbox Core API list all folders

description: Dropbox Core API list all folders


code: self.t1.delete('1.10') #deletes 'y' (line 1, column 10)

rawDescription: Tkinter Textbox index delete 1.10 not working


code:
results = ( Table
            .objects
            .using('production')
            .filter(foreign_id=76)
            .order_by()
            .distinct()
            )

rawDescription: Django QuerySet contains duplicate entries


code:
def fake_requested_from_root(fn):
    """
    Login decorator which when used on a view modifies the reqquest.path
    to fool the template into thibking that the request is coming from the
    root page
    """
    def decorator(request, **kwargs):
        request.path = reverse('home')
        return fn(request, **kwargs)
    return decorator

rawDescription: Custom function decorator for views that modified the request path


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

def f(l):
    x = l.copy()
    for i in l:
        if x.count(i) > 1:
            first_index = x.index(i)
            second_index = x.index(i, first_index + 1)
            x = x[:first_index] + x[second_index:]
    return x

rawDescription: Python - Remove between indexes of two values if it occurs twice in a list


code:
# linked_list is the list you want to reverse
previous_node = None
current_node = linked_list.head

while current_node is not None:
    next_node = node.get_next()
    current_node.set_next(previous_node)
    previous_node, current_node = current_node, next_node

linked_list.head = previous_node

rawDescription: Reverse link direction of singly linked list


code:
for w in xrange(workers):
        p = multiprocessing.Process(target=scrape_site, args=(q, ))
        p.start()
        processes.append(p)

rawDescription: Python Multiprocessing Will Not Continue Past Number of CPUs/Cores


code:
for sub in obj:
    if len(sub) == 2 and all(isinstance(i, list) for i in sub): # you can add " and isinstance(sub, list)" if you are not sure about the type of sub
        look_val(sub)

rawDescription: What should I use instead of isinstance()


rawDescription: Python class that extends int doesn't entirely behave like an int


code:
form = browser.forms()[0]
control = form.find_control(name="ctl00$SPWebPartManager1$g_9bdf5859_9c73_4144_8b6a_9a3b3df417d5$ctl01$ddlBrand")

rawDescription: Can't figure out how to use Mechanize with Python to select items from a dropdown box on an ASP.NET page


code:
import logging
import matplotlib
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path

import matplotlib.pyplot as plt
from numpy.random import rand

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

class Datum(object):
    colorin = colorConverter.to_rgba('red')
    colorShift = colorConverter.to_rgba('cyan')
    colorCtrl = colorConverter.to_rgba('pink')
    colorout = colorConverter.to_rgba('blue')

    def __init__(self, x, y, include=False):
        self.x = x
        self.y = y
        if include:
            self.color = self.colorin
        else:
            self.color = self.colorout

class LassoManager(object):
    def __init__(self, ax, data):
        self.axes = ax
        self.canvas = ax.figure.canvas
        self.data = data

        self.Nxy = len(data)

        facecolors = [d.color for d in data]
        self.xys = [(d.x, d.y) for d in data]
        fig = ax.figure
        self.collection = RegularPolyCollection(
            fig.dpi, 6, sizes=(100,),
            facecolors=facecolors,
            offsets = self.xys,
            transOffset = ax.transData)

        ax.add_collection(self.collection)

        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
        self.keyPress = self.canvas.mpl_connect('key_press_event', self.onKeyPress)
        self.keyRelease = self.canvas.mpl_connect('key_release_event', self.onKeyRelease)
        self.lasso = None
        self.shiftKey = False
        self.ctrlKey = False

    def callback(self, verts):
        logging.debug('in LassoManager.callback(). Shift: %s, Ctrl: %s' % (self.shiftKey, self.ctrlKey))
        facecolors = self.collection.get_facecolors()
        p = path.Path(verts)
        ind = p.contains_points(self.xys)
        for i in range(len(self.xys)):
            if ind[i]:
                if self.shiftKey:
                    facecolors[i] = Datum.colorShift
                elif self.ctrlKey:
                    facecolors[i] = Datum.colorCtrl
                else:
                    facecolors[i] = Datum.colorin
            else:
                facecolors[i] = Datum.colorout

        self.canvas.draw_idle()
        self.canvas.widgetlock.release(self.lasso)
        del self.lasso

    def onpress(self, event):
        if self.canvas.widgetlock.locked():
            return
        if event.inaxes is None:
            return
        self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
        # acquire a lock on the widget drawing
        self.canvas.widgetlock(self.lasso)

    def onKeyPress(self, event):
        logging.debug('in LassoManager.onKeyPress(). Event received: %s (key: %s)' % (event, event.key))
        if event.key == 'alt+alt':
            self.ctrlKey = True
        if event.key == 'shift':
            self.shiftKey = True

    def onKeyRelease(self, event):
        logging.debug('in LassoManager.onKeyRelease(). Event received: %s (key: %s)' % (event, event.key))
        if event.key == 'alt':
            self.ctrlKey = False
        if event.key == 'shift':
            self.shiftKey = False

if __name__ == '__main__':

    data = [Datum(*xy) for xy in rand(100, 2)]

    ax = plt.axes(xlim=(0,1), ylim=(0,1), autoscale_on=False)
    lman = LassoManager(ax, data)

    plt.show()

rawDescription: Combine key and mouse button events in wxpython panel using matplotlib


code:
import multiprocessing
def worker(name, que):
    que.put("%d is done" % name)

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=3)
    m = multiprocessing.Manager()
    q = m.Queue()
    workers = pool.apply_async(worker, (33, q))

rawDescription: Sharing a result queue among several processes


code:
import collections

def freq():
    var1 = dict()
    info = input("File Name")
    filehandle = open(info, "r")
    data = filehandle.read().upper()
    char_counter = collections.Counter(data)
    for char, count in char_counter.most_common():
        if char in data.upper():
            s = (str(count))
            my_tokens = s.split("|")
            print(my_tokens)
            var1[char] = my_tokens[0]
    return var1

var1 = freq()
print(var1)

rawDescription: Each loop of an if statement, save to a different variable


code:
import cv2
import urllib
import numpy as np

req = urllib.urlopen('http://answers.opencv.org/upfiles/logo_2.png')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr,-1) # 'load it as it is'

cv2.imshow('lalala',img)
if cv2.waitKey() & 0xff == 27: quit()

rawDescription: How can i read an image from an internet url in python cv2 , scikit image and mahotas?

description: Read an image from an internet url in python cv2 , scikit image and mahotas


code:
ed_user = User('ed', 'Ed Jones', 'edspassword') #user is the class you mapped the table to
session.add(ed_user)
session.commit() # basically auto saving here :)

rawDescription: Single-file storage for a Python application