code:
class GoDown(dict):
    """Dictionary with an additional attribute recording the initial key."""

    def __init__(self, **kwargs):
        if len(kwargs) != 1:
            raise TypeError("Exacly one keyword argument required.")
        super(GoDown, self).__init__(**kwargs)
        self.key = kwargs.keys()[0]

rawDescription: Python Tree / Dict

description: Python Tree / Dict


code:
def get_picture(self, event, data):
    drawable = self.movie_window.window
    colormap = drawable.get_colormap()
    pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8, *drawable.get_size())
    pixbuf = pixbuf.get_from_drawable(drawable, colormap, 0,0,0,0, *drawable.get_size())
    pixbuf.save(r'somefile.png', 'png')
    pixbuf.save(r'somefile.jpeg', 'jpeg')

rawDescription: save gtk.DrawingArea to file

description: Save gtk.DrawingArea to file


rawDescription: how can get the unicode version in my python3.4?

description: How can get the unicode version in my python3.4


code:
D_id_color = {'A': u'orchid', 'B': u'darkcyan', 'C': u'grey', 'D': u'dodgerblue', 'E': u'turquoise', 'F': u'darkviolet'}
x_coordinates = [1,2,3,4,5,6] # Added missing datapoint
y_coordinates = [3,3,3,3,3,3] # Added missing datapoint
size_map = [50,100,200,400,800,1200] # Added missing datapoint
color_map = [color for color in D_id_color.values()[:len(x_coordinates)]]
plt.scatter(x_coordinates,y_coordinates, s = size_map, c = color_map)

# The following two lines generate custom fake lines that will be used as legend entries:
markers = [plt.Line2D([0,0],[0,0],color=color, marker='o', linestyle='') for color in D_id_color.values()]
plt.legend(markers, D_id_color.keys(), numpoints=1)

plt.show()

rawDescription: matplotlib.pyplot scatterplot legend from color dictionary

description: Matplotlib.pyplot scatterplot legend from color dictionary


code:
import random
import time

##Declare Variables
user_num=0
##lottery_num=random.randint(10,99)
lottery_num=12

##Input
print("Welcome to the Lottery Program!")
user_num=int(input("Please enter a two digit number: "))
print("Calculating Results.")
for i in range(3):
  time.sleep(1)
  print(".")

##Calc & Output
lottery_tens = lottery_num // 10
lottery_ones = lottery_num % 10

user_tens = user_num // 10
user_ones = user_num % 10

if lottery_num == user_num:
    print("All your numbers match in exact order! Your reward is $10,000!\n")
elif lottery_tens == user_ones and lottery_ones == user_tens:
    print("All your numbers match! Your reward is $3,000!\n")
elif lottery_tens == user_tens or lottery_ones == user_ones \
  or lottery_ones == user_tens or lottery_tens == user_ones:
    print("One of your numbers match the lottery. Your reward is $1,000!\n")
else:
    print("Your numbers don't match! Sorry!")

##Same as Calc & Output using Sets.
##lottery_set = set('%02d' % lottery_num)
##user_set = set('%02d' % user_num)
##if lottery_num == user_num:
##    print("All your numbers match in exact order! Your reward is $10,000!\n")
##elif lottery_set == user_set:
##    print("All your numbers match! Your reward is $3,000!\n")
##elif lottery_set.intersection(user_set):
##    print("One of your numbers match the lottery. Your reward is $1,000!\n")
##else:
##    print("Your numbers don't match! Sorry!")

rawDescription: Compare two digit numbers for a lottery program in Python


code:
derp_r1_sum_select = """
    select sum(`derp_related_1`.`amount`)
    from `derp_related_1`
    where `derp_related_1`.`fk` = `derp`.`pk`
    """
derp_r2_sum_select = """
    select sum(`derp_related_2`.`amount`)
    from `derp_related_2`
    where `derp_related_2`.`fk` = `derp`.`pk`"
    """

def queryset(self, request):
        qs = super(DerpAdmin, self).queryset(request)
        qs = qs.extra(select={'derp_r1_sum': derp_r1_sum_select,
                              'derp_r2_sum': derp_r2_sum_select})
        return qs

rawDescription: Django aggregation across multiple tables in ModelAdmin queryset


code:
from django.conf.urls.defaults import *
from views import views

urlpatterns = patterns('',
     (r'^/us/$', views.american_time),
     (r'^/ca/$', views.canadian_time),
)

rawDescription: Why is the URL 404 not found with Django?


code:
import sys, tempfile, os
from subprocess import call

EDITOR = os.environ.get('EDITOR','vim') #that easy!

initial_message = "" # if you want to set up the file somehow

with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
  tf.write(initial_message)
  tf.flush()
  call([EDITOR, tf.name])

  # do the parsing with `tf` using regular File operations.
  # for instance:
  tf.seek(0)
  edited_message = tf.read()

rawDescription: call up an EDITOR (vim) from a python script

description: Call up an EDITOR (vim) from a python script


code: statement % conn.literal(query_params)

rawDescription: sqlite3 with python - query debugging - print the final query

description: Sqlite3 with python - query debugging - print the final query


code:
s = "Kilometer"
print(s.lower())

rawDescription: How to convert string to lowercase in Python?

description: Convert string to lowercase in Python


code:
self.glb_data_list = {'disp_type': 2}

disp_type = fields.SelectField(u'Preset Mapping',
                                      choices=[(0, u'Custom'),
                                      (1, u'Loopback'),
                                      (2, u'All_East'),
                                      (3, u'All_Wast'),
                                      (4, u'16_East_16_West'),
                                      (5, u'8_East_8_West'),
                                      (6, u'STM1_East')],
                                    coerce=int, default=0)

disp_type.data = self.glb_data_list['dist_type']

rawDescription: Assiging a value to wtform field

description: Assiging a value to wtform field


code:
try:
    open(filename, 'w').close()
    os.unlink(filePath)
    print('Filename is valid.')
except OSError:
    print('Filename is not valid.')

rawDescription: Check if a filename is valid

description: Check if a filename is valid


code:
ticks = labels = [650, 700]
plt.figure()
loansmin = pd.read_csv('../datasets/loanf.csv')
p=loansmin.boxplot('Interest.Rate','FICO.Score')
p.set_xticks(ticks)
p.set_xticklabels(labels)

rawDescription: Show only the n'th ticklabel in a pandas boxplot


rawDescription: Interpolation without specifying indices in Python


code: title2 = planTitle.findAll("h3")[1]

rawDescription: How to get second matched object while using .find method in Python

description: Get second matched object while using .find method in Python


rawDescription: Python/Numpy index of array in array

description: Python/Numpy index of array in array


code:
def intro(skips=3):
    print ('skip')
    answer = input()
    if 'skip' in answer:
        skips -= 1
        if skips <= 0:
            print('you are out of skips')
            end()
        elif skips > 0:
            print ('You have ' ,skips, ' left')
            intro(skips)
def end():
    print ('you are out of skips. Game Over')

intro()

rawDescription: ValueError: invalid literal for int() with base 10: 'skip'


code:
img = Image.open('myimage.pbm')

frames = []
for angle in range(0, 365, 5):
    # rotate the image with expand=True, which makes the canvas
    # large enough to contain the entire rotated image.
    x = img.rotate(angle, expand=True)

    # crop the rotated image to the size of the original image
    x = x.crop(box=(x.size[0]/2 - img.size[0]/2,
               x.size[1]/2 - img.size[1]/2,
               x.size[0]/2 + img.size[0]/2,
               x.size[1]/2 + img.size[1]/2))

    # do stuff with the rotated image here.

rawDescription: How do I stop PIL from swapping height/width when rotating an image 90°?

description: Stop PIL from swapping height/width when rotating an image 90°


code:
data = ["some", "data", "lots", "of", "strings"]
separator = "."

print(separator.join(data))
some.data.lots.of.strings

rawDescription: Python 3: str.join() with seperator

description: Python 3: str.join() with seperator


rawDescription: Select a specific child node based on tag using XPath or lxml


code:
bisect.bisect_left(pj, d1)
pj[bisect.bisect_left(pj, d1)]

rawDescription: Python:Continuing try loop until first item in list is found


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

gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])
ax1=plt.subplot(gs[:,:-1])
ax2=plt.subplot(gs[:-1,-1])
ax3=plt.subplot(gs[-1,-1])

# ax 1
X=np.linspace(0,10,100)
Y=np.sin(X)
#ax1 = plt.gca()
ax1.scatter(X, Y)
ax1.axis("tight")
ax1.set_title('ax1')
ax1.set_xlim([0,10])
ax1.set_ylim([-1,1])
# You can use ax1.set_xticks() and ax1.set_xticklabels() instead.
ax1.set_xticks([])
ax1.set_yticks([])
#plt.xticks([])
#plt.yticks([])

# ax 2
#ax2 = plt.gca()
vel=np.random.rand(1000)
n, bins, patches = ax2.hist(vel, 10, normed=True, histtype='stepfilled', facecolor='green', alpha=1.0)
ax2.set_title('Velocity Distribution')
ax2.axis("tight")
# You can use ax2.set_xticks() and ax2.set_xticklabels() instead.
ax2.set_xticks([0,0.5,1])
ax2.set_yticks([0,1,2])
#plt.xticks([0,0.05,0.10])
#plt.yticks([0,10,20])

# ax 3
Z=np.exp(X)
ax3.plot(X, Z,'red', lw=5)
# You can use ax3.set_xticks() and ax3.set_xticklabels() instead.
ax3.set_xticks([0, 5, 10])
ax3.set_yticks([0, 10000, 20000])
ax3.set_yticklabels(['0', '10K', '20K'])

plt.show()

rawDescription: Python subplots not working properly

description: Python subplots not working properly


rawDescription: assert_has_calls does not stub the method call

description: Assert_has_calls does not stub the method call


code:
a = "string1"
b = "string2"
dic = {'a':a, 'b':b}
return render(request, 'index.html', dic)

rawDescription: Get value from a dictionary key in django template


code:
def __new__(cls, *args):
   ... # as above
   new_self = super(MyClass, cls).__new__(cls)
   new_self.args = new_args
   return new_self

#def __init__(self, *args):
#    self.args = args

rawDescription: Python: override __init__ args in __new__


code:
for n in range (lo_limit, up_limit + 1):
    if (int(n) % 2 == 0):
        printedstring=str(n)
        for a in range (1, n + 1):
            if is_prime(a):
                for b in range(1, n + 1):
                    if is_prime(b):
                        if (a + b == n):
                            if (a <= b):
                                printedstring = printedstring + str(" = ", a, " + ", b)
        print(printedstring)

rawDescription: Goldbach Python Output

description: Goldbach Python Output


code:
#!/usr/bin/env python3
import html
import sys
from subprocess import Popen, PIPE, STDOUT, DEVNULL
from textwrap import dedent

from flask import Flask, Response # $ pip install flask

app = Flask(__name__)

@app.route('/')
def index():
    def g():
        yield "<!doctype html><title>Stream subprocess output</title>"

        with Popen([sys.executable or 'python', '-u', '-c', dedent("""\
            # dummy subprocess
            import time
            for i in range(1, 51):
                print(i)
                time.sleep(.1) # an artificial delay
            """)], stdin=DEVNULL, stdout=PIPE, stderr=STDOUT,
                   bufsize=1, universal_newlines=True) as p:
            for line in p.stdout:
                yield "{}".format(html.escape(line.rstrip("\n")))
                yield "
\n"
    return Response(g(), mimetype='text/html')

if __name__ == "__main__":
    import webbrowser
    webbrowser.open('http://localhost:23423') # show the page in browser
    app.run(host='localhost', port=23423, debug=True) # run the server

rawDescription: Flask: Showing print on website instead of console?


code:
value = datetime.timedelta(0, 64800)
(datetime.datetime.min + value).time()

rawDescription: Python: How do I get time from a datetime.timedelta object?


rawDescription: How to return default value if field is NULL?

description: Return default value if field is NULL


code:
import builtins

def print(*args, **kwargs):
    builtins.print("    > ", *args, **kwargs)

rawDescription: Python: Indent print output from class

description: Python: Indent print output from class


rawDescription: alternative to python's time.sleep()

description: Alternative to python's time.sleep()


code:
Example
from __future__ import print_function
import numpy

a = numpy.arange(0, 100, 10) # 0, 10, 20, ...
ind = numpy.where(a>30)[0]
print(ind) # [4 5 6 7 8 9]

rawDescription: Extracting coordinates of region within matrix


code:
import itertools
from pprint import pprint

def stanzas(f):
    stanza = []
    for line in f:
        line = line.strip()
        if line.startswith('['):
            if stanza:
                yield stanza
            stanza = []
        if line:
            stanza += [line]
    if stanza:
        yield stanza

with open('foo.ini') as input_file:
    all_data = stanzas(input_file)
    all_data = sorted(all_data, key = lambda x:x[0])
    all_data = itertools.groupby(all_data, key = lambda x:x[0])
    all_data = {k:list(v) for k,v in all_data}

# All of the data is in a dict in all_data. The dict keys are whatever
# stanza headers in the file there were.
# We can extract out the bits we want using []
bigListA = all_data['[Blocktype A]']
bigListB = all_data['[Blocktype B]']
pprint(bigListA)
pprint(bigListB)

rawDescription: Parse text file between specific lines

description: Parse text file between specific lines


code:
x == 1 # x is less than 10, so it is doubled
x == 2 # x is less than 10, so it is doubled
x == 4 # x is less than 10, so it is doubled
x == 8 # x is less than 10, so it is doubled
x == 16 # now x is greater than 10, so it is not doubled again

rawDescription: is counter has certain value inside a class in python

description: Is counter has certain value inside a class in python


code:
import itertools

with open(filename1) as in1, open(filename2) as in2, open(filename3, "w") as out:
    for line1, line2 in itertools.izip(in1, in2):
        out.write("{0:0{1}b}\n".format(long(line1, 2) & long(line2, 2), len(line1) - 1))

rawDescription: Is there some way to AND two strings in python?


code:
fg = seaborn.factorplot(x='Group', y='val', hue='Mean',
                        col='Sex', data=data, kind='bar',
                        ci=68, row='Split',
                        order=['Group 1', 'Group 2'],
                        row_order=['Poor','Good'],
                        col_order=['Male', 'Female'],
                        sharex=False, sharey="row",
                        palette='deep', legend_out=False
                       )

(fg.set_axis_labels("", "val")
  .set_titles("{row_name} - {col_name}")
  .set(ylim=(0, 300))
  .despine(left=True)
)

# Increase space between rows and remove space between cols
fg.fig.subplots_adjust(hspace=.4, wspace=0)

# Change some label sizes
fg.axes[0, 0].title.set(size=16)
fg.axes[1, 0].yaxis.label.set(size=16)
plt.setp(fg.axes[0, 1].get_xticklabels(), size=16)

# Remove the legend title
fg.axes[0, 0].legend()

# Save to a vector format
fg.savefig("figure.svg")

rawDescription: Seaborn - aesthetic options

description: Seaborn - aesthetic options


code:
def DeleteToDo():
    print ("Which Item Do You Want To Delete?")
    DeleteItem = raw_input(">") #select a line number to delete
    print ("Are You Sure You Want To Delete Number" + DeleteItem + "(y/n)")
    DeleteItem=int(DeleteItem)
    VerifyDelete = str.lower(raw_input(">"))
    if VerifyDelete == "y":
        FILE = open('data.txt',"r") #open the file (tried w+ as well, entire file is deleted)
        lines=[x.strip() for x in FILE if int(x[:x.index('.')])!=DeleteItem] #read all the lines first except the line which matches the line number to be deleted
        FILE.close()
        FILE = open('data.txt',"w")#open the file again
        for x in lines:FILE.write(x+'\n')    #write the data to the file

    else:
        print ("Nothing Deleted")
DeleteToDo()

rawDescription: Delete a row from a text file with Python


code: columns = [c.firstChild.data for c in pmaexport.getElementsByTagName('column') if c.getAttribute('name') == 'news_title']

rawDescription: Extracting Data from Mysql XML dump with xml.dom.minidom


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

root = tree.getroot()
count = 0
for changetexts in root.findall('log'):
    temp = changetexts.text
    lines =  temp.splitlines()
    tenlines = lines[0:10]
    print (len(tenlines)) # Should be 10, use tenlines variable as you wish !!

rawDescription: Edit the text while parsing the xml file


code:
import os
class FCopy(object):
    def __init__(self, source):
        self.source = source
        self.target = os.path.join(source, '_output')
        if not os.path.exists(self.target):
            os.makedirs(os.path.abspath(self.target))
        self.lf, self.ld = [], []

    def walk(self, path):
        for x in (os.path.join(path, x) for x in os.listdir(path)):
            if x == self.target:continue
            if os.path.isfile(x):
                self.lf.append(x)
            elif os.path.isdir(x):
                self.ld.append(x)
                self.walk(x)
            #extra code if you want to handle symlinks

    def do(self):
        #if thats all you want,
        #code this directly in walk
        self.walk(self.source)

        for x in self.ld:
            x = x.replace(self.source, self.target)
            os.makedirs(x)
        for x in self.lf:
            x = x.replace(self.source, self.target)
            with open(x, 'w') as f:pass

f = FCopy('C:\\PerfLogs\\w\\tmp\\codemirror')
f.do()

rawDescription: Create a duplicate of a folder and the folders in it, while changing their names


code:
import numpy as np
import matplotlib.pyplot as plt
# import for 3d plot
from mpl_toolkits.mplot3d import Axes3D
# initializing 3d plot
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
# several data points
r = np.array([0, 14, 64, 114])
# get lengths of the separate segments
r[1:] = r[1:] - r[:-1]
phi = np.array([255.6, 255.6, 261.7, 267.4])
theta = np.array([-79.5, -79.5, -79.4, -78.8])
# convert to radians
phi = phi * 2 * np.pi / 360.
# in spherical coordinates theta is measured from zenith down; you are measuring it from horizontal plane up
theta = (90. - theta) * 2 * np.pi / 360.
# get x, y, z from known formulae
x = r*np.cos(phi)*np.sin(theta)
y = r*np.sin(phi)*np.sin(theta)
z = r*np.cos(theta)
# np.cumsum is employed to gradually sum resultant vectors
ax.plot(np.cumsum(x),np.cumsum(y),np.cumsum(z))

rawDescription: Convert a 3d drillhole trace to cartesian coordinates and plot it with matplotlib


code:
grp = df.groupby(['split_1','split_2'])
grp.agg([np.mean, np.median, np.max, np.min, np.size]).stack(0)

rawDescription: Pandas spreadsheet like tabular

description: Pandas spreadsheet like tabular


code:
class Task(models.Model):
    CANCELLED = -1
    REQUIRES_ATTENTION = 0
    WORK_IN_PROGRESS = 1
    COMPLETE = 2

    Status = (
        (CANCELLED, 'Cancelled'),
        (REQUIRES_ATTENTION, 'Requires attention'),
        (WORK_IN_PROGRESS, 'Work in progress'),
        (COMPLETE, 'Complete'),
    )

    status = models.IntegerField(choices=Status, default=REQUIRES_ATTENTION)

rawDescription: Best practice for Python & Django constants


code:
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
import numpy as np

# your dataset
nValues = np.arange(0,30)
xValues = np.linspace(0,10)
dataset = [(xValues-5-0.5*n)**2 for n in nValues]

# setup the normalization and the colormap
normalize = mcolors.Normalize(vmin=nValues.min(), vmax=nValues.max())
colormap = cm.jet

# plot
for n in nValues:
    plt.plot(dataset[n], color=colormap(normalize(n)))

# setup the colorbar
scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)
scalarmappaple.set_array(nValues)
plt.colorbar(scalarmappaple)

# show the figure
plt.show()

rawDescription: show matplotlib colorbar instead of legend for multiple plots with gradually changing colors

description: Show matplotlib colorbar instead of legend for multiple plots with gradually changing colors


code:
left_df['Helper'] = left_df.groupby(['amount','date']).cumcount()
right_df['RHelper'] = right_df.groupby(['amount','date']).cumcount()

rawDescription: Pandas join without replacement

description: Pandas join without replacement


code:
a = [0, 5, 1]
b = [1, 2, 1]
list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
b = [2, 3, 4]
list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))

rawDescription: Python Repeat Elements in One List Based on Elements from Another


code: binaries &= ~(modifier > 0.2)

rawDescription: Optimizing Boolean Compares Between Arrays with Python


rawDescription: pandas groupby access last group

description: Pandas groupby access last group


code:
plt.gca().set_aspect('equal')
i, j = np.where(np.all(r!=255, axis=2))
xlimits = j.min(), j.max()
ylimits = i.min(), i.max()
plt.xlim(xlimits)
plt.ylim(ylimits)

rawDescription: Apply complex transformation to an image using matplotlib and numpy


code:
import Tkinter as tk

root = tk.Tk()
lb1 = tk.Listbox(root)
lb2 = tk.Listbox(root)
vsb1 = tk.Scrollbar(root, orient="vertical", command=lb1.yview)
vsb2 = tk.Scrollbar(root, orient="vertical", command=lb2.yview)
lb1.configure(yscrollcommand=vsb1.set)
lb2.configure(yscrollcommand=vsb2.set)

lb1.pack(side="left", fill="both", expand=True)
vsb1.pack(side="left", fill="y", expand=False)
lb2.pack(side="left", fill="both", expand=True)
vsb2.pack(side="left", fill="y", expand=False)

root.mainloop()

rawDescription: TK, understanding pack and expanding space


code:
#!/usr/bin/python

import sys
import fileinput

x = open("output.txt", "a")

for line in fileinput.input():
    l = line.replace(r"{\frac{d^{2}}{d^{2}{r}}}\zeta","\zeta''")
    x.write(l)

rawDescription: Replace Mathematical Symbols in File

description: Replace Mathematical Symbols in File


code:
import numpy as np

v = np.array([1., 1., 1., np.nan, 1., 1., 1., 1., np.nan, 1.])
n = np.isnan(v)
a = ~n
c = np.cumsum(a)
d = np.diff(np.concatenate(([0.], c[n])))
v[n] = -d
np.cumsum(v)

rawDescription: Cumsum reset at NaN

description: Cumsum reset at NaN


code:
def count():
    nLiving = 0
    nDead = 0
    for y in range(size_y):
        for x in range(size_x):
            if live[x][y]==0:
                nDead+=1
            if live[x][y]==1:
                nLiving+=1
    z = nLiving / 10.0
    print("nLiving over ten is: ", z,)
    print("%")
    return nLiving

def one_game(initial):
    load(initial)
    gen_array = []
    for gen in range(1, 101):
        print("Gen: ", str(gen) + ":",)
        nLiving = count()
        process()
        gen_array.append(nLiving)
    return gen_array

def many_games():
    gen_output = []
    numbers = range(1,51)
    for initial in numbers:
        print(initial/100.0)
        gen_array = one_game(initial/100.0)
        gen_output.append(gen_array)
    return gen_output

gen_output = many_games()
#one_game(0.5)

fig, ax = plt.subplots(1)

x = np.array( gen_output )

p = ax.pcolormesh(x)
fig.colorbar(p)
plt.show()

rawDescription: How do I get my data in my heatmap?

description: Get my data in my heatmap


code:
sql = "update %s set %s" % (my_table, ','.join('%s=%%s' % f for f in fields))
values = [current_response_dict[site][info_type] for site in site_list for info_type in self.all_info_type]
cursor.execute(sql, values)

rawDescription: What's wrong with this sql

description: What's wrong with this sql


code:
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

# since you have a column of lists skip any type of string munging
# instead, go straight to converting the lists to a Series
s = df['ID'].apply(Series,1).stack()
s.index = s.index.droplevel(-1)
s.name = 'ID'
del df['ID']
df = df.join(s)

rawDescription: Pandas - convert list to string & Wide to Long with one column


code:
for root, dirs, files in os.walk(directory):
    for filename in files:
        if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')):
            pass

rawDescription: Use fnmatch.filter to filter files by more than one possible file extension


code:
df
df.reset_index().pivot('loc', 'time', 'speed')

rawDescription: pandas DataFrame pivoting issue

description: Pandas DataFrame pivoting issue


code:
if("multipart/form-data" in headers["Content-Type"]):
    data_list = []
    content_list = content.split("\r\n\r\n")
    for i in range(len(content_list) - 1):
        data_list.append("")

    data_list[0] += content_list[0].split("name=")[1].split(";")[0].replace('"','') + "="

    for i,c in enumerate(content_list[1:-1]):
        key = c.split("name=")[1].split(";")[0].replace('"','')
        data_list[i+1] += key + "="
        value = c.split("\r\n")
        data_list[i] += value[0]

    data_list[-1] += content_list[-1].split("\r\n")[0]

    content = "&".join(data_list)

rawDescription: Python server cgi.FieldStorage parsing multipart/form-data


code:
NestedList = [["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],["BLAHBLAH\Pics","BLAHBLAH\Folder","BLAHBLAH\Music"]]
output = [[os.path.basename(path) for path in li] for li in NestedList]

rawDescription: Remove everything before certain character in nested lists (Python)


code:
from scipy.spatial.distance import cdist
A = np.random.randn(540, 2)
B = np.random.randn(540, 2)
alpha = 1.
ind = np.all(cdist(A, B) > alpha, axis=0)
outliers = B[ind]

rawDescription: fastest way to find euclidean distance in python

description: Fastest way to find euclidean distance in python


code:
strings = ['a', 'b']
strings = [s + 'c' for s in strings]

rawDescription: Changing python immutable type while iterating through a mutable container such as list


code:
from eve import Eve
app = Eve()

@app.route('/hello')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

rawDescription: REST API framwork that works with my python program instead of Database


code:
s = scatter(X,Y, s=75, c=T, alpha=.5)
colorbar(s)
show()

rawDescription: Python scattered chart legend

description: Python scattered chart legend


code:
from PyQt4.QtCore import QProcess

class YourClass(QObject):

    [...]

    def videoProcess(self):
        self.pushButton.setEnabled(0)
        self.pushButton.setText("Please Wait")
        command = "handbrake.exe"
        args =  ["-i", "somefile.wmv", "-o", "somefile.mp4"]
        process = QProcess(self)
        process.finished.connect(self.onFinished)
        process.startDetached(command, args)

    def onFinished(self, exitCode, exitStatus):
        self.pushButton.setEnabled(True)

    [...]

rawDescription: subprocess Popen blocking PyQt GUI

description: Subprocess Popen blocking PyQt GUI


code: hosts = [eval('modulename.' + x) for x in dir(local_variables) if '_ip' in x]

rawDescription: How to extract and then refer to variables defined in a python module?

description: Extract and then refer to variables defined in a python module


rawDescription: Estimating the Size of Binary Data encoded as a B64 String in Python


code:
def writetxt(phrase):
    f = open("file.txt", "a")
    phrase = f.read()
    palabras = phrase.split()
    for word in palabras:
        print (word)
        f.write(word)
    f.close()

rawDescription: Split a phrase into words and write a TXT


code:
for row in c.execute("SELECT DIR_Radius from Tanks"):
    if row[0]>0.0001:
        int1 = math.pi * row[0]
        ...

rawDescription: Is there a way to use a column header in a database as a variable in Python?


code:
for sentence in sentences:
    if all(term not in sentence for term in terms):
        empty.append(sentence)

rawDescription: Filter out sentences in a list that don't contain particular words


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--head',
                    dest='size',
                    const=10,
                    default=80,
                    action='store',
                    nargs='?',
                    type=int,
                    help='Only print the head of the output')
print(parser.parse_args(''.split()))
# output: Namespace(size=80)
print(parser.parse_args('--head'.split()))
# output: Namespace(size=10)
print(parser.parse_args('--head 15'.split()))
# output: Namespace(size=15)

rawDescription: How to make an optional value for argument using argparse?

description: Make an optional value for argument using argparse


code: output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat 2>&1 | grep 'RMS     amplitude:'",stderr= subprocess.STDOUT, shell=True)

rawDescription: How to get one line from a print output in linux?

description: Get one line from a print output in linux


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

s = [{1: 1000000, 2: 1000000, 3: 1000000, 4: 1000000, 5:1000000},
     {1: 1000000, 0: 1000000, 8: 1000000, 3: 1000000, 7:1000000}]

def boxplot(data, x=0):

    sorted_data = np.array(data.items())
    sorted_data = np.sort(sorted_data, 0)
    values = sorted_data[:,0]
    freqs = sorted_data[:,1]
    freqs = np.cumsum(freqs)
    freqs = freqs*1./np.max(freqs)

    #get 25%, 50%, 75% percentiles
    idx = np.searchsorted(freqs, [0.25, 0.5, 0.75])
    p25, p50, p75 = values[idx]
    vmin, vmax = values.min(), values.max()

    ax = plt.gca()
    l,r = -0.2+x, 0.2+x
    #plot boxes
    plt.plot([l,r], [p50, p50], 'k')
    plt.plot([l, r, r, l, l], [p25, p25, p75, p75, p25], 'k')
    plt.plot([x,x], [p75, vmax], 'k')
    plt.plot([x,x], [p25, vmin], 'k')

for i in range(len(s)):
    boxplot(s[i],i)
plt.xlim(-0.5,1.5)
plt.show()

rawDescription: Boxplot dictionaries instead of lists?

description: Boxplot dictionaries instead of lists


code:
cur = db.cursor()
cur.execute(sql)
timestamps = []
for rec in cur:
    timestamps.append(rec[0])

rawDescription: why can't I fetch sql statements in python?

description: Why can't I fetch sql statements in python


code:
n = 5
for s in 'ABCDEF', 'AAAAAA':
    len({s[i:i+n] for i in range(len(s)-n+1)})

rawDescription: Counting the number of different 5 characters substrings inside a string


code:
for i_t in range(0, np.shape(t)[1]):
    ax.clear()
    plt.hold(True)
    #    plot limits
    ax.set_xlim(-(max(q0) + bodies[-1].L), +(max(q0) + bodies[-1].L))
    ax.set_ylim(-(max(q0) + bodies[-1].L), +(max(q0) + bodies[-1].L))
    for i in range(0, N):
        ax.plot(x_matrix[i_t, i], y_matrix[i_t, i], 's', color=colors[0, i])

    plt.pause(0.0001)

rawDescription: animation plot in matplotlib with double for loop

description: Animation plot in matplotlib with double for loop


code:
def initialize_function(num,instruction,emplacement1,emplacement2,current_pipeline):
    function_mapping={
    "LOAD" : LOAD,
    "STORE" : STORE,
    "MOVE" : MOVE_IADD,
    "IADD" : MOVE_IADD,
    "FADD" : FADD
    }
    current_pipeline=function_mapping[instruction](num,emplacement1,emplacement2,current_pipeline)
    return(current_pipeline)

rawDescription: How to cancel the dictionary to initialize ? python3.3

description: Cancel the dictionary to initialize ? python3.3


code:
from django.db import connection

cursor = connection.cursor()
cursor.execute("""select
                      count(*), column_value
                  from
                      tableX
                  where
                      column_label = 'Age'
                  group by
                      column_value
                  having
                      column_value > 30""")
result = cursor.fetchall()

rawDescription: Django Raw Query: Making Count query with group BY clause


code:
def map_failure(ff):
    return {'Test Suite': ff['Test Suite'], 'Test': ff['Test'],
            'Failure': failure, 'Project': 'project'}

mappedFailures = [map_failure(ff) for ff in fixedFailures]

rawDescription: Mapping a list of dictionaries from one type to another


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        items = {"one": ["a","b","c"],
                 "two": ["d","e","f"],
                 "three": ["g","h","i"]}

        self.the_value = tk.StringVar()
        self.the_value.set("a")

        self.menubutton = tk.Menubutton(self, textvariable=self.the_value, indicatoron=True)
        self.topMenu = tk.Menu(self.menubutton, tearoff=False)
        self.menubutton.configure(menu=self.topMenu)

        for key in sorted(items.keys()):
            menu = tk.Menu(self.topMenu)
            self.topMenu.add_cascade(label=key, menu=menu)
            for value in items[key]:
                menu.add_radiobutton(label=value, variable = self.the_value, value=value)

        self.menubutton.pack()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Are There any Tkinter Widgets like OptionMenu That Can be Nested?


code:
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

executable_path = "path_to_webdriver"
os.environ["webdriver.chrome.driver"] = executable_path

chrome_options = Options()
chrome_options.add_extension('path_to_extension')

driver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
driver.quit()

rawDescription: Using Extensions with Selenium (Python)

description: Using Extensions with Selenium (Python)


code:
import itertools

x3 = [next(g) for k, g in itertools.groupby(x2, lambda x:(x.a, x.b))]

rawDescription: Sorted/unique list of object instances from a larger list?


code:
tup_list = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
filter_list = [1,7]
[tup for tup in tup_list if any(i in tup for i in filter_list)]

rawDescription: Filtering list of tuples based on the availability of a member in a list


code:
import pyodbc
conn_str = """\
DRIVER={Microsoft Access Driver (*.mdb)};
DBQ=C:\\Users\\Public\\a2003test.mdb;
"""
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
hyperlink = r'C:\Users\Gord\Desktop\foo.txt'
sql = "UPDATE Table1 SET docLink=? WHERE ID=1"
crsr.execute(sql, ['#'+hyperlink+'#'])
cnxn.commit()
crsr.close()
cnxn.close()

rawDescription: Text inserted into Hyperlink field shows up but does not act as a link


code: [x[::-1] for x in b]

rawDescription: Generic reverse of list items in Python

description: Generic reverse of list items in Python


code:
cursor = conn.cursor("some_unique_name")
cursor.execute("SELECT aid FROM pgbench_accounts")
for record in cursor:
    something(record)

rawDescription: Streaming data from Postgres into Python


code:
import datetime as dt
return dt.datetime(year, month, day, tzinfo=dt.timezone(utc_offset)).timestamp()

rawDescription: Get the timestamp of the start of a day (local time)


code:
import boto

conn = boto.connect_ec2()
reservations = conn.get_all_instances(instance_ids=['i-782cc9fb'])
instance = reservations[0].instances[0]
instance.modify_attribute('groupSet', ['sg-47fb243f'])

rawDescription: How to use aws cli in python or node.js programming language?

description: Use aws cli in python or node.js programming language


code: [{'id':x, 'frame':y, 'length':z} for x,y,z in zip(*old_list)]

rawDescription: How to convert list into a dictionary by python

description: Convert list into a dictionary by python


code:
z = zip(x,y)  #z = [(x[0],y[0]), ...]

smaller = [(xval,yval) for (xval,yval) in z if xval<= 5]  #those with x<=5
larger = [(xval,yval) for (xval,yval) in z if xval>=6]    #those with x>=6

x1,y1 = map(list,zip(*smaller))   #break them apart and make the results lists, not tuples.

x2,y2 = map(list,zip(*larger))

rawDescription: Cutting 1D list into two parts in python


code:
self.buttons = [button1, button2, ..., button18]

def updateButtonImage(self):
    for button in self.buttons:
        button.configure(image=self.newImage)

updateButton = Button(root, text="Change button image", command=self.updateButton)

rawDescription: Python - Configuring multiple buttons at once in Tk


code:
expr = create_index_expression('pointer', 'abc')
clause = create_index_clause([expr])
with cassandra_cf.batch() as b:
    for key, user in cassandra_cf.get_indexed_slices(clause):
        b.remove(key)

rawDescription: pycassa - Remove multiple rows by their secondary index?

description: Pycassa - Remove multiple rows by their secondary index


code: sorted_niwa = sorted(ids_seqs.items(), key = lambda val: int(val[0].split()[2]), reverse=False)

rawDescription: Error in sorting operation on dictionary


code:
from collections import namedtuple
IntradayData = namedtuple('IntradayData',
        ['close', 'high', 'low', 'open', 'volume', 'count'])

response = urllib2.urlopen('https://www.google.com/finance/getprices?q=AAPL')
result=response.read().split('\n')
result = result[15 :] # Your code does this, too. Not sure why.

all_data = []
for i, data in enumerate(x):
    if data == '': continue
    c, h, l, o, v, _ = map(float, data.split(','))
    all_data.append(IntradayData(c, h, l, o, v, i))

rawDescription: From C to Python

description: From C to Python


code:
name='report 112 hits'
namelist = name.split()
print(namelist[0])
# report
print(namelist[1])
# 112
print(namelist[2])
# hits

rawDescription: Read numbers in a string with any number of digits in python


code:
def delete_country(id):
    query_url = oauth['instance_url']+'/services/data/v23.0/sobjects/Country__c/%s' % id + '/'
    headers = {
      'Authorization': 'OAuth '+oauth['access_token']
    }
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    req = urllib2.Request(query_url, None, headers)
    req.get_method = lambda: 'DELETE'  # creates the delete method
    url = urllib2.urlopen(req)  # deletes database item

rawDescription: Cannot get DELETE working with liburl2 with python for REST api


code:
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from scrapy.http import Request
from metacritic.items import MetacriticItem
from string import lowercase

class MetacriticSpider(BaseSpider):
    name = "metacritic"
    allowed_domains = ["metacritic.com"]
    max_id = 5

    def start_requests(self):
        for c in lowercase:
            for i in range(self.max_id):
                yield Request('http://www.metacritic.com/browse/games/title/ps3/{0}?page={1}'.format(c, i),
                              callback=self.parse)

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//div[@class="product_wrap"]/div')
        items = []

        for site in sites:
            titles = site.xpath('a/text()').extract()
            if titles:
                item = MetacriticItem()
                item['title'] = titles[0].strip()
                items.append(item)
        return items

rawDescription: Scrapy code not iterating through pages

description: Scrapy code not iterating through pages


code:
from inspect import getsource

class NumberStore(object):
    def __init__(self, num):
        self.num = num

    def get(self):
        return self.num

    @classmethod
    def print_class_definition(cls):
        return getsource(cls)

rawDescription: How do I return the definition of a class in python?

description: Return the definition of a class in python


code:
import logging.handlers
object_handler = logging.handlers.BufferingHandler(float('inf'))
logging.root.handlers.append(object_handler)
logging.root.level = logging.DEBUG
something = object()
object_handler.buffer
logging.info("something happened", something)
object_handler.buffer
object_handler.buffer[-1].args[0] is something

rawDescription: Python logging: standard approach to log to a live object?


rawDescription: python numpy set elements of list by condition

description: Python numpy set elements of list by condition


code:
a
b
reduce(lambda x,y:x+y,[[a] + [x] for x in b])

rawDescription: How to make a list of n lists shuffled in order (in the most pythonic way possible)?

description: Make a list of n lists shuffled in order (in the most pythonic way possible)


code:
@main.route('/category/<name>')
def view_posts_in_category(name):
    cat = Category.query.filter_by(name=name).first_or_404()
    return render_template('category.html', name=name, posts=cat.posts)

rawDescription: Many-to-one Flask SqlAlchemy rendering

description: Many-to-one Flask SqlAlchemy rendering


rawDescription: Convert Pandas DataFrame to dictionary

description: Convert Pandas DataFrame to dictionary


code:
import glob
import os.path
from bs4 import BeautifulSoup

dir_path = r"C:\My_folder\tmp"
results_dir = r"C:\My_folder\tmp\working"

for file_name in glob.glob(os.path.join(dir_path, "*.html")):
    with open(file_name) as html_file:
        soup = BeautifulSoup(html_file)

    results_file = os.path.splitext(file_name)[0] + '.txt'
    with open(results_file, 'w') as outfile:
        for i in soup.select('font[color="#FF0000"]'):
            print(i.text)
            outfile.write(i.text + '\n')

rawDescription: BeautifulSoup on multiple .html files

description: BeautifulSoup on multiple .html files


code:
def canonicalize(s):
    return min(s[i:]+s[:i] for i in xrange(len(s)))

canonical_strings = {canonicalize(s) for s in my_strings}
for cs in canonical_strings:
    process(cs)

rawDescription: When strings are equivalent up to rotation


code:
marfoo = self.frobnoz.marfoos[0]
marfoo.rotate(CLOCKWISE, degrees=90)
if marfoo.is_cloudy():
    self.purge_clouds(marfoo)

rawDescription: Why Use a=b in Python

description: Why Use a=b in Python


code:
json_object = requests.get('https://api.myjson.com/bins/3ygu6').json()
json_object['asset5'] = 'ON'

rawDescription: Update an online JSON file

description: Update an online JSON file


code:
with open(filename, 'w+') as f:
    f.write(data)

rawDescription: Correct way of loading JSON from file into a Python dictionary


code:
from castro import Castro
c = Castro()
c.start()
# Do something awesome!
c.stop()

rawDescription: Capturing screenshots with python in windows and linux


code:
send_bufr = "PRIVMSG %s :Hello %s\r\n" %(self.channel, sender)
print(send_bufr)
self.sock.send(bytearray(send_bufr, "utf-8"))

rawDescription: Python socket.send() is not sent until socket is closed


code:
import numpy as np
a = np.random.randint(0, 100, (100,128,256))
np.sum(a > 10, axis=0)

rawDescription: python numpy/scipy find count or frequency of a relative variable in multi-dimensional array

description: Python numpy/scipy find count or frequency of a relative variable in multi-dimensional array


code:
class Foo(object):
    """It is long and it has to deal
    with PEP8 code width requirements
    which are 72 characters for
    comments and docstrings and 79
    for actual code.
    """
    class_parm = 12
    pass # after several long, broken down|
       # into several pieces, but in the|
       # end *fit* lines of script, phew|

def make_foo(parm):
    class Foo2(Foo):
        """Foo without indentation problems."""
        class_parm = parm
    return Foo2

rawDescription: Python, squeezed between indentation levels and PEP-8 width limit


code:
import datetime
from django.views.decorators.cache import cache_page

def my_cache(time_func, *args, **kwargs):
    def decorator(func):
        def wraps(*args, **kwargs):
            @cache_page(time_func())
            def inner_func(*args, **kwargs):
                return func(*args, **kwargs)
            return inner_func(*args, **kwargs)
        return wraps
    return decorator

def till_hour():
    now = datetime.datetime.now()
    return (60 - now.minute) * 60 + (60 - now.second)

@my_cache(time_func=till_hour)
def my_view(request):
    ... # view code_here

rawDescription: How do I specify a KEY_FUNCTION for a specific @cache_page

description: Specify a KEY_FUNCTION for a specific @cache_page


code:
my_item = QtGui.QTreeWidgetItem()
my_item.setForeground(0,QtGui.QBrush(QtGui.QColor("#123456")))

rawDescription: PYSide/PyQt Qtreewidget font color

description: PYSide/PyQt Qtreewidget font color


code:
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(bottom=0.1, left=0.2, right=0.8, top=0.9)

par1 = host.twinx()
par2 = host.twinx()
par3 = host.twinx()
par3.axis["right"].set_visible(False)

new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",axes=par2,offset=(60, 0))

host.set_xlabel("Y axis")
host.set_ylabel("X axis 1 on the left")
par1.set_ylabel("X axis 2 on the right")
par2.set_ylabel("X axis 3 on the right")
par3.set_ylabel("X axis 4 on the left")

new_fixed_axis = par3.get_grid_helper().new_fixed_axis
par3.axis["left"] = new_fixed_axis(loc="left",axes=par3,offset=(-60, 0))

p1, = host.plot([1,2,3,4],[1,2,3,4], label="1")
p2, = par1.plot([1,2,3,4],[2,2,2,2], label="2")
p3, = par2.plot([1,2,3,4],[3,3,2,1], label="3")
p4, = par3.plot([1,2,3,4],[1,1,2.5,3.5], label="4")

plt.show()

rawDescription: Stuck with python multiple twinx axis graph using matlibplot


code:
from numba import jit

@jit(nopython=True)
def interpolate_numba(arr, no_data=-32768):
    """return array interpolated along time-axis to fill missing values"""
    result = np.zeros_like(arr, dtype=np.int16)

    for x in range(arr.shape[2]):
        # slice along x axis
        for y in range(arr.shape[1]):
            # slice along y axis
            for z in range(arr.shape[0]):
                value = arr[z,y,x]
                if z == 0:  # don't interpolate first value
                    new_value = value
                elif z == len(arr[:,0,0])-1:  # don't interpolate last value
                    new_value = value

                elif value == no_data:  # interpolate

                    left = arr[z-1,y,x]
                    right = arr[z+1,y,x]
                    # look for valid neighbours
                    if left != no_data and right != no_data:  # left and right are valid
                        new_value = (left + right) / 2

                    elif left == no_data and z == 1:  # boundary condition left
                        new_value = value
                    elif right == no_data and z == len(arr[:,0,0])-2:  # boundary condition right
                        new_value = value

                    elif left == no_data and right != no_data:  # take second neighbour to the left
                        more_left = arr[z-2,y,x]
                        if more_left == no_data:
                            new_value = value
                        else:
                            new_value = (more_left + right) / 2

                    elif left != no_data and right == no_data:  # take second neighbour to the right
                        more_right = arr[z+2,y,x]
                        if more_right == no_data:
                            new_value = value
                        else:
                            new_value = (more_right + left) / 2

                    elif left == no_data and right == no_data:  # take second neighbour on both sides
                        more_left = arr[z-2,y,x]
                        more_right = arr[z+2,y,x]
                        if more_left != no_data and more_right != no_data:
                            new_value = (more_left + more_right) / 2
                        else:
                            new_value = value
                    else:
                        new_value = value
                else:
                    new_value = value
                result[z,y,x] = int(new_value)
    return result

rawDescription: Fast 1D linear np.NaN interpolation over large 3D array


code: setattr(SarProfile, '%sjobtitle%d' % (var, count), x['position']['name'])

rawDescription: writing to model field in django / python

description: Writing to model field in django / python


code:
from igraph import *
g = Graph.Read_Ncol("stuff.csv", directed=True)

rawDescription: Read edges from .csv file to igraph using python


rawDescription: Change a list into a dictionary

description: Change a list into a dictionary


code:
import os
os.path.expanduser(path)

rawDescription: Python Locating the file path

description: Python Locating the file path


code:
name = raw_input('Enter your name: ')
name.isalnum()
name = raw_input('Enter your name: ')
name.isalnum()

rawDescription: applying a filter on a string in python

description: Applying a filter on a string in python


code:
# append to the *end* of the system path.
sys.path.append('~/Applications/yt/yt-x86_64/lib/python2.7/path/to/libs')

rawDescription: added path in PYTHONPATH changes sys.path entires

description: Added path in PYTHONPATH changes sys.path entires


code:
import traceback

def status():
    print(traceback.extract_stack(limit=2)[-2][0])

rawDescription: Catching file name

description: Catching file name


rawDescription: Any way to open a local folder in myComp/explorer programmatically using Python?


code:
# game.py
class Game(object):
    pass

import sys
sys.modules["game"] = Game()

rawDescription: Can modules have properties?

description: Can modules have properties


code:
import numpy as np

with open('output.csv', 'w') as fh:
    for i in range(10):  # loop over features
        row = np.random.random(4000)
        np.savetxt(fh, row.reshape(1, -1), fmt='%.5e', delimiter=',')

rawDescription: Limit decimals numbers when writing to csv in python


rawDescription: django datefield filter

description: Django datefield filter


code:
#!/bin/python

import os
import sys
import csv
import argparse
import requests

URI = 'http://playlist.fish/api'

description = 'Download your Grooveshark playlists as CSV.'
parser = argparse.ArgumentParser(description = description)
parser.add_argument('USER', type=str, help='Grooveshar user name')
args = parser.parse_args()
user = args.USER

with requests.Session() as session:
    # Login as user
    data = {'method': 'login', 'params': {'username': user}}
    response = session.post(URI, json=data).json()
    if not response['success']:
        print('Could not login as user "%s"! (%s)' %
              (user, response['result']))
        sys.exit()

    # Get user playlists
    data = {'method': 'getplaylists'}
    response = session.post(URI, json=data).json()
    if not response['success']:
        print('Could not get "%s" playlists! (%s)' %
              (user, response['result']))
        sys.exit()

    # Save to CSV
    playlists = response['result']
    if not playlists:
        print('No playlists found for user %s!' % user)
        sys.exit()
    path = './pysharkbackup_%s' % user
    if not os.path.exists(path):
        os.makedirs(path)
    for p in playlists:
        plid = p['id']
        name = p['n']
        data = {'method': 'getPlaylistSongs', 'params': {'playlistID': plid}}
        response = session.post(URI, json=data).json()
        if not response['success']:
            print('Could not get "%s" songs! (%s)' %
                  (name, response['result']))
            continue
        playlist = response['result']
        f = csv.writer(open(path + '/%s.csv' % name, 'w'))
        f.writerow(['Artist', 'Album', 'Name'])
        for song in playlist:
            f.writerow([song['Artist'], song['Album'], song['Name']])

rawDescription: How can I make a script to recover my Grooveshark playlists now that the service has been shut down?

description: Make a script to recover my Grooveshark playlists now that the service has been shut down


code:
@expose
def redirect(self, url):
    raise cherrypy.HTTPRedirect(url)

rawDescription: Have CherryPy "submit" button launch external web page


code:
from django.contrib import admin
from booknowapp.models import Customer, ModelClass1, ModelClass2

myModels = [Customer, ModelClass1, ModelClass2]  # iterable list
admin.site.register(myModels)

rawDescription: How to add new class created in models.py to admin.py (django)

description: Add new class created in models.py to admin.py (django)


code:
# Articles tagged with 'tag1'
Articles.select().join(ArticleTags).join(Tags).where(Tags.name == 'tag1')

rawDescription: Peewee ORM get similar entries based on foreign key


code:
env.user = "your_username"
env.key_filename = ["/path/to/keyfile"]

rawDescription: Fabric auto-login in Windows

description: Fabric auto-login in Windows


code:
def foo():
  blahblah

foo1 = decorator_1(foo)
foo2 = decorator_2(decorator(foo))
foo3 = decorator_3(foo)

rawDescription: different decorators for the same function

description: Different decorators for the same function


code:
def displayhook(value):
    if value is None:
        return
    # Set '_' to None to avoid recursion
    builtins._ = None
    text = repr(value)
    try:
        sys.stdout.write(text)
    except UnicodeEncodeError:
        bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
        else:
            text = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value

rawDescription: Where is documentation for the Python standard interpreter single underscore "_" builtin variable?


code:
import base64

def GET(self,r):
    user_data = CC.get_data(query) # holds the content of the blob field.
    data = {'name': 'test',
           'photo': base64.b64encode(user_data)}
    return json.dump(data)

rawDescription: Send MySQL blob content as a json response


code:
hi_obj = hi()
hi_obj.__dict__.keys()

rawDescription: How to get instance variables in Python?

description: Get instance variables in Python


code:
a="hello | my friends| in | stack | over | flow"
a.split('|')[1].strip()

rawDescription: Get substring between two spesific characters in python


code:
def get_date(**kwargs):
    '''Returns now, with the given parts overwritten'''
    dt = datetime.now()
    # optionally, depending on intended use of this function
    kwargs = { k : v for k,v in kwargs.items() if v is not None }
    return dt.replace(**kwargs)

rawDescription: How to overwrite a datetime.now() object

description: Overwrite a datetime.now() object


code: set([(a,b,c) if a<b else (b,a,c) for a,b,c in tups])

rawDescription: eliminating redundant tuples

description: Eliminating redundant tuples


code:
try:
    couch = couchdb.Server() # assuming localhost
    db = couch['existent']
except:
    db = couch.create('somedb')

rawDescription: python-couchdb: How to check if database already exists

description: Python-couchdb: How to check if database already exists


code:
class InlineConnectn(admin.TabularInline):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "book1":
            kwargs["queryset"] = Foo.objects.filter(book1__book_type=1)
        return super(InlineConnectn, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: Django admin - TabularInline - display only a few objects from other model


code:
import csv
import sys

keys = []
values = []

reader = csv.reader(sys.stdin, delimiter="\t")
for row in reader:
    keys.extend(row)
    values.extend(next(reader))

    # skip empty line
    assert next(reader, []) == []

writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerow(keys)
writer.writerow(values)

rawDescription: I've got a funky tab delimited file that I'd like to make less funky


code:
import sys, random
from PyQt4 import QtCore, QtGui

class TabContainer(QtGui.QWidget):
  def __init__(self):
    super(TabContainer, self).__init__()
    self.next_item_is_table = False
    self.initUI()

  def initUI(self):
    self.setGeometry( 150, 150, 650, 350)
    self.tabwidget = QtGui.QTabWidget(self)
    vbox = QtGui.QVBoxLayout()
    vbox.addWidget(self.tabwidget)
    self.setLayout(vbox)
    self.pages = []
    self.add_page()
    self.show()

  def create_page(self, *contents):
    page = QtGui.QWidget()
    vbox = QtGui.QVBoxLayout()
    for c in contents:
        vbox.addWidget(c)

    page.setLayout(vbox)
    return page

  def create_table(self):
    rows, columns = random.randint(2,5), random.randint(1,5)
    table = QtGui.QTableWidget( rows, columns )
    for r in xrange(rows):
        for c in xrange(columns):
            table.setItem( r, c, QtGui.QTableWidgetItem( str( random.randint(0,10) ) ) )
    return table

  def create_list(self):
    list = QtGui.QListWidget()
    columns = random.randint(2,5)
    for c in xrange(columns):
        QtGui.QListWidgetItem( str( random.randint(0,10) ), list )

    return list

  def create_new_page_button(self):
    btn = QtGui.QPushButton('Create a new page!')
    btn.clicked.connect(self.add_page)
    return btn

  def add_page(self):
    if self.next_item_is_table:
        self.pages.append( self.create_page( self.create_table(), self.create_new_page_button() ) )
        self.next_item_is_table = False
    else:
        self.pages.append( self.create_page( self.create_list(), self.create_new_page_button() ) )
        self.next_item_is_table = True

    self.tabwidget.addTab( self.pages[-1] , 'Page %s' % len(self.pages) )
    self.tabwidget.setCurrentIndex( len(self.pages)-1 )

app = QtGui.QApplication(sys.argv)
ex = TabContainer()
sys.exit(app.exec_())

rawDescription: Dynamically change view of tabs in a QTabWidget (PyQt)


code:
{
    '_auth_user_id': 123,
    '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend',
}

rawDescription: I'm using Django user authentication with PHP. Will this cookie based authentication scheme be secure?


code:
results = { "Possible Answer 1":"Game response 1",
    "Possible Answer 2":"Game response 2",
    "Possible Answer 3":"Game response 3" }
if VARIABLE in results:
    print (results[VARIABLE])
# else :
#     default action, if appliable

rawDescription: Can you use multiple elifs for one variable?

description: Use multiple elifs for one variable


code:
import re
regex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')

rawDescription: How can I support * in user-defined search strings in python?

description: Support * in user-defined search strings in python


code:
def activate(self, license=None):
        if self.activate_count != 2 and self.license == license:
            import pdb; pdb.set_trace()
            self.activate_count += 1
            self.save()
            return True
        else:
            return False

rawDescription: Assignment of field in Django model

description: Assignment of field in Django model


code:
event = gtk.gdk.Event(gtk.gdk.FOCUS_CHANGE)
event.window = entry.get_window()  # the gtk.gdk.Window of the widget
event.send_event = True  # this means you sent the event explicitly
event.in_ = False  # False for focus out, True for focus in

rawDescription: pygtk: how to manually emit signal

description: Pygtk: how to manually emit signal


code:
def makeImage (triangle, largura, altura):
    """
    triangle: receives a tuple in the form: x1, y1, x2, y2, x3, y3, R, G, B, A
    largura: image weight
    altura: image height

    returns: numPy array of the triangle composed final image
    """
    back = Image.new('RGBA', (largura,altura), (0,0,0,0))
    poly = Image.new('RGBA', (largura,altura))
    pdraw = ImageDraw.Draw(poly)

    pdraw.polygon([1,2,3,4,5,6], fill=(255,0,0,127))
    back.paste(poly,mask=poly)

    back = back.convert('RGB')
    backArr = asarray(back)
    #back.show()

    return backArr

rawDescription: Convert Matplotlib figure to NumPy array without any borders/frame or axis


code:
import base58
unencoded_string = "BEEFAFEEB"
encoded_string = base58.b58encode(unencoded_string)

rawDescription: Base58Check Python Example

description: Base58Check Python Example


code:
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1

rawDescription: django sort dict after query

description: Django sort dict after query


rawDescription: SQLAlchemy order_by string column with int values


code:
df[['Project_Type','Project Age']].groupby('Project_Type').agg(['min',
                                                            'max',
                                                            'mean',
                                                            'std'])

rawDescription: Working with Pandas Groupby and multiple rows


code:
class DataModel(model):
    time = ...
    value = ...
    label = ...

class TrainDataModel(DataModel):
    pass

class TestDataModel(DataModel):
    pass

rawDescription: Cloning Django models or add a differentiating field in the second model?


rawDescription: Pandas: creating an indexed time series [starting from 100] from returns data


code:
maxlen=max(len(i) for i in a) #get the max length of all tuples
[i+(0,)*(maxlen-len(i)) for i in a] #fill each tuple with extra zeros

rawDescription: Python: Converting list of tuples(variable size) into array like structure with fixed shape


code:
#!/usr/bin/env python

import argparse
import re

# Give help description
parser = argparse.ArgumentParser(description='Merge some data files')
# Add to help description
parser.add_argument('fname', metavar='f', nargs='+',
                    help='Names of files to be merged')
# Parse the input arguments!
args = parser.parse_args()
argdct = vars(args)

topcomment=None
output = {}
# Loop over file names
for name in argdct['fname']:
    with open(name, "r") as infile:
        # Loop over lines in each file
        for line in infile:
            line = str(line)
            # Skip comment lines, except to take note of first one that
            # matches "#A"
            if re.search('^#', line):
                if re.search('^#A', line) != None and topcomment==None:
                    topcomment = line
                continue
            items = line.split()
            # If a line matching this one has been encountered in a previous
            # file, add the column values
            currkey = float(items[0])
            if currkey in output.keys():
                for ii in range(len(output[currkey])):
                    output[currkey][ii] += float(items[ii+1])
            # Otherwise, add a new key to the output and create the columns
            else:
                output[currkey] = list(map(float, items[1:]))

# Print the comment line
print(topcomment, end='')
# Get total number of files for calculating average
nfile = len(argdct['fname'])
# Sort the output keys
skey = sorted(output.keys())
# Loop through sorted keys and print each averaged column to stdout
for key in skey:
    outline = str(int(key))
    for item in output[key]:
        outline += ' ' + str(item/nfile)
    outline += '\n'
    print(outline, end='')

rawDescription: combine/average multiple data files

description: Combine/average multiple data files


code:
attrsToCopy = ['name', 'inventory', 'maxhp', 'thrust', 'ftlspeed']
for attr in attrsToCopy:
    setattr(self, attr, getattr(theshiptype, attr))

rawDescription: More elegant way to copy properties in Python 3


code:
names = list()
a = open(sf, 'r')
for row in a:
    place = row.find(',')
    names.append(row[:place])
print(names)

rawDescription: How to take a specific string from a csv file into a list - python 3.4

description: Take a specific string from a csv file into a list - python 3.4


code:
a = 1
b = 2
int_div  = a // b

rawDescription: Python3 integer division

description: Python3 integer division


code:
import tkinter as tk

def demo(master):
    listbox = tk.Listbox(master)
    listbox.pack(expand=1, fill="both")

    # inserting some items
    listbox.insert("end", "A list item")

    for item in ["one", "two", "three", "four"]:
        listbox.insert("end", item)

    # this changes the background colour of the 2nd item
    listbox.itemconfig(1, {'bg':'red'})

    # this changes the font color of the 4th item
    listbox.itemconfig(3, {'fg': 'blue'})

    # another way to pass the colour
    listbox.itemconfig(2, bg='green')
    listbox.itemconfig(0, foreground="purple")

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

rawDescription: Is it possible to colour a specific item in a Listbox widget?


code:
from tkinter import *;
from tkinter.ttk import *; #Notebook comes from this
from tkinter.messagebox import *;

class Editor:
    def __init__(self):
        self.tk=Tk();
        self.tabs=0;
        self.frame=Frame(self.tk);
        self.nb=Notebook(self.frame);
        self.nb.bind("<ButtonRelease-1>", self.test);
        self.frame.pack();
        for x in range(5):
            self.add_tab();
        self.nb.pack();
        self.tk.mainloop();
    def add_tab(self):
        newTabFrame=Frame(self.nb);
        text=Text(newTabFrame);
        text.pack();
        if self.tabs==0:
            self.nb.add(newTabFrame, text=str(self.tabs), compound=TOP);
        else:
            self.nb.add(newTabFrame, text=str(self.tabs));
        self.tabs+=1;
    def test(self, event=None):
        showinfo("Success", "It works!");
        #Imagine the code for selecting the text widget is here.
        return "break";

if __name__ == '__main__':
    e=Editor();
    try:
        e.tk.destroy();
    except:
        pass;

rawDescription: Event handler for left-click on Notebook tabs in Tkinter


code: query = query % tuple(db.literal(item) for item in args)

rawDescription: MySQLdb format query parameters without executing?


code:
a = '\nThu Apr 04           Finish PTI Video\n                     Weigh In\n                         Eat out\n\nSat Apr 06           Collect NIC\n\nMon Apr 08           Serum uric acid        test\n\n'
b = {}
same_day = ''
for x in a.split('\n'):
    c = x.split('           ')
    if c[0] is '':
        for q in c:
            if q is not '':
                b.update({same_day: b[same_day] + ', ' + q.strip()})
                break
    else:
        same_day = c[0]
        b.update({c[0] : c[1]})

rawDescription: split output after date

description: Split output after date


code:
#get reference to attribute dict
attributes = data["Event"]["Attribute"]
#in the event dictionary, replace it with an empty list
data["Event"]["Attribute"] = []

for attribute in attributes:
    for value in attribute["value"]:
        #for every value in every attribute, copy that attribute
        new_attr = attribute.copy()
        #set the value to that value
        new_attr["value"] = value
        #and append it to the attribute list
        data["Event"]["Attribute"].append(new_attr)

rawDescription: python dictionary/json inception

description: Python dictionary/json inception


code:
from subprocess import Popen, PIPE
p = Popen("./vecdiff.py file1 file2", stdout=PIPE, stderr=PIPE)
output, errput = p.communicate()

rawDescription: Python subprocess: how to retrieve the standard output


code: print(convert(op, NewTemp))

rawDescription: My Program does not return a value?

description: My Program does not return a value


code:
import re
import locale
decimal_point_char = locale.localeconv()['decimal_point']
clean = re.sub(r'[^0-9'+decimal_point_char+r']+', '', str(param[2]))
value = float(clean)

rawDescription: Remove currency symbols and literals from a string with a price universal solution


code:
from distutils import sysconfig
sysconfig.get_python_inc()
sysconfig.get_python_inc(plat_specific=True)

rawDescription: Cross-platform method for finding python include folder


code:
fnmatch('hello.xlsx', '[!~]*.xlsx')
fnmatch('~hello.xlsx', '[!~]*.xlsx')

rawDescription: Using fnmatch to match 2 parts of a file name


code:
for index, linkobj in enumerate(myfiles):
    if "sca" in linkobj.url:
        resp = br.follow_link(text='Download [IMG]',nr=0)
        content = resp.read()
        with open('output%s.txt' % index, 'w') as fo:
           fo.write(content)

rawDescription: How to download files from a web based file server with Python Mechanize

description: Download files from a web based file server with Python Mechanize


code:
txt = None

def onclick(event):
    global txt
    txt = plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)
    fig.canvas.draw()

def offclick(event):
    txt.remove()
    fig.canvas.draw()

fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('button_release_event', offclick)

plt.show()

rawDescription: python matplotlib add and remove text to figure using button events

description: Python matplotlib add and remove text to figure using button events


code:
recording_time = models.DateTimeField(auto_now=True)
previous_value = models.FloatField(null=True, default=None)
previous_recording_time = models.DateTimeField(null=True, default=None)

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    try:
        obj = Observation.objects.get(pk=self.pk)
        # this is the record of this instance before editing
    except Observation.DoesNotExist:  # self.pk==None: this is a new Observation
        pass
    else:  #  this is indeed an update
        self.previous_value = obj.value
        previous_db_recording_time = obj.db_recording_time
    super(Observation, self).save(force_insert=force_insert, force_update=force_update, using=using,
         update_fields=update_fields)

rawDescription: Override model save method to automatically store previous values of updated fields


code: DataFrame(df1.values + df2.values, df1.index, df1.columns)

rawDescription: Adding DataFrames in pandas

description: Adding DataFrames in pandas


code:
import re

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        outfile.write(re.sub('\s\s+', '\n', line))

rawDescription: For each line in a file, replace multiple-whitespace substring of variable length with line break


code:
for col in res:
    tmp_tot = float(col[7])
    tot.append(tmp_tot)

rawDescription: Reading values from csv and drawing bar chart with matplotlib in python


code:
s = inspect.stack()
module_name = inspect.getmodule(s[1][0]).__name__
func_name = s[1][3]
arginfo = inspect.getargvalues(s[1][0])
if len(arginfo.args) > 0 and arginfo.args[0] == "self":
    func_name = "%s.%s" (arginfo.locals["self"].__class__.__name__, func_name)
prefix = '### %s->%s' % (module_name, func_name)

rawDescription: How can I get the name of the class of a bound method from the interpreter stack?

description: Get the name of the class of a bound method from the interpreter stack


code:
def underscore_to_camelcase(value):
    def camelcase():
        yield str.lower
        while True:
            yield str.capitalize

    c = camelcase()
    return "".join(c.next()(x) if x else '_' for x in value.split("_"))

rawDescription: How can I simplify this conversion from underscore to camelcase in Python?

description: Simplify this conversion from underscore to camelcase in Python


code:
import ast
s = "((1, u'Central Plant 1', u'http://egauge.com/'),(2, u'Central Plant 2', u'http://egauge2.com/'))"
ast.literal_eval(s)

rawDescription: How to convert tuple in string to tuple object?

description: Convert tuple in string to tuple object


code:
a = array.array('c')
a.fromstring(s)

rawDescription: Create Python array.array Object from cStringIO Object


code:
def dialog():
    '''function to create dialog window'''
    msgbox = Toplevel() # create an instance of toplevel

    # create widgets with toplevel instance as parent
    Entry(msgbox, textvariable=var).pack()
    Button(msgbox, text='Enter', command=msgbox.destroy).pack()

root = Tk()

var = StringVar()
Button(root, text='Call Dialog Box', command=dialog).pack()
Label(root, textvariable=var).pack()

mainloop()

rawDescription: How to put an Entry option in a Messagebox?

description: Put an Entry option in a Messagebox


code:
r_numberless = re.compile(r"(?:and )?number\(@begin\).*?\/@begin\)")
numberless_xpath = r_numberless.sub("", lv_xpath)
lv_x_levels = count_depth(numberless_xpath)

def count_depth(xpath):
    depth = 0
    max_depth = 0
    for c in xpath:
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1

        if depth > max_depth:
            max_depth = depth

    return max_depth

rawDescription: Counting levels of embedding in string with Python


code:
from decorator import decorator
from Module1 import Class1
from Module2 import Class2

def _my_decorator(func, *args, **kwargs):
    #add decorator code here
    return func(*args, **kwargs)

def my_decorator(f):
    return decorator(_my_decorator, f)

methods_to_decorate = [
    'Class1.method1',
    'Class2.method2',
    ]

for method in methods_to_decorate:
    exec_str = method + '= my_decorator('+method+'.im_func)'
    exec(exec_str)

rawDescription: Can I use aspects in python without changing a method / function's signature?

description: Use aspects in python without changing a method / function's signature


code:
parser = etree.XMLParser(remove_blank_text=True)
root = etree.parse('in.xml', parser)
root.xpath('//pplv:node2/text()', namespaces={'pplv': 'whatever'})
root.write('out.xml', pretty_print=True)

rawDescription: Python, XML and multiple "hierarchical" default namespaces


code:
import argparse

parser=argparse.ArgumentParser()
parser.add_argument('--name',nargs='*',action='store')

print(parser.parse_args('--name try1 3'.split())) #Namespace(name=['try1', '3'])

rawDescription: argparse - Optional argument with list/tuple

description: Argparse - Optional argument with list/tuple


code:
import collections

# build an adjacency list representation of your input
graph = collections.defaultdict(set)
for l in input_list:
    if l:
        first = l[0]
        for element in l:
            graph[first].add(element)
            graph[element].add(first)

# breadth-first search the graph to produce the output
output = []
marked = set() # a set of all nodes whose connected component is known
for node in graph:
    if node not in marked:
        # this node is not in any previously seen connected component
        # run a breadth-first search to determine its connected component
        frontier = set([node])
        connected_component = []
        while frontier:
            marked |= frontier
            connected_component.extend(frontier)

            # find all unmarked nodes directly connected to frontier nodes
            # they will form the new frontier
            new_frontier = set()
            for node in frontier:
                new_frontier |= graph[node] - marked
            frontier = new_frontier
        output.append(tuple(connected_component))

rawDescription: How can i get union of 2D list items when there occurs any intersection (in efficient way)?

description: Get union of 2D list items when there occurs any intersection (in efficient way)


code: cur.execute("""SELECT feed_id FROM feed_master WHERE url_link = '%s'""",(source,))

rawDescription: Python MySQL query gives no results while using Python variables in query


code:
fig = plt.figure(figsize=(20, 2))
ax = fig.add_subplot(111)
ax.plot(x, y)

rawDescription: Matplotlib: make x-axis longer

description: Matplotlib: make x-axis longer


code:
from __future__ import print_function  # to make it work with Python 2, just in case
import time

print ("Hello world", end='\r', flush=True)
time.sleep(1)
print ("New Text     ", end='\r', flush=True)
time.sleep(1)
print ("Last Text    ")

rawDescription: How to clean a specific thing on command line

description: Clean a specific thing on command line


code:
connection = MySQLdb.connect(
    host=config.HOST, user=config.USER,
    passwd=config.PASS, db=config.MYDB, )
with connection as cursor:
    print(cursor)
    # the connection is closed for you automatically
    # when Python leaves the `with-suite`.

rawDescription: MySQL, should I stay connected or connect when needed?


code: [e for e in soup(recursive=False, text=False) if e.span.string == 'Text2']

rawDescription: BeautifulSoup question

description: BeautifulSoup question


code:
import Tkinter

class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.master.minsize(width=256, height=256)
        self.master.config()
        self.pack()

        self.main_frame = Tkinter.Frame()

        self.some_list = [
            'One',
            'Two',
            'Three',
            'Four'
        ]

        self.some_listbox = Tkinter.Listbox(self.main_frame)

        # bind the selection event to a custom function
        # Note the absence of parentheses because it's a callback function
        self.some_listbox.bind('<<ListboxSelect>>', self.listbox_changed)
        self.some_listbox.pack(fill='both', expand=True)
        self.main_frame.pack(fill='both', expand=True)

        # insert our items into the list box
        for i, item in enumerate(self.some_list):
            self.some_listbox.insert(i, item)

        # make a label to show the selected item
        self.some_label = Tkinter.Label(self.main_frame, text="Welcome to SO!")
        self.some_label.pack(side='top')

        # not really necessary, just make things look nice and centered
        self.main_frame.place(in_=self.master, anchor='c', relx=.5, rely=.5)

    def listbox_changed(self, *args, **kwargs):
        selection_index = self.some_listbox.curselection()
        selection_text = self.some_listbox.get(selection_index, selection_index)
        self.some_label.config(text=selection_text)

root = Tkinter.Tk()
app = Application(root)
app.mainloop()

rawDescription: Python Tkinter listbox with MySQLdb

description: Python Tkinter listbox with MySQLdb


code:
item['title'] = article.xpath('.//div[@class="art_title"]/text()').extract()[0]
item['url'] = article.xpath('.//a/@href').extract()[0]

rawDescription: Scrapy - Problems scraping simple website


code: f = open("something", "wb+")

rawDescription: Writing files in Python and carriage return in Windows


code: np.where((conditions ==  a).all(axis=1))[0]

rawDescription: Index of an array from a 2d np.array in Python?


code:
import numpy as np
a = ['Foo', '59.8', 'bar', 'spam']
arr = np.ma.array(a, mask=[True, False, True, True])
arr.compressed().astype(float)
arr[arr.mask].data

rawDescription: converting a list of strings into integers in python, skipping masked terms

description: Converting a list of strings into integers in python, skipping masked terms


code:
from tkinter import *

root = Tk()

root.geometry("200x200")
root.title("Question 2")
root.configure(background="green")

parent = Frame(root)
Label(parent, text = "RED", fg="red", bg="black").pack(fill="x")
Label(parent, text = "WHITE", fg="white", bg="black").pack(fill="x")
Label(parent, text = "BLUE", fg="blue", bg="black").pack(fill="x")
parent.pack(expand=1)  # same as expand=True

root.mainloop()

rawDescription: How to center widgets vertically and horizontally in window with Tkinter?

description: Center widgets vertically and horizontally in window with Tkinter


code:
for i, record in enumerate(qs):
    record.value = i

rawDescription: Update queryset attribute value without losing order on that attribute


code: any(i.x == 'b' for i in mylist)

rawDescription: One-line way to iterate over a list of classes and examine a single attribute


rawDescription: ordering shuffled points that can be joined to form a polygon (in python)

description: Ordering shuffled points that can be joined to form a polygon (in python)


code:
@models_committed.connect_via(app)
def on_models_committed(sender, changes):
    for obj, change in changes:
        if change == 'delete' and hasattr(obj, '__commit_delete__'):
            obj.__commit_delete__()

rawDescription: Execute some code when an SQLAlchemy object's deletion is actually committed


code:
height = int(input("Height of triangle: "))
count = 0

for i in range(height-1):
    print('#' + ' '*count + '#')
    count += 1

print('#'*height)

rawDescription: How to print a triangle using for loops

description: Print a triangle using for loops


code:
def removeSubsumed(L, R):
    return [s for s in L if not any(s >= r for r in R)]

rawDescription: Python Remove if Not Found

description: Python Remove if Not Found


code:
your_list = ['productX', 'deployment-package', '1.2.3.4', None, None, None]
'-'.join(item for item in your_list if item)

rawDescription: String Joining from Iterable containing Strings and ( NoneType / Undefined )


code:
df.dtypes
df.replace('SUPP', 3, inplace=True)
df.dtypes
df = df.convert_objects(convert_numeric=True)
df.dtypes

rawDescription: Replace string by numerical value

description: Replace string by numerical value


code:
import turtle
foo = turtle.Turtle()
bar = turtle.Turtle()

foo.forward(100)
bar.left(90)

rawDescription: is there a way to make a drawing game on python turtle with two turtles at the same time, where they cant touch the lines?

description: Is there a way to make a drawing game on python turtle with two turtles at the same time, where they cant touch the lines


rawDescription: Python Regex best delimiter to use?

description: Python Regex best delimiter to use


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

df = pd.DataFrame(np.random.randint(20, size=20))
cmap = cm.get_cmap('Spectral') # Colour map (there are many others)

fig, ax = plt.subplots(1)
# Now here's the plot. range(len(df)) just makes the x values 1, 2, 3...
# df[0] is then the y values. c sets the colours (same as y values in this
# case). s is the marker size.
ax.scatter(range(len(df)), df[0], c=df[0], s=120, cmap=cmap, edgecolor='None')
plt.show()

rawDescription: How to use colormaps to color plots of Pandas DataFrames

description: Use colormaps to color plots of Pandas DataFrames


code: data = [map(float, line.split()) for line in lines]

rawDescription: Smart way to read big input file with multiple unmarked variables (assorted in columns) in python


code:
import requests

from lxml import html

root_url = 'http://lawyerlist.com.au/'

def get_page_urls():
  for no in ('1','2'):
    page = requests.get('http://lawyerlist.com.au/lawyers.aspx?city=Sydney&Page=' + no)
    tree = html.fromstring(page.text)
    yield tree.xpath('//td/a/@href')

for page_of_urls in get_page_urls():
  for li in page_of_urls:
    pag=requests.get(root_url + li)
    doc = html.fromstring(pag.text)
    for name in doc.xpath('//tr/td/h1/text()'):
      print(name)

rawDescription: loop not going to next page

description: Loop not going to next page


code:
from websocket import create_connection
ws = create_connection("wss://coinsecure.in/websocket")
ws.send('{"method": "recentbuytrades"}')

while True:
  result =  ws.recv()
  print ("Received '%s'" % result)

ws.close()

rawDescription: Accessing API via WebSockets using Python


code:
def provera():
    while True:
        komanda = input("\n>> ")
        if komanda in ("1", "2"):
            break
        print("\nUneli ste pogrešnu komandu.\n")
    return komanda

def unos():
    while True:
        komanda = provera()
        if komanda == "1":
            unosNam()
        elif komanda == "2":
            unosKat()
        else:
            break

rawDescription: how to return variable in another function

description: Return variable in another function


rawDescription: numpy: filling a subset of array

description: Numpy: filling a subset of array


code:
"""
Create Bandwidth Pool

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Bandwidth_Version1_Allotment/createObject/

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer
# For nice debug output:
from pprint import pprint as pp

API_USERNAME = 'set me'
API_KEY = 'set me'

# Set the needed values to create a new item
accountId = 307600

# The values for bandwidthAllotmentTypeId are: (1) and (2)
# where: (1) means this allotment is marked as a virtual private rack or
#        (2) bandwidth pooling
bandwidthAllotmentTypeId = 2

# To get locationGroupId, execute: SoftLayer_Location_Group::getAllObjects
locationGroupId = 1
newBandwithPoolName = 'testPool02'

# Create an object template to create the item.
objectTemplate = {
    'accountId': accountId,
    'bandwidthAllotmentTypeId': bandwidthAllotmentTypeId,
    'locationGroupId': locationGroupId,
    'name': newBandwithPoolName
}

# Creates a new connection to the API service.
client = SoftLayer.Client(
    username=API_USERNAME,
    api_key=API_KEY
)

try:
    result = client['SoftLayer_Network_Bandwidth_Version1_Allotment'].createObject(objectTemplate)
    pp(result)

except SoftLayer.SoftLayerAPIError as e:
    pp('Failed ... Unable to create a new Bandwidth Pool  faultCode=%s, faultString=%s'
        % (e.faultCode, e.faultString))

rawDescription: Creating a Bandwidth Pool in Python

description: Creating a Bandwidth Pool in Python


code:
import os, sys, time

name = "logfile"
current = open(name, "r")
curino = os.fstat(current.fileno()).st_ino
while True:
    while True:
        buf = current.read(1024)
        if buf == "":
            break
        sys.stdout.write(buf)
    try:
        if os.stat(name).st_ino != curino:
            new = open(name, "r")
            current.close()
            current = new
            curino = os.fstat(current.fileno()).st_ino
            continue
    except IOError:
        pass
    time.sleep(1)

rawDescription: python: read file continuously, even after it has been logrotated

description: Python: read file continuously, even after it has been logrotated


code:
all_cookies[0]['name']  # returns 'JSESSIONID'
all_cookies[0]['value']  # returns '8430c050201161b5404d52194a5445561a02'

rawDescription: python selenium, retrieving value of cookie and inserting into a GET

description: Python selenium, retrieving value of cookie and inserting into a GET


code:
# using defaultdict
lookup = collections.defaultdict(list)
for item in items:
    lookup[key(item)].append(item)

# or, using plain dict
lookup = {}
for item in items:
    lookup.setdefault(key(item), []).append(item)

rawDescription: Grouping items by a key?

description: Grouping items by a key


rawDescription: Passing argument with *list doesn't work with execl


code:
class ListDictSerializer(serializers.ListSerializer):
    def get_field_name(self):
        if not hasattr(self.Meta, 'field_name'):
            raise ValueError('ListDictSerializer requires defining Meta.field_name overriding get_field_name()')
        return self.Meta.field_name

    def to_internal_value(self, data):
        field_name = self.get_field_name()
        return super(ListDictSerializer, self).to_internal_value(data[field_name])

    def to_representation(self, data):
        field_name = self.get_field_name()
        return ReturnDict({
                field_name: super(ListDictSerializer, self).to_representation(data)
            }, serializer=self
        )

    @property
    def data(self):
       # skip over the ListSerializer to get the real data without the
        # ReturnList
        ret = super(serializers.ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

class PersonListSerializer(ListDictSerializer):
    class Meta:
        field_name = 'userList'

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        list_serializer_class = PersonListSerializer
        model = Person
        fields = ('username', 'lat', 'lon')

    username = serializers.CharField(source='name')
    lat = serializers.SerializerMethodField(method_name='get_latitude')
    lon = serializers.SerializerMethodField(method_name='get_longitude')

    def get_latitude(self, instance):
        return instance.location.coords[1]

    def get_longitude(self, instance):
        return instance.location.coords[0]

    def to_internal_value(self, data):
        return ReturnDict({
            'name': data.get('username'),
            'location': Point(data['lat'], data['lon']),
        }, serializer=self)

rawDescription: Django Custom Deserialization

description: Django Custom Deserialization


code: df = pd.get_dummies(df, columns=['type'])

rawDescription: Pandas: Get Dummies

description: Pandas: Get Dummies


code:
import ctypes
b = ctypes.create_string_buffer(500)
b[:6] = 'foobar'
ctypes.cast(ctypes.byref(b, 4), ctypes.POINTER(ctypes.c_char))
_.contents

rawDescription: Ctypes Offset Into A Buffer

description: Ctypes Offset Into A Buffer


code:
active = False
previous = None
with open(filename, 'r') as f:
    for line in f:
        prev = previous #this is the previous line now
        previous = line
        if active: #active contains previous line ...
           do_something_with_line_after_some_string(prev,line) #terrible function name but you get the idea
        elif line.find("some string") != -1:
           active = line
           continue
        active = False

rawDescription: Read next and previous lines while reading file line-by-line


code:
from time import time
prevState = (False,time())
while not self.done():
    current = time()
    if self._io_left_nav.button0 and (current-prevState[1])*1000>2: #For example, 2 ms
        if self._io_left_nav.button0 != prevState[0]:
            print("repeats")
        prevState = (self._io_left_nav.button0,time())

rawDescription: How to check the state of a robot button using python?

description: Check the state of a robot button using python


code:
class mylist(object):
    def __init__(self, n, a0, a1, eps=1e-8):
        self._n = n
        self._a0 = a0
        self._a1 = a1
        self._eps = eps

    def __contains__(self, x):
        y = float(x - self._a0) / self._a1
        return 0 <= int(y) < self._n and abs(y - int(y)) < self._eps

    def __getitem__(self, i):
        if 0 <= i < self._n:
            return self._a0 + i * self._a1
        raise IndexError

    def __iter__(self):
        current = self._a0
        for i in xrange(self._n):
             yield current
             current += self._a1

    def __len__(self):
        return self._n

rawDescription: Arithmetic Progression in Python without storing all the values


code:
allranges = (range(1, lim+1) for lim in inputs)
for prod in itertools.product(*allranges):
    print(prod)

rawDescription: Generate list by its upper bounds

description: Generate list by its upper bounds


rawDescription: python request param

description: Python request param


code:
class SystemTrayIcon(QtGui.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        menu = QtGui.QMenu(parent)
        changeicon = menu.addAction("Update")
        exitAction = menu.addAction("Exit")
        self.setContextMenu(menu)
        exitAction.triggered.connect(QtGui.qApp.quit)
        changeicon.triggered.connect(self.updateIcon)
        self.updateIcon()

    def updateIcon(self):
        try:
            timer = QtCore.QTimer()
            timer.timeout.connect(self.updateIcon)
            timer.start(5000)
            resultats = serial_ports()
            icone = "red.ico"
            for resultat in resultats:
                if "COM3" in resultat:
                    icone = "green.ico"
                    break

            self.setIcon(QtGui.QIcon(icone))

        finally:
            QtCore.QTimer.singleShot(5000,self.updateIcon)

rawDescription: threading for tray icon application

description: Threading for tray icon application


code:
import pytz

entered_at = request.session['entered_at']
entered_at = datetime.strptime(entered_at, "%m-%d-%Y")
day_start = entered_at.replace(hour=00, minute=00)
day_end = entered_at.replace(hour=23, minute=59)

timezone = pytz.timezone("America/Los_Angeles")
day_start = timezone.localize(day_start)
day_end = timezone.localize(day_end)

entries = Entry.objects.filter(customer=customer,
                               entered_at__lt=day_end,
                               entered_at__gte=day_start)

rawDescription: how to get records for a day relative to timezone in django

description: Get records for a day relative to timezone in django


code:
while i < 360:
    forward(3)
    left(3)
    i+=3

rawDescription: Draw faster circles with Python turtle

description: Draw faster circles with Python turtle


code:
class Game(threading.Thread):
    def update(self):
        pygame.display.update()
        self.screen.fill(self.fillcolour)

    def setup(self):
        """Placeholder for setup"""
        pass

    def frame(self):
        """Placeholder for frame"""
        pass

    def handleEvent(self, event):
        """Placeholder for input handling"""
        pass

    def handleInputs(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.quit()
            self.handleEvent(event)

    def run(self):
        self.setup()

        while True:
            if self.FRAMERATE:
                self.clock.tick(self.FRAMERATE)

            self.frame()
            self.update()
            self.handleInputs()

rawDescription: Placeholder class methods Python 3

description: Placeholder class methods Python 3


code:
def repaintAll(self):
    """ Refresh the paint on the entire tree """
    region = self.tree.childrenRegion()
    self.tree.setDirtyRegion(region)

rawDescription: Qt: When nothing seems to update or repaint a tree


code: sortedlist = [x[1] for x in sorted(zip(Numbers, Fruits))]

rawDescription: Python: Combine then sort list

description: Python: Combine then sort list


code:
from collections import defaultdict
dict1 = {1:'a',2:'b',3:'c'}
dict2 = {1:'hello', 4:'four', 5:'five'}
my_dict = defaultdict(list)
for k in dict1:
   my_dict[k].append(dict1[k])
for k in dict2:
   my_dict[k].append(dict2[k])
my_dict[1]

rawDescription: insert or update keys in a python dictionary

description: Insert or update keys in a python dictionary


code:
meta = {u'CODE': u'N03', u'FABRIC': u'Jersey', u'Colour mix': u'{MGY: {1: 85, 2: 15}}', u'WEIGHT G': 165, u'Main': u'3:100', u'WEIGHT OZ': 4}
import json
str = json.dumps(meta)
str
meta2 = json.loads(str)
meta == meta2

rawDescription: converting python string to dictionary

description: Converting python string to dictionary


code:
# Retrieve tasks
# Reference: http://docs.celeryproject.org/en/latest/reference/celery.events.state.html
query = celery.events.state.tasks_by_type(your_task_name)

# Kill tasks
# Reference: http://docs.celeryproject.org/en/latest/userguide/workers.html#revoking-tasks
for uuid, task in query:
    celery.control.revoke(uuid, terminate=True)

rawDescription: How to inspect and cancel Celery tasks by task name

description: Inspect and cancel Celery tasks by task name


rawDescription: Binning pandas data by top N percent

description: Binning pandas data by top N percent


code:
for key in yourdict:
    if 'yes' in yourdict[key]:
        print(yourdict[key]['yes'])

rawDescription: Query items in nested dictionaries with wildcards


code:
def getPath(self, target):

    stack = []

    def _getPath(head):
        nonlocal stack
        nonlocal target
        if head.value == target:
            stack.append(head)
            return True
        for child in (head.left, head.right):
            if child is not None:
                if  _getPath(child):
                    stack.append(head)
                    return True
        return False

    _getPath(self.root)
    return reversed(stack)

rawDescription: Recursively obtaining path to node in binary tree


code:
import re
pattern = r"\t(\w+) -- (\w+)"
s = '       test1 -- test2'
a, b = re.search(pattern, s).groups()
a
b

rawDescription: Retrieve variables Regex Python

description: Retrieve variables Regex Python


code: a = csv.writer(fp, quoting=csv.QUOTE_ALL)

rawDescription: Python CSV reader/writer handling quotes: How can I wrap row fields in quotes? (Getting triple quotes as output)


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

fig,ax=plt.subplots(2,1)

x=np.linspace(0,np.pi*2,50)

ax[0].plot(x,np.sin(x),'b-')
ax[1].plot(x,np.sin(x),'b-')

rect=mpatches.Rectangle([0.35,0.1], 0.1, 0.8,
         ec='k', fc='g', alpha=0.5, clip_on=False, transform=fig.transFigure)
ax[1].add_patch(rect)

fig.savefig('figure.png')

rawDescription: How to add shading through all subplot

description: Add shading through all subplot


rawDescription: python: computing statistics on subset of an image

description: Python: computing statistics on subset of an image


code:
result = [[compute_stat(data[row], data[col]) for col in labels]
          for row in labels]

rawDescription: building a pairwise matrix in scipy/numpy in Python from dictionaries

description: Building a pairwise matrix in scipy/numpy in Python from dictionaries


code:
persons = []
...
for line in new_contents:
    words = line.split()
    persons.append(Person(...))

rawDescription: How do I append to a new object?

description: Append to a new object


code:
import requests, bs4

# request the content of the feed an create a BeautifulSoup object from its content
response = requests.get('http://rss.slashdot.org/Slashdot/slashdot')
responsesoup = bs4.BeautifulSoup(response.text)

linksoups = []
linktexts = []
linkimageurls = []

# iterate over all <link>…</link> tags and fill three lists: one with the soups of the
# linked pages, one with all their visible text and one with the urls of all embedded
# images
for link in responsesoup.find_all('link'):
    url = link.text
    linkresponse = requests.get(url) # add support for relative urls with urlparse
    soup = bs4.BeautifulSoup(linkresponse.text)
    linksoups.append(soup)

    linktexts.append(soup.find('body').text)
    # Append all text between tags inside of the body tag to the second list

    images = soup.find_all('img')
    imageurls = []
    # get the src attribute of each <img> tag and append it to imageurls
    for image in images:
        imageurls.append(image['src'])
    linkimageurls.append(imageurls)

# now somehow merge the retrieved information.

rawDescription: How to read website content in python

description: Read website content in python


code:
#!/usr/bin/python
import subprocess, os

def rename_file():
    for f in os.listdir(os.getcwd()):
        if '-' in f and f.endswith('.csv'):
            os.rename(f,f.replace('-','_'))

file = open('links20151111.txt','r')
for url in file:
        print ('[+] downloadin ' + url.strip())
        subprocess.call(['wget', '--content-disposition', url.strip()])
        rename_file()

rawDescription: Automatically changing name of downloaded files using Python


code:
iterable1 = [0,1,2,3,4]
iterable2 = ['a','b','c']
import itertools as it
list(x+y for x,y in it.product(it.combinations(iterable1, 2), it.combinations(iterable2, 1)))

rawDescription: combining n elements of iterable1 with m elements of iterable2

description: Combining n elements of iterable1 with m elements of iterable2


code: mystring.replace (" ", "_")

rawDescription: How do I replace whitespaces with underscore and vice versa?

description: Replace whitespaces with underscore and vice versa