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

x = np.random.randint(2004,2017,500)
y =np.clip(np.random.normal(13,7,500),0,24)

plt.scatter(x,y)
plt.xticks(range(2004,2017,3),[str(i) for i in range(2004,2017,3)],rotation=45)
plt.yticks(range(0,24,3),[str(i)+':00' for i in range(0,24,3)])

plt.xlim(2002,2019)
plt.ylim(-3,28)
plt.show()

rawDescription: Add padding to time axis in matplotlib

description: Add padding to time axis in matplotlib


code:
from itertools import product
X = {1,2}
Y = {'a','b'}
[dict(zip(X,y)) for y in product(Y,repeat=len(X))]

rawDescription: A list of all functions from X to Y in Python


code:
def command_output(cmd):
    """ Capture a command's standard output."""
    import subprocess;
    return subprocess.Popen(cmd.split(), stdout=subprocess.PIPE).communicate()[0];

result = command_output('ls -al');

rawDescription: How do I integrate existing scripts into Django?

description: Integrate existing scripts into Django


code:
x <- 'ABCDE'
grepl('^AB', x) # starts with AB?
grepl('DE$', x) # ends with DE?
substr(x, 1, 2) == 'AB'
substr('ABCDE', nchar(x)-1, nchar(x)) == 'DE'

rawDescription: Does R have function startswith or endswith like python?


code:
text1 = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integereu lacus accumsan arcu fermentum euismod. Donec pulvinar porttitortellus. Aliquam venenatis. Donec facilisis pharetra tortor. In necmauris eget magna consequat convallis. Nam sed sem vitae odiopellentesque interdum. Sed consequat viverra nisl. Suspendisse arcumetus, blandit quis, rhoncus ac, pharetra eget, velit. Maurisurna. Morbi nonummy molestie orci. Praesent nisi elit, fringilla ac,suscipit non, tristique vel, mauris. Curabitur vel lorem id nisl portaadipiscing. Suspendisse eu lectus. In nunc. Duis vulputate tristiqueenim. Donec quis lectus a justo imperdiet tempus."""

text1_lines = text1.splitlines()

text2 = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integereu lacus accumsan arcu fermentum euismod. Donec pulvinar porttitortellus. Aliquam venenatis. Donec facilisis pharetra tortor. In necmauris eget magna consequat convallis. Nam sed sem vitae odiopellentesque interdum. Sed consequat viverra nisl. Suspendisse arcumetus, blandit quis, rhoncus ac, pharetra eget, velit. Maurisurna. Morbi nonummy molestie orci. Praesent nisi elit, fringilla ac,suscipit non, tristique vel, mauris. Curabitur vel lorem id nisl portaadipiscing. Suspendisse eu lectus. In nunc. Duis vulputate tristiqueenim. Donec quis lectus a justo imperdiet tempus."""

text2_lines = text2.splitlines()

rawDescription: ImportError :No module named difflib_data


code:
for key, value in dict2.iteritems():
    dict1.setdefault(key, []).extend(value)

rawDescription: update one dictionary with another by adding values rather then replacing it

description: Update one dictionary with another by adding values rather then replacing it


code:
mytuple = (10,10)
mylist = []
for i in range(mytuple[0], -1, -1):
    mylist.append((i, mytuple[1]))
print(mylist)

rawDescription: Continuously subtracting- Python 3.X

description: Continuously subtracting- Python 3.X


code:
from django.db.models import F
Order.objects.filter(received__lt=F('ordered'))

rawDescription: Django filter a queryset with field value lookup


code:
def select(columns=None, whereclause=None, from_obj=[], **kwargs):
    """Returns a ``SELECT`` clause element.
    (... long docstring ...)
    """
    return Select(columns, whereclause=whereclause, from_obj=from_obj, **kwargs)

rawDescription: SQLAlchemy sqlalchemy.sql.expression.select vs. sqlalchemy.sql.expression.Select


code:
import lxml.etree
tree = lxml.etree.XML("<root><a id='1'/><b id='2'/></root>")
tree.xpath("*[@id=1]")
lxml.etree.tostring(tree.xpath("*[@id=1]")[0])

rawDescription: Prototype for python?

description: Prototype for python


code:
files = ['the', 'files', 'here']
output = '/output/file/here'

for file in files:
    with open(file, 'r') as input_file:
        with open(output, 'a') as output_file:
            output_file.write(input_file.read())

rawDescription: Initialize an empty csv in python?

description: Initialize an empty csv in python


code:
# pick a font you have and set its size
myfont = pg.font.SysFont("Comic Sans MS", 30)
# apply it to text on a label
label = myfont.render("Python and Pygame are Fun!", 1, yellow)
# put the label object on the screen at point x=100, y=100
screen.blit(label, (100, 100))

rawDescription: Writing text in pygame

description: Writing text in pygame


code:
def fake_light(image, tilesize=50):
    WIDTH, HEIGHT = i.size
    for x in xrange(0, WIDTH, tilesize):
        for y in xrange(0, HEIGHT, tilesize):
            br = int(255 * (1 - x / float(WIDTH) * y /float(HEIGHT)))
            tile = Image.new("RGBA", (tilesize, tilesize), (255,255,255,128))
            image.paste((br,br,br), (x, y, x + tilesize, y + tilesize), mask=tile)

rawDescription: adding lighting effects to an image in python

description: Adding lighting effects to an image in python


code:
ax = x.plot(kind='bar', legend=False)
patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='best')

rawDescription: Pandas bar plot with specific colors and legend location?


code:
import numpy as np
a = np.array([[np.nan, 0], [1, 2]])
a
a = np.nan_to_num(a)
a

rawDescription: Python - Force nan values to get a certain value


code:
exp = 3
range(exp)

rawDescription: How many times this function is being executed


code:
import operator

method_name = '__eq__'
desired_length = 1

func = getattr(operator, method_name)
n_ints = len(re.findall('\d+', 'password1'))
if func(n_ints, desired_length):
   print('Yeah Buddy!')

rawDescription: How to perform __eq__, __gt__ etc on int object in Python?

description: Perform __eq__, __gt__ etc on int object in Python


code:
import subprocess

answer = subprocess.check_output('bash TestingCode', shell=True)
answer = answer.rstrip()

rawDescription: Call shell script from python code without any return value (0) or new lines


code:
# help functions
def valid_text(start, end):
    if not start or not end:
        return False
    if start.get_line_offset() > end.get_line_offset():
        (start, end) = (end, start) # swap
    text = doc.get_text(start, end, False)
    for char in text:
        if not re.match("\w", char):
            return False
    return True
def increment(index, incr):
    newindex = index.copy()
    newindex.set_line_offset(index.get_line_offset() + incr)
    return newindex
def find_word_bound(index, step):
    condition = lambda x: not index.get_line_offset() == 0 if step < 0 else lambda x: not x.ends_line()
    while condition(index):
        newindex = increment(index, step)
        # newindex contains word?
        if not valid_text(newindex, index):
            break
        # save new index
        index = newindex
    return index
# get vars
cursor = doc.get_iter_at_mark(doc.get_insert())
start = find_word_bound(cursor, -1)
end = find_word_bound(cursor, +1)
word = doc.get_text(start, end, False)

rawDescription: How to get the word below cursor and update it in Python Gedit plugin

description: Get the word below cursor and update it in Python Gedit plugin


code:
def doOpenFile(*args):
    for fn in args:
        flist.open(fn)

# The command below is a hook in aquatk that is called whenever the app
# receives a file open event. The callback can have multiple arguments,
# one for every file that should be opened.
root.createcommand("::tk::mac::OpenDocument", doOpenFile)

rawDescription: Getting the name of document that used to launch the application bundle on OS X


rawDescription: Searching a MySQL Database on ClearDB using Python script


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

x = np.arange(0,np.pi*3,.1)
y = np.sin(x)

fig = plt.figure()
plt.plot(x,y)

imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='svg')
imgdata.seek(0)  # rewind the data

svg_dta = imgdata.buf  # this is svg data

file('test.htm', 'w').write(svg_dta)  # test it

rawDescription: Matplotlib svg as string and not a file

description: Matplotlib svg as string and not a file


code:
import json

class Amazon():

    def parse(self, inpath, outpath):
        g = open(inpath, 'r')
        with open(outpath, 'w') as fout:
            for l in g:
                fout.write(json.dumps(eval(l)))

amazon = Amazon()
amazon.parse("original.json", "cleaned.json")

rawDescription: how to clean a JSON file and store it to another file in Python

description: Clean a JSON file and store it to another file in Python


code:
import pytz
import datetime as dt

now=dt.datetime(year=2011, month=7, day=7)
utc=pytz.utc
pacific=pytz.timezone('US/Pacific')
now_pacific=pacific.localize(now)
now_utc=now_pacific.astimezone(utc)

print(repr(now_pacific))
# datetime.datetime(2011, 7, 7, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
print(repr(now_utc))
# datetime.datetime(2011, 7, 7, 7, 0, tzinfo=<UTC>)

rawDescription: python datetime.datetime not returning correct timezone info with daylight savings time

description: Python datetime.datetime not returning correct timezone info with daylight savings time


code:
class Test:
    def __init__(self, t):
        self.t = t
    def __repr__(self):
        return repr(self.t)
    def __hash__(self):
        return hash(self.t)
    def __eq__(self, other):
        return isinstance(other, Test) and self.t == other.t

rawDescription: Comparison of hashable objects

description: Comparison of hashable objects


code:
import datetime

s = "20120808111051"
parsed_datetime = datetime.datetime.strptime(s, "%Y%m%d%H%M%S")

rawDescription: Convert string into date time in python

description: Convert string into date time in python


code: baby_grid = [i for i, j in grid if j.tag == "Baby_Bear"][0]

rawDescription: Index of a list item

description: Index of a list item


code:
import pandas as pd
source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'],
                  'City' : ['New-York1', 'New-York', 'Sankt-Petersburg', 'New-York']})

#trim column value selecting first two symbols
def s_trim(x):
    return x.str[:2]

#make new column from two selecting first two symbols from each
def s_trim_concat(x,y):
    return '%s-%s' % (x[:2],y[:2])

features = [
    ('trim',['Country'],s_trim),
    ('trim1',['Country','City'],s_trim_concat),
    ('trim2',['City','Country'],s_trim_concat)
    ]

for feature_name, columns, func in features:
    source[feature_name] = source[columns].apply(
        func if len(columns) == 1
        else lambda x: func(x[0],x[1]), axis=1)
print(source)

rawDescription: Easiest feature mapper in python

description: Easiest feature mapper in python


code:
import base64

ws_client.write_message({
    "img": base64.b64encode(img_data),
    "desc": img_description,
})

rawDescription: How to transfer .png or .jpg file over websocket in Tornado

description: Transfer .png or .jpg file over websocket in Tornado


code: {{ mymodel.status.status }}

rawDescription: How to use function returnig dictionary in django template?

description: Use function returnig dictionary in django template


code: avg_img = Image.new('L', img.size, 'black')

rawDescription: Python Image Library: image saved after pixel manipulation is always white


code:
import re

text = 'abc'
# This would be your key in the dict
rx = re.compile('a(\w)c')
# This would be the value for the key (the replacement string, eg: `\1\1\1`)
res = rx.match(text).expand(r'\1\1\1')
# bbb

rawDescription: re.sub repl function returning \1 does not replace the group

description: Re.sub repl function returning \1 does not replace the group


code:
import turtle

# Defining shapes
def polySquare(t, x, y, length):
    t.goto(x, y)
    t.begin_poly()
    for count in range(4):
        t.forward(length)
        t.left(90)
    t.end_poly()
    return t.get_poly()

def polyRectangle(t, x, y, length1, length2):
    t.goto(x, y)
    t.begin_poly()
    for count in range(2):
        t.forward(length1)
        t.left(90)
        t.forward(length2)
        t.left(90)
    t.end_poly()
    return t.get_poly()

def tankCursor():
    """
    Create the tank cursor.
    """
    temporary = turtle.Turtle()
    temporary.hideturtle()
    temporary.penup()

    screen = turtle.getscreen()
    delay = screen.delay()
    screen.delay(0)

    tank = turtle.Shape("compound")
    tire1 = polyRectangle(temporary, -65, -75, 30, 75)  # Tire #1
    tank.addcomponent(tire1, "gray", "black")
    tire2 = polyRectangle(temporary, 35, -75, 30, 75)  # Tire #2
    tank.addcomponent(tire2, "gray", "black")
    tire3 = polyRectangle(temporary, 35, 0, 30, 75)  # Tire #3
    tank.addcomponent(tire3, "gray", "black")
    tire4 = polyRectangle(temporary, -65, 0, 30, 75)  # Tire #4
    tank.addcomponent(tire4, "gray", "black")
    bodyTank = polyRectangle(temporary, -55, -65, 110, 130)
    tank.addcomponent(bodyTank, "black", "gray")
    gunTank = polyRectangle(temporary, -10, 25, 20, 100)   # Gun
    tank.addcomponent(gunTank, "black", "gray")
    exhaustTank = polyRectangle(temporary, -25, -75, 10, 20)
    tank.addcomponent(exhaustTank, "black", "gray")
    turretTank = polySquare(temporary, -25, -25, 50)  # Turret
    tank.addcomponent(turretTank, "red", "gray")
    turtle.addshape("tank", shape=tank)

    del temporary
    screen.delay(delay)

tankCursor()  # creates and registers the "tank" cursor shape
turtle.shape("tank")
turtle.up()  # get rid of the ink

# Movement of tank
screen = turtle.Screen()
screen.onkeypress(lambda : turtle.right(90), "Right")
screen.onkeypress(lambda : turtle.left(90), "Left")
screen.onkeypress(lambda : turtle.forward(40), "Up")
screen.onkeypress(lambda : turtle.backward(40), "Down")

turtle.listen()

turtle.mainloop()

rawDescription: Logic error in python turtle

description: Logic error in python turtle


code:
def appending(appending_list = []):
    print("Please type EOF when you want to stop!")
    while True:
        c = input("Please enter EOF to stop adding. Please enter a choice: ")
        if(c=="EOF"):
            break
        else:
            appending_list.append(c)
    print("You have inserted {} choices".format(len(appending_list)))
    print("Please verify them below: ")
    for x in range(0, len(appending_list)):
        print(appending_list[x])
    return appending_list

def removing(removing_list = []):
    print("Following are choices: ")
    r = input("What do you want to remove? ")
    removing_list.remove(r)
    print("{} successfully removed!".format(r))
    return removing_list

print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
    confirm = input("Is your list complete?[Y/N]")
    if(confirm == "Y"):
        print("Yaay! Choices creation complete."
              "{} choices have been added successfully".format(len(choosing_list)))
        list_incomplete = False
    elif(confirm == "N"):
        action = input("What do you want to do? [Append/Delete]")
        if(action == "Append"):
             choosing_list = appending(choosing_list)
        elif(action == "Delete"):
            choosing_list = removing(choosing_list)

rawDescription: Return to main fuction in python

description: Return to main fuction in python


code:
...
unittest.main(testRunner=runner, exit=False)
...

rawDescription: Execution of commands after unittest.main()


code:
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np

datatype = 'grid'

npts = 900
xs = uniform(-2, 2, npts)
ys = uniform(-2, 2, npts)

# define output grid.
xt = np.linspace(-2.1, 2.1, 2506)
yt = np.linspace(-2.1, 2.1, 2506)

#Input is a series of 900 points
if datatype is 'points':
    values = xs*np.exp(-xs**2 - ys**2)
    # grid the data.
    Z = griddata(xs, ys, values, xt, yt, interp='nn')

#Input is a 900 x 900 grid of x,y,z points
elif datatype is 'grid':

    X, Y = np.meshgrid(xs,ys, indexing='ij')
    values = 2 - 2 * np.cos(X)*np.cos(Y) - np.cos(X - 2*Y)

    # grid the data.
    Z = griddata(X.ravel(), Y.ravel(), values.ravel(), xt, yt, interp='nn')

# contour the gridded data, plotting dots at the nonuniform data points.
CS = plt.contour(xt, yt, Z, 15, linewidths=0.5, colors='k')
CS = plt.contourf(xt, yt, Z, 15, cmap=plt.cm.RdYlBu_r)
plt.colorbar()

# plot data points.
plt.scatter(xs, ys, marker='o', c='b', s=5, zorder=10)
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.show()

rawDescription: Reshaping after Interpolation

description: Reshaping after Interpolation


code:
def __unicode__(self):
    return self.name

rawDescription: How do we override the choice field display of a reference property in appengine using Django?


code:
from functools import singledispatch
from io import BytesIO, StringIO, IOBase, TextIOBase

@singledispatch
def textualise(input, output):
    if not isinstance(input, IOBase):
        raise TypeError(input)
    if not isinstance(output, TextIOBase):
        raise TypeError(output)
    data = input.read().decode("utf-8")
    output.write(data)
    output.flush()

@textualise.register(bytes)
def textualise_bytes(bytes_):
    input = BytesIO(bytes_)
    output = StringIO()
    textualise(input, output)
    return output.getvalue()

@textualise.register(str)
def textualise_filenames(in_filename, out_filename):
    with open(in_filename, "rb") as input, open(out_filename, "wt") as output:
        textualise(input, output)

s = textualise(b"some text")
assert s == "some text"

textualise("inputfile.txt", "outputfile.txt")

rawDescription: What are the appropriate argument/return types for a function to take binary files/streams/filenames and convert them to readable text format?


code:
import matplotlib.pyplot as plt

# define data

Oxygen = [ 0.1 , 0.5, 1, 10, 15, 20, 15, 10, 1, 0.5, 0.5]
Depth  = [ 0,     1,  2,  4,  8, 10, 12, 14, 16, 20, 40 ]

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(Oxygen, Depth, 'go--')
ax.xaxis.tick_top()

ax.set_ylabel('depth')
ax.set_ylim(50, 0)
ax.set_xlim(0, 25)
ax.set_xlabel('Oxygen level [ppm]')

plt.show()

rawDescription: Is it possible to draw a plot vertically with python matplotlib?


code:
Label(number,textvariable=c1,width=int(c1.get())//10,height=1,fg="red",anchor="ne",bg="green").grid(row=0,column=2, sticky=E, pady=10)
Label(number,textvariable=c2,width=int(c2.get())//10,height=1,fg="blue",anchor="ne",bg="snow").grid(row=4,column=2, sticky=E, pady=10)
Label(number,textvariable=c3,width=int(c3.get())//10,height=1,fg="cyan",anchor="ne",bg="grey").grid(row=8,column=2, sticky=E, pady=10)
Label(number,textvariable=c4,width=int(c4.get())//10,height=1,fg="gold",anchor="ne",bg="blue").grid(row=16,column=2, sticky=E, pady=10)
#                                                                                ^^^^^^^

rawDescription: separate random numbers in tkinter

description: Separate random numbers in tkinter


code:
oldTypeOnes = session.query(oldTable).filter(oldTable.type == 1).all()

for oldTypeOne in oldTypeOnes:
    session.add(newTable(parent_id=oldTypeOne.id, type=oldTypeOne.type, \
        name=oldTypeOne.name))

session.commit()

rawDescription: Copying oldtable to newtable with slight differences in newtable?


code:
import numpy as np
wds = np.random.rand(550800, 8)
z = np.random.rand(212065)
ixs = np.random.randint(212065, size=(550800, 8))
np.einsum('ij,ij->i', wds, z[ixs])
np.vdot(wds[0], z[ixs[0]])
np.vdot(wds[1], z[ixs[1]])

rawDescription: Numpy 2D dot operation, indexing and iteration. How to optimize?


code:
# Before screwing with builtins:
builtins_backup = builtins.__dict__.copy()

# After screwing with builtins:
builtins.__dict__.clear()
builtins.__dict__.update(builtins_backup)

rawDescription: How to Reload a Python Module? Clearing Variable Info


code:
import urllib.request, threading
from queue import Queue
from bs4 import BeautifulSoup
from sys import exit
from a3_3 import store_to_db

class a3_5:

    __url_q = Queue(100)
    __html_q = Queue()
    __data_q = Queue()
    __visited_urls=[]

    def gethtml(self,url):
        try:
            req=urllib.request.Request(url)
            html=urllib.request.urlopen(req).read()
            self.__html_q.put(html)
            pars=urlparse(url)
        except urllib.error.URLError as e:
            print(e.reason+':'+url)
        except:
            print("invalid: " + url)

    def mine_thread(self):
        while True:
            if not self.__html_q.empty():
                soup = BeautifulSoup(self.__html_q.get(),"html.parser")
                for a in soup.find_all('a', href=True):
                    link=a.get('href')
                    """if not link.startswith('www'):
                        link=self.__prfx+link"""
                    if link not in self.__visited_urls:
                        self.__url_q.put(link)
                        self.__data_q.put(link)
            else:
                break

    def store(self):
        while True:
            if not self.__data_q.empty():
                cont=self.__data_q.get()
                print (cont)
            else:
                break

    def download_thread(self):
        while True:
            if not self.__url_q.empty():
                self.gethtml(self.__url_q.get())
                self.__url_q.task_done()

    def op(self,*urls):
        for x in range(25):
            d = threading.Thread(target=self.download_thread)
            d.setDaemon(True)
            d.start()
        for url in urls:
            self.__url_q.put(url)
        self.__url_q.join()
        self.mine_thread()
        self.store()

if __name__ == '__main__':
    urls=['https://en.wikipedia.org/wiki/Bajirao']#,'https://en.wikipedia.org/wiki/Malharrao_Holkar','https://en.wikipedia.org/wiki/Ranoji_Scindia']
    a=a3_5()
    a.op(*urls)

rawDescription: multi threaded crawler in python

description: Multi threaded crawler in python


rawDescription: How do I use numpy.genfromtxt to read a lower triagular matrix into a numpy array?

description: Use numpy.genfromtxt to read a lower triagular matrix into a numpy array


code:
Similarity1 = (1.0 + len(intersection1))/(1.0 + max(len(set_sentence1), len(set_sentence3)))
Similarity2 = (1.0 + len(intersection2))/(1.0 + max(len(set_sentence2), len(set_sentence3)))

rawDescription: compare similarity between sets in python

description: Compare similarity between sets in python


code:
896         # If msg and message_body are sent in a single send() call,
897         # it will avoid performance problems caused by the interaction
898         # between delayed ack and the Nagle algorithm.

rawDescription: Python 3.3 HTTPConnection endheaders and send data


code:
class NullNotNullTransformer(BaseEstimator, TransformerMixin):
    """
    Transforms data according to null/not-null scheme.
    """
    def fit(self, X):
        return self

    def transform(self, X):
        return pd.isnull(X)

rawDescription: A scikit-learn encoder for "Null/Not Null"?


code:
words = df.select("Word").distinct().flatMap(lambda x: x).collect()
dfs = [df.where(df["Word"] == word) for word in words]

rawDescription: PySpark - Split/Filter DataFrame by column's values


code:
import numpy

class SimpleString():
    popSize = 1000
    displaySize = 5
    alphatbet = "abcdefghijklmnopqrstuvwxyz "

    def __init__(self):
        pop = numpy.empty(self.popSize, object)
        target = getTarget()
        targetSize = len(target)

rawDescription: Why is Python class not recognizing static variable


rawDescription: Python: match one of multiple regex patterns and extract IP address if match


code:
from shapes import Shape

class Circle(Shape):
   ...

rawDescription: About importing modules in python

description: About importing modules in python


rawDescription: Querying by related object value

description: Querying by related object value


code:
def settingsUrl(self):
    # this is odd... should be much more straightforward?
    # also, this is pretty slow.
    manager = self.manager
    context = self.context
    assignment = self.data

    allAss = []
    while not assignment in allAss:
        pam = getMultiAdapter((context,manager), IPortletAssignmentMapping)
        allAss = pam.values()
        if assignment in allAss:
            break

        if IAcquirer.providedBy(context):
            context=aq_parent(aq_inner(context))
        else:
            context = context.__parent__

    return '%s/++contextportlets++%s/%s' % (context.absolute_url(),
                                            manager.__name__,
                                            assignment.__name__)

rawDescription: Accessing Plone 4 portlet's assignment context from Renderer instance


code:
a
for row in a:
    row[:] = np.r_[row[row == 0], row[row != 0]]

a

rawDescription: Numpy, sort rows of a matrix putting zeros first and not modifying the rest of the row


code:
import re
# must use raw strings for paths, otherwise we need to
# escape \ characters
input1 = r"C:\Users\sony\Desktop\PBUSH1.BDF"
input2 = r"C:\Users\sony\Desktop\PBUSH2.BDF"

with open(input1) as f1, open(input2) as f2:
    dat1 = f1.read()
    dat2 = f2.read()

# use finditer instead of findall so that we will get
# a match object for each match.
# For each matching line we also have one subgroup, containing the
# "PBUSH   NNN     " part, whereas the whole regex matches until
# the next end of line
matches = re.finditer('^(PBUSH\s+[0-9]+\s+).*$', dat1, flags=re.MULTILINE)

for match in matches:
    # for each match we construct a regex that looks like
    # "^PBUSH   123      .*$", then replace all matches thereof
    # with the contents of the whole line
    dat2 = re.sub('^{}.*$'.format(match.group(1)), match.group(0), dat2, flags=re.MULTILINE)

with open(input2, 'w') as outf:
    outf.write(dat2)

rawDescription: Use findall and sub functions from regex to search and replace exact string


rawDescription: Efficient way to implement newsfeed

description: Efficient way to implement newsfeed


code:
import Tkinter
root = Tkinter.Tk()
frame = Tkinter.Frame(root)
text = Tkinter.Text(frame)
text.pack()
frame.pack()
text.edit_modified()
text.insert('1.0', 'some text')
text.edit_modified()
text.edit_modified(False)
text.edit_modified()

rawDescription: tkinter: check modified

description: Tkinter: check modified


code:
from Tkinter import *
root = Tk()
label = Label(root)
label.pack()
img = PhotoImage(width=300,height=300)
data = ("{red red red red blue blue blue blue}")
img.put(data, to=(20,20,280,280))
label.config(image=img)
root.mainloop()

rawDescription: Why is Photoimage put slow?

description: Why is Photoimage put slow


code:
def get_next_week(self, date):
    """
    Get the next valid week.
    """
    next = date + datetime.timedelta(days=7)
    return _get_next_prev_month(self, next, is_previous=False, use_first_day=False)

def get_previous_week(self, date):
    """
    Get the previous valid week.
    """
    prev = date - datetime.timedelta(days=7)
    return _get_next_prev_month(self, prev, is_previous=True, use_first_day=False)

rawDescription: How do I paginate WeekArchiveView?

description: Paginate WeekArchiveView


code:
Mean=[3.4] #mean
IQR=[3.0,3.9] #inter quantile range
CL=[2.0,5.0] #confidence limit
A=np.random.random(50)
D=plt.boxplot(A) # a simple case with just one variable to boxplot
D['medians'][0].set_ydata(Mean)
D['boxes'][0]._xy[[0,1,4], 1]=IQR[0]
D['boxes'][0]._xy[[2,3],1]=IQR[1]
D['whiskers'][0].set_ydata(np.array([IQR[0], CL[0]]))
D['whiskers'][1].set_ydata(np.array([IQR[1], CL[1]]))
D['caps'][0].set_ydata(np.array([CL[0], CL[0]]))
D['caps'][1].set_ydata(np.array([CL[1], CL[1]]))
_=plt.ylim(np.array(CL)+[-0.1*np.ptp(CL), 0.1*np.ptp(CL)]) #reset the limit

rawDescription: Matplotlib boxplot using precalculated (summary) statistics


code:
import http.cookiejar
import urllib.request
self.cj = http.cookiejar.MozillaCookieJar(self.cookie_file)
self.opener = urllib.request.build_opener(
            urllib.request.HTTPRedirectHandler(),
            urllib.request.HTTPHandler(debuglevel=0),
            urllib.request.HTTPSHandler(debuglevel=0),
            urllib.request.HTTPCookieProcessor(self.cj)
        )

rawDescription: Translating Python 2 code to Python 3

description: Translating Python 2 code to Python 3


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

fig,ax = plt.subplots()
ax.plot(range(10),np.linspace(0,1e11,10))

offset_text = ax.yaxis.get_offset_text()

offset_text.set_size(20)
offset_text.set_color('red')

plt.show()

rawDescription: matplotlib format offset string

description: Matplotlib format offset string


code:
def Palindrome_test_string (input_str):
    output_str = ""
    count = 0
    input_str = input_str.lower()
    ...

rawDescription: How to run a palindrome test on a string in python?

description: Run a palindrome test on a string in python


code:
# col is the column of your data to aggregate over
# minval and maxval are the minimum and maximum (inclusive)
# values they can take. Getting these to set automatically
# is a trivial task.
def agg(A, col, minval, maxval):
    D = np.array( [ [ int(x) for x in d.split(',') ] for d,t in A ] )
    V = np.array( [ t for d,t in A ] )
    dvals = range(minval,maxval+1)
    q = []
    for v in unique(V):
        q.append( { 'name': v, 'series':
                 numpy.array([ [x,sum(V[D[...,col]==x]==v)] for x in dvals ]) } )
    return q

rawDescription: Aggregate Values by Month, Year or Day

description: Aggregate Values by Month, Year or Day


code:
df2 = p.DataFrame()

for name, group in gb:
    if len(group) > 1:
        group['keeper'] =  group.test.isin(preferred_values)
        newindex = group[ group.keeper==True ].head(1).copy()
        if len(newindex) < 1:
            newindex = group.head(1).copy()
        df2 = df2.append(newindex[['data','id','test']])

rawDescription: Removing duplicated indexes with priority given by the value in a column


code:
def seven(array):
    for i in range(len(array)-2):
        three = array[i:i+3]
        if sum(three) == 7:
            return True
    return False

rawDescription: Looping through indices in array by 3s

description: Looping through indices in array by 3s


code:
from playhouse.pool import PooledPostgresqlExtDatabase

db = PooledPostgresqlExtDatabase(
    'my_database',
    max_connections=8,
    stale_timeout=300,
    user='postgres')

rawDescription: Peewee Connection pooling with postgresql 9.4 and JSON fields support


code:
[[y[1] for y in x[1]] for x in itertools.groupby(sorted((hash(y), y)
  for y in items), operator.itemgetter(0))]

rawDescription: Dictionary comprehension to build list of lists: referencing the current value for a key during comprehension


rawDescription: Swap position of entities in the list

description: Swap position of entities in the list


code:
import pytest
import requests
from hamcrest import *

class SiteImpl:
    def __init__(self, url):
        self.url = url

    def has_valid_cert(self):
        return requests.get(self.url, verify=True)

@pytest.yield_fixture
def site(request):
    # setUp
    yield SiteImpl('https://' + request.param)
    # tearDown

def has_status(item):
    return has_property('status_code', item)

@pytest.mark.parametrize('site', ['google.com', 'github.com'], indirect=True)
def test_cert(site):
    assert_that(site.has_valid_cert(), has_status(200))

if __name__ == '__main__':
    pytest.main(args=[__file__, '-v'])

rawDescription: What is a good Python library on which to base custom http test assertions?


code:
with open(filename) as f:
    for word in real_longest:
        print("This word is one of the largest:", word)
        print(len(word))       # <---------- changed here from `len(longest)` .

rawDescription: Error printing the length of the longest word?


code:
idf = df.set_index(['tag', 'epochTimeMS'], verify_integrity=False).sort_index()
idf
idf.ix['tag1']

rawDescription: Pandas rolling median for duplicate time series data


code:
class Base(object):
    foo = 5

class Derived(Base):
    """A class derived from Base.

    >>> bar = Base()
    >>> print bar.foo
    5
    >>> foobar = Derived()
    >>> print foobar.foo
    6
    >>> print foobar.__class__.__base__.foo
    5
    >>> foobar.__class__.__base__.foo = 7
    >>> bar.foo
    7
    """
    foo = 6

rawDescription: Access a member in base class in Python?

description: Access a member in base class in Python


code:
class MySpider(CrawlSpider):
    ...
    start_urls_crawlspider = (url1, url2,)
    start_urls_basespider = (url3,)

    def start_requests(self):
        for url in self.start_urls_crawlspider :
            yield Request(url, callback=self.parse) # "parse" is the default anyway

        for url in self.start_urls_basespider:
            yield Request(url, callback=self.parse_base)

    def parse_base(self, response):
        ...

rawDescription: BaseSpider and CrawlSpider together

description: BaseSpider and CrawlSpider together


code:
class BaseDynamic:
    def __conform__(self, protocol):
        if protocol is sqlite3.PrepareProtocol:
            return self.args_string

rawDescription: Registering base class adapter in Python's sqlite3


code:
rom_file= [0,3,1]
#Main Function which adds s dots and xs to the deck list(s) depending on the data input file
def main():
    #Container for the output of the program, each nested list contains one row of the output
    decks = [[], [], [], [], []]
    #list that contains the number of empty rows for inputs 1-5(location of input given by [each - 1])
    empty_rows = [4, 3, 2, 1, 0]
    #Scan through each element of the list
    for each in from_file:
        #If the element 'each' is equal to 0, append a single dot to all 5 rows
        if each == 0:
            for i in range(5):
                decks[i].append('.')
        #If the input is in the range 1-5, define variables and the nested for loops
        else:
            #Maximum width of each pyramid
            max = (each * 2) - 1
            half_dots = int((max - 1) / 2)
            base_x = 1
            loc = each - 1
            #For loop that appends the max. number of dots to rows depending on data in empty_rows
            for every in range(empty_rows[loc]):
                decks[every].append(max * '.')
            #Primary for loop; appends the dots and xs to any row not covered by the previous loop (ALl rows that do not already have max dots) for each between 1-5
            for i in range(each):
                decks[i + empty_rows[loc]].append(half_dots * '.')
                decks[i + empty_rows[loc]].append(base_x * 'x')
                decks[i + empty_rows[loc]].append(half_dots * '.')
                half_dots -= 1
                base_x += 2
    #A loop that print out the results
    for each in decks:
        text = ""
        for i in each:
            text += i
        print(text)

#Starts the program by calling the main function
main()

rawDescription: Converting images to grey scale in Python


code:
with open('output.csv', 'w') as dest:
    writer = csv.writer(dest)
    for key, values in data.items():
        writer.writerow([key, values[0]])
        for value in values[1:]:
            writer.writerow([None, value])

rawDescription: Saving records to a CSV from python with multiple values assigned to each record


code:
z_values = {
    1: X1,
    42: X2,
    }

Z = z_values[V]

rawDescription: Python assign value X if variable V is 1, Y if it is 43,


code:
class EditProfileForm(forms.ModelForm):

    def __init__(self, initial_volunteer, *args, **kwargs):
            super(EditProfileForm, self).__init__(*args, **kwargs)
            self.fields['language'] = forms.ModelMultipleChoiceField(
            label=_(u'Language'),
            queryset=Language.objects.all(),
            # now you have the value you passed to use here
            initial=VolunteerLanguage.objects.filter(volunteer=initial_volunteer)
            )

rawDescription: How would I use the objects from a related Model to populate the initial value of a Field in a ModelForm?


code:
class Parent(models.Model):

    @property
    def subchildren_count(self):
        return Subchildren.objects.filter(child__parent=self).count()

rawDescription: Django: How to Order a set By the number of its children's children?


code:
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.widgets.markers import makeMarker

def bar_chart():
    drawing = Drawing(400, 200)
    # ...
    drawing.add(bc)
    return drawing

def line_plot():
    drawing = Drawing(400, 200)
    # ...
    drawing.add(lp)
    return drawing

the_canvas = canvas.Canvas("output.pdf")
renderPDF.draw(bar_chart(), the_canvas, 0, 0)
the_canvas.showPage()
renderPDF.draw(line_plot(), the_canvas, 0, 0)
the_canvas.showPage()
the_canvas.save()

rawDescription: Generating Reports using ReportLabs in Python


rawDescription: Easy way for finding elements in a NP.array and replacing them


code:
class MyModel(models.Model):

    # your fields....

    class Meta:
        verbose_name = 'Activity'
        verbose_name_plural = 'Activities'

rawDescription: django 1.2.1: Override model name in admin interface?

description: Django 1.2.1: Override model name in admin interface


code:
import numpy
pr = 0.5
x = numpy.random.geometric(pr, 1)[0]

rawDescription: Prioritizing first items in a list (Random & Probability Distribution)


rawDescription: how to pass value from output to a string in python

description: Pass value from output to a string in python


code:
import sys
from PyQt4.Qt import *

class MyPopup(QWidget):
    def __init__(self, mainWindow):
        QWidget.__init__(self)

        # use the mainWindow passed as parameter
        mainWindow.label1.setText('hello')

class MainWindow(QMainWindow):
    def __init__(self, *args):
        QMainWindow.__init__(self, *args)
        self.cw = QWidget(self)
        self.setCentralWidget(self.cw)
        self.btn1 = QPushButton("Click me", self.cw)
        self.btn1.setGeometry(QRect(50, 50, 100, 30))
        self.label1 = QLabel("No Commands running", self.cw)
        self.connect(self.btn1, SIGNAL("clicked()"), self.doit)
        self.w = None

    def doit(self):
        self.w = MyPopup(self) #when creating the popup pass in the main window
        self.w.setGeometry(QRect(100, 100, 400, 200))
        self.w.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())

rawDescription: PyQt class inheritance

description: PyQt class inheritance


code:
from gi.repository import Gtk

class FileChooserWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="FileChooser Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Choose File")
        button1.connect("clicked", self.on_file_clicked)
        box.add(button1)

        button2 = Gtk.Button("Choose Folder")
        button2.connect("clicked", self.on_folder_clicked)
        box.add(button2)

    def on_file_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        self.add_filters(dialog)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()

    def add_filters(self, dialog):
        filter_text = Gtk.FileFilter()
        filter_text.set_name("Text files")
        filter_text.add_mime_type("text/plain")
        dialog.add_filter(filter_text)

        filter_py = Gtk.FileFilter()
        filter_py.set_name("Python files")
        filter_py.add_mime_type("text/x-python")
        dialog.add_filter(filter_py)

        filter_any = Gtk.FileFilter()
        filter_any.set_name("Any files")
        filter_any.add_pattern("*")
        dialog.add_filter(filter_any)

    def on_folder_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a folder", self,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             "Select", Gtk.ResponseType.OK))
        dialog.set_default_size(800, 400)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Select clicked")
            print("Folder selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()

win = FileChooserWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: Calling ubuntu file browser (explorer) in python


code:
class Foo(object):

    def __init__(self):
        self.hello = "Hey!"

    def bar(self):
        return self.hello + " How's it going?"

def side_effect_foo_bar(*args, **kwargs):
    return args[0].hello + " What's up?"

class TestFoo(unittest.TestCase):

    @patch.object(Foo, 'bar', autospec=True)
    def test_bar(self, mocked_bar):
        mocked_bar.side_effect = side_effect_foo_bar
        foo = Foo()
        self.assertTrue(foo.bar() == "Hey! What's up?")

rawDescription: How to access object instance from mocked instance method when unit testing?

description: Access object instance from mocked instance method when unit testing


code: sorted(inputdict.items(), key=lambda item: item[1]['sum'])

rawDescription: Sort nested dictionary by values

description: Sort nested dictionary by values


code:
from kivy.lang import Builder
from kivy.app import App
from kivy.properties import NumericProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label

kv_str = '''
<PrimeiroScreen>:
    GridLayout:
        cols: 1
        size_hint: (.3, .1)
        pos_hint:{'x': .045, 'y': .89}
        MyLabel:
            text: "my value: {}".format(self.value)
            font_size: '30dp'
            text_size: self.width, self.height
            id: lb1
        Button:
            text: "Somar 3"
            font_size: '30dp'
            text_size: self.width - 50, self.height
            on_press: root.fc()
'''

class PrimeiroScreen(Screen):
    def fc(self):
        self.ids.lb1.value += 1

class MyLabel(Label):
    value = NumericProperty(0)

Builder.load_string(kv_str)

class AnApp(App):
    def build(self):
        rw = ScreenManager()
        rw.add_widget(PrimeiroScreen(name='main'))
        return rw
AnApp().run()

rawDescription: How to add to number in label in kivy?

description: Add to number in label in kivy


code:
class EventAdmin(admin.ModelAdmin):
  filter_horizontal = ('participantes',)

rawDescription: Change default form for field in django

description: Change default form for field in django


code:
fig, ax = plt.subplots(figsize=(6, 10))

ax.matshow(df.mask(df.isin(df.att1)!=True), cmap=cm.Reds,  aspect='auto')
ax.matshow(df.mask(df.isin(df.att2)!=True), cmap=cm.Greens, aspect='auto')
ax.matshow(df.mask(df.isin(df.att3)!=True), cmap=cm.Blues, aspect='auto')

plt.xticks(range(3), df.columns)
plt.yticks(range(0, 800, 100), df.index[::100])

rawDescription: Increasing Number of Rows in Python 2D Heatmap


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

data=np.arange(9).reshape((3,3))
plt.imshow(data)
plt.xlim(0.5, 1.5)
plt.ylim(0.5,1.5)
plt.show()

rawDescription: Matplotlib imshow zoom function?

description: Matplotlib imshow zoom function


code:
for cell in self.cells.flat:
    do_somethin(cell)

rawDescription: Iterating through a multidimensional array in Python


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

engine = create_engine('sqlite:///:memory:')
Base = declarative_base()

class Answer(Base):
    __tablename__ = 'answer'

    id = Column(Integer, primary_key=True)
    question_id = Column(Integer, ForeignKey('question.id'))
    text = Column(String)

    question = relationship('Question', backref='answers')

    def __repr__(self):
        return "<Answer '%s'>" % self.text

class Question(Base):
    __tablename__ = 'question'

    id = Column(Integer, primary_key=True)
    text = Column(String)

    best_answer = relationship('Answer',
                               secondary=lambda: best_answer,
                               uselist=False)

    def __repr__(self):
        return "<Question, '%s'>" % (self.text)

best_answer = Table('best_answer', Base.metadata,
                    Column('question_id',
                           Integer,
                           ForeignKey('question.id'),
                           primary_key=True),
                    Column('answer_id',
                           Integer,
                           ForeignKey('answer.id'))
                    )

if __name__ == '__main__':

    session = sessionmaker(bind=engine)()
    Base.metadata.create_all(engine)

    question = Question(text='How good is SQLAlchemy?')

    somewhat = Answer(text='Somewhat good')
    very = Answer(text='Very good')
    excellent = Answer(text='Excellent!')

    question.answers.extend([somewhat, very, excellent])
    question.best_answer = excellent

    session.add(question)
    session.commit()

    question = session.query(Question).first()

    print(question.answers)
    print(question.best_answer)

rawDescription: How do I get rid of a circular dependency error while creating a database in sqlalchemy?

description: Get rid of a circular dependency error while creating a database in sqlalchemy


code:
while True:
    DISPLAYSURF.blit(background,(0,0))

    DISPLAYSURF.blit(sprite,(spritex,spritey))

    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if (event.key == K_LEFT):
                sprite=pygame.image.load('left.png')
            elif (event.key == K_RIGHT):
                sprite=pygame.image.load('right.png')
            elif (event.key == K_UP):
                sprite=pygame.image.load('up.png')
            elif (event.key == K_DOWN):
                sprite=pygame.image.load('down.png')

    keys_pressed = key.get_pressed()

    if keys_pressed[K_LEFT]:
        spritex -= 5

    if keys_pressed[K_RIGHT]:
        spritex += 5

    if keys_pressed[K_UP]:
        spritey -= 5

    if keys_pressed[K_DOWN]:
        spritey += 5

    pygame.display.update()
    fpsClock.tick(FPS)

rawDescription: Python - Smooth Keyboard Movement in Pygame


code:
class mainClass(irc.IRCClient):

    from othermodule import a, b, c
    # othermodule.a, b, and c are now methods of mainClass

    from anothermodule import *
    # everything in anothermodule is now in mainClass

    # if there are name conflicts, last import wins!

rawDescription: Importing methods from file into a class


code:
df = pd.DataFrame({'item_id':['a', 'b', 'a'], 'foo':['X','Y','Z']})
df.groupby('item_id').agg(' '.join).reset_index()

rawDescription: How to group all review texts of each item together with python-pandas?

description: Group all review texts of each item together with python-pandas


rawDescription: Python3 - How to create a list from a string without breaking up the int


code:
allLines = [line for line in stdout.readlines()]
data_no_firstfour = "\n".join(allLines[4:])

rawDescription: How to remove lines from stdout in python?

description: Remove lines from stdout in python


code:
import wx

class Mainframe(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.panel = wx.Panel(self)

        ctrls = []
        for n in range(6):
            ctrls.append(wx.StaticText(self.panel, label='bad',
                pos=(20, 30 * n)))

        ctrls[1].SetLabel('good')
        ctrls[5].SetLabel('excellent')

if __name__ == '__main__':
    app = wx.App(False)
    frame = Mainframe(None)
    frame.Show()
    app.MainLoop()

rawDescription: creating statictext dynamically and then setting label with python

description: Creating statictext dynamically and then setting label with python


code:
class MyParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.epilog

rawDescription: displaying newlines in the help message when using python's optparse

description: Displaying newlines in the help message when using python's optparse


code:
import http.client

def chunk_data(data, chunk_size):
    dl = len(data)
    ret = ""
    for i in range(dl // chunk_size):
        ret += "%s\r\n" % (hex(chunk_size)[2:])
        ret += "%s\r\n\r\n" % (data[i * chunk_size : (i + 1) * chunk_size])

    if len(data) % chunk_size != 0:
        ret += "%s\r\n" % (hex(len(data) % chunk_size)[2:])
        ret += "%s\r\n" % (data[-(len(data) % chunk_size):])

    ret += "0\r\n\r\n"
    return ret

conn = http.client.HTTPConnection(host)
url = "/some_path"
conn.putrequest('POST', url)
conn.putheader('Transfer-Encoding', 'chunked')
conn.endheaders()
conn.send(chunk_data(body, size_per_chunk).encode('utf-8'))

resp = conn.getresponse()
print(resp.status, resp.reason)
conn.close()

rawDescription: How to force http.client to send chunked-encoding HTTP body in python?

description: Force http.client to send chunked-encoding HTTP body in python


code:
class MainHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.POST['myName']
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write("Hello, %s!" % name)

rawDescription: Create a POST service in app engine with python


rawDescription: Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?


code:
import logging

class MyFilter(logging.Filter):
    def filter(self, record):
        record.filename_lineno = "%s:%d" % (record.filename, record.lineno)
        return True

rawDescription: How to set width of combined fields in Python logging

description: Set width of combined fields in Python logging


code:
np.ma.array(a, mask=np.concatenate((b,b,b)))  # shapes are (3, 3, 3) and (9, 3)
np.ma.array(a, mask=np.tile(b, (a.shape[0],1)))  # same as above, just more general as it doesn't require you to specify just how many times you need to stack b.
np.ma.array(a, mask=a*b[np.newaxis,:,:])  # used broadcasting

rawDescription: Apply Mask Array 2d to 3d

description: Apply Mask Array 2d to 3d


code:
def abcmaker(ind):
    def abc(state):
        self.feature_inputs[ind].setEnabled(state == Qt.Checked)
    return abc
active_checkbox.stateChanged.connect(abcmaker(i))

rawDescription: Few slot connection in cycle

description: Few slot connection in cycle


code:
n = 1000
xs = np.random.randn(n).cumsum()
i = np.argmax(np.maximum.accumulate(xs) - xs) # end of the period
j = np.argmax(xs[:i]) # start of period

plt.plot(xs)
plt.plot([i, j], [xs[i], xs[j]], 'o', color='Red', markersize=10)

rawDescription: Start, End and Duration of Maximum Drawdown in Python


code:
import matplotlib.pyplot as plt

# initial plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3,4,5])

yTickPos,_ = plt.yticks()
yTickPos = yTickPos[:-1] #slice off the last as it is the top of the plot
# create bars at yTickPos that are the length of our greatest xtick and have a height equal to our tick spacing
ax.barh(yTickPos, [max(plt.xticks()[0])] * len(yTickPos), height=(yTickPos[1]-yTickPos[0]), color=['g','w'])

plt.show()

rawDescription: matplotlib - zebra-stripe a figure's background color?

description: Matplotlib - zebra-stripe a figure's background color


code:
#!/usr/bin/python
# based on : www.daniweb.com/code/snippet263775.html
import math
import wave
import struct

# Audio will contain a long list of samples (i.e. floating point numbers describing the
# waveform).  If you were working with a very long sound you'd want to stream this to
# disk instead of buffering it all in memory list this.  But most sounds will fit in
# memory.
audio = []
sample_rate = 44100.0

def append_silence(duration_milliseconds=500):
    """
    Adding silence is easy - we add zeros to the end of our array
    """
    num_samples = duration_milliseconds * (sample_rate / 1000.0)

    for x in range(int(num_samples)):
        audio.append(0.0)

    return

def append_sinewave(
        freq=440.0,
        duration_milliseconds=500,
        volume=1.0):
    """
    The sine wave generated here is the standard beep.  If you want something
    more aggresive you could try a square or saw tooth waveform.   Though there
    are some rather complicated issues with making high quality square and
    sawtooth waves... which we won't address here :)
    """

    global audio # using global variables isn't cool.

    num_samples = duration_milliseconds * (sample_rate / 1000.0)

    for x in range(int(num_samples)):
        audio.append(volume * math.sin(2 * math.pi * freq * ( x / sample_rate )))

    return

def save_wav(file_name):
    # Open up a wav file
    wav_file=wave.open(file_name,"w")

    # wav params
    nchannels = 1

    sampwidth = 2

    # 44100 is the industry standard sample rate - CD quality.  If you need to
    # save on file size you can adjust it downwards. The stanard for low quality
    # is 8000 or 8kHz.
    nframes = len(audio)
    comptype = "NONE"
    compname = "not compressed"
    wav_file.setparams((nchannels, sampwidth, sample_rate, nframes, comptype, compname))

    # WAV files here are using short, 16 bit, signed integers for the
    # sample size.  So we multiply the floating point data we have by 32767, the
    # maximum value for a short integer.  NOTE: It is theortically possible to
    # use the floating point -1.0 to 1.0 data directly in a WAV file but not
    # obvious how to do that using the wave module in python.
    for sample in audio:
        wav_file.writeframes(struct.pack('h', int( sample * 32767.0 )))

    wav_file.close()

    return

append_sinewave(volume=0.25)
append_silence()
append_sinewave(volume=0.5)
append_silence()
append_sinewave()
save_wav("output.wav")

rawDescription: python - how can I generate a WAV file with beeps?

description: Python - how can I generate a WAV file with beeps


code:
# version1: table definition
mytable = Table('mytable', meta,
    # ...
    Column('customer_id', Integer, ForeignKey('customers.customer_id')),
    Column('location_code', Unicode(10)),

    UniqueConstraint('customer_id', 'location_code', name='uix_1')
    )
# or the index, which will ensure uniqueness as well
Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)

# version2: declarative
class Location(Base):
    __tablename__ = 'locations'
    id = Column(Integer, primary_key = True)
    customer_id = Column(Integer, ForeignKey('customers.customer_id'), nullable=False)
    location_code = Column(Unicode(10), nullable=False)
    __table_args__ = (UniqueConstraint('customer_id', 'location_code', name='_customer_location_uc'),
                     )

rawDescription: sqlalchemy unique across multiple columns

description: Sqlalchemy unique across multiple columns


code:
powers = {'B': 10 ** 9, 'M': 10 ** 6, 'T': 10 ** 12}
# add some more to powers as necessary

def f(s):
    try:
        power = s[-1]
        return int(s[:-1]) * powers[power]
    except TypeError:
        return s

df.applymap(f)

rawDescription: Converting string of numbers and letters to int/float in pandas dataframe


code:
class Slot:
# the '__init__' method is the constructor
# the first argument must be 'self' (as with any method belonging to the class)
#the advantage of giving default values (here 'None') is that you do not have to care the parameter order when calling the method
    def __init__(self,SerialNumber=None,PartNumber=None,
                 Name=None,Status=None,Type=None):
        self.SerialNumber = SerialNumber
        self.PartNumber = PartNumber
        self.Name = Name
        self.Status = Status
        self.Type = Type
        print('Name: ',Name,' ; SerialNumber: ',SerialNumber,
              ' ; PartNumber: ',PartNumber,
              ' ; Status: ',Status,' ; Type: ',Type)

# further in the code, you create the instances of the object Slot
CPM = Slot(Name='CPM', PartNumber='toto', Type='poo')# just to show you can give any parameter in any order
IOM = Slot(Name='IOM')
MDA = Slot(Name='MDA')
# to access the values of instances:
print('CPM name: ',CPM.Name)
print('CPM Type: ', CPM.Type)
CPM.Type = 'paa'
#...

rawDescription: Python: how to create a class with objects and attributes


rawDescription: How to access name of a specific vertex in graph (python-igraph)

description: Access name of a specific vertex in graph (python-igraph)


code:
def make_re(args):
    args = (re.escape(arg) for arg in args) #if you want to escape special characters
    return re.compile('^({0})$'.format('|'.join(args)) )

boolre = make_re(('true','false'))

rawDescription: Regular expression to test a limited palette of possible values for a string?


code:
import datetime

restaurant.date = Date(date=datetime.datetime(2014, 11, 15))

rawDescription: ParsePy AttributeError: 'Date' object has no attribute '_date'


code:
fwd()
ot = time.time()
while(time.time() - ot < 4):    #running while loop for 3 seconds
    BrickPiUpdateValues()       # Ask BrickPi to update values for sensors/motors
    time.sleep(.1)
stop()

rawDescription: BrickPi Python Documentation

description: BrickPi Python Documentation


rawDescription: How to grow a list to fit a given capacity in Python

description: Grow a list to fit a given capacity in Python


code:
# You update your copy here, so the original will be used unchanged, which is not the
# case if you don't have the copy
valuesCopy.update({state: convergedValue})

# If you have the copy, you'll be using the old value stored in self.value here,
# not the updated one
qValue += probability * (reward + (self.discount * self.values[successor]))

rawDescription: Why is shallow copy needed for my values dictionary to correctly update?


code:
from matplotlib._cntr import Cntr

x, y = np.linspace(0, 2*np.pi), np.linspace(0, 2*np.pi)
xx, yy = np.meshgrid(x, y)
data = np.sin(xx) * np.sin(yy)
level = 0.5

cntr = Cntr(xx, yy, data)
res = cntr.trace(level)

rawDescription: numpy analog of matplotplotlib contourplot?

description: Numpy analog of matplotplotlib contourplot


code: [key for key in keys if not any(re.match(pattern, key) for pattern in patterns)]

rawDescription: Python list of strings and list of regexes, clean way to find strings which don't match anything?


code: os.read(fd, n)

rawDescription: Python sys.stdin.read(max) blocks until max is read (if max>=0), blocks until EOF else, but select indicates there is data to be read


code:
import itertools
from collections import defaultdict
partition_lengths = [1, 2, 3]
range_start = 1
range_end = 12
endpoints = defaultdict(list)
for p_len in itertools.cycle(partition_lengths):
    end = range_start + p_len - 1
    if end > range_end: break
    endpoints[p_len].append((range_start, end))
    range_start += p_len

endpoints

rawDescription: Getting the endpoints of sets across a range


code: {tuple(sorted(t)): t for t in list_1}.values()

rawDescription: Removing commutative pairs in a list in Python


code: l = [another_function(i) for i in range(lower, upper)]

rawDescription: making a list from values returned by a function inside a for-loop in python

description: Making a list from values returned by a function inside a for-loop in python


code:
from statistics import mean

def main():
   grades = getScores()
   grade = mean(grades)
   abcGrade = getGrade(grade)
   print(grade, "is an", abcGrade)

def getScores():
   grades = []
   while True:
      grade = int(input("Enter grades (-999 ends): "))
      if grade == -999: return grades
      grades.append(grade)

def getGrade(grade):
   best = 100
   if grade >= best - 10:
      return 'A'
   elif grade >=  best - 20:
      return 'B'
   elif grade >= best - 30:
      return 'C'
   elif grade >= best - 40:
      return 'D'
   else:
      return 'F'

main()

rawDescription: Python 3- Assign grade

description: Python 3- Assign grade


code:
import xml.etree.cElementTree as et

def is_svg(filename):
    tag = None
    with open(filename, "r") as f:
        try:
            for event, el in et.iterparse(f, ('start',)):
                tag = el.tag
                break
        except et.ParseError:
            pass
    return tag == '{http://www.w3.org/2000/svg}svg'

rawDescription: How can I say a file is SVG without using a magic number?

description: Say a file is SVG without using a magic number


code:
import mosquitto
import time # import time module
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",8000,60,True)
mqttc.subscribe("test/", 2)
while mqttc.loop() == 0:
    mqttc.publish("test","Hello")
    time.sleep(10)# sleep for 10 seconds before next call

rawDescription: publish a message every 10 seconds mqtt

description: Publish a message every 10 seconds mqtt


code:
## top of my .fcgi script
import sys, time
original_modules = sys.modules.copy()

## in a separate thread
old_ctime = os.path.getctime("mymodule.py")
while True:
    time.sleep(10)
    new_ctime = os.path.getctime("mymodule.py")
    if new_ctime > old_ctime:
        sys.modules = original_modules # reset all imports
        import mymodule
        mymodule.dofcgi()

rawDescription: Reload mod_fcgid without killing Python Service


code:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('your excel file.xlsx')
print(len(wb.Worksheets))  # tells you how many worksheets

rawDescription: Number of spreadsheets in workbook in python


code:
json_output = [
  [
    {
      "internal": "0",
      "flags": "0",
      "groupid": "110",
      "name": "- GSOC - Systems"
    },
    {
      "internal": "0",
      "flags": "0",
      "groupid": "313",
      "name": "Applications - Email Digest"
    }
  ]
]

names = [d['name'] for d in json_output[0]]

print(names)  # -> [u'- GSOC - Systems', u'Applications - Email Digest']

rawDescription: Extracting multiple fields from json output


code:
s = ['p=011', 'or=artificial', 'pc=3718']
dict(x.split('=') for x in s)

rawDescription: python: how to make the result of split directly key, value pair

description: Python: how to make the result of split directly key, value pair


code:
def pctSame(s1,s2):
    # Make sorted arrays of string chars
    s1c = [x for x in s1]
    s1c.sort()
    s2c = [x for x in s2]
    s2c.sort()
    i1 = 0
    i2 = 0
    same = 0
    # "merge" strings, counting matches
    while ( i1<len(s1c) and i2<len(s2c) ):
        if s1c[i1]==s2c[i2]:
            same += 2
            i1 += 1
            i2 += 1
        elif s1c[i1] < s2c[i2]:
            i1 += 1
        else:
            i2 += 1
    # Return ratio of # of matching chars to total chars
    return same/float(len(s1c)+len(s2c))

rawDescription: Comparing 2 strings with similar letters


code:
class Item(models.Model):
    serial_number = models.CharField(max_length=200)
    name = models.CharField(max_length=200)
    part_number = models.CharField(max_length=200)
    location = models.CharField(max_length=200)
    rma = models.ForeignKey(RMA)
    def __unicode__(self):
        return self.name

rawDescription: Storing list of objects in Django model

description: Storing list of objects in Django model


code:
df1 = pd.DataFrame(myData1, columns=['Genre', 'City', 'Sold'])
df2 = pd.DataFrame(myData2, columns=['Genre', 'City', 'Sold'])

df1['Key'] = 'trail1'
df2['Key'] = 'trail2'

DF = pd.concat([df1,df2],keys=['trail1','trail2'])

DFGroup = DF.groupby(['Genre','Key'])

DFGPlot = DFGroup.sum().unstack('Key').plot(kind='bar')

rawDescription: How to plot two DataFrame on same graph for comparison

description: Plot two DataFrame on same graph for comparison


code:
import re
samp = """<sitemap xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <loc>http://www.some_page.com/sitemap-page-2010-11.xml</loc>
    <lastmod>2011-12-22T15:46:17+00:00</lastmod>
</sitemap>"""
re.findall(r'<loc>(.*)</loc>', samp)

rawDescription: LXML: remove the x

description: LXML: remove the x


rawDescription: Python regex matching 1 or 2 but not 3 of a character


code:
import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.text = tk.Text(self)
        self.text.pack()
        self.text.bind("<KeyRelease-Return>", self.on_return_release)

    def on_return_release(self, event):
        self.text.insert("end", "boink! ")

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: Tkinter <Return> event on key release

description: Tkinter <Return> event on key release


code:
#!/usr/bin/env python
"""
Draw a graph with matplotlib.
You must have matplotlib for this to work.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
try:
    import matplotlib.pyplot as plt
except:
    raise

import networkx as nx

G=nx.house_graph()
# explicitly set positions
pos={0:(0,0),
     1:(1,0),
     2:(0,1),
     3:(1,1),
     4:(0.5,2.0)}

nx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4])
nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b')
nx.draw_networkx_edges(G,pos,alpha=0.5,width=6)
plt.axis('off')
plt.savefig("house_with_colors.png") # save as png
plt.show() # display

rawDescription: Adding an edge/node with a color attribute


rawDescription: print statement not appearing in terminal

description: Print statement not appearing in terminal


code:
open("/etc/passwd","r") #Oops I forgot to assign it
f = _ # Not to worry. It's stored as _
f

rawDescription: How to assign a memory address to a variable in Python?

description: Assign a memory address to a variable in Python


code:
class UserServiceWizard(SessionWizardView):
    instance = None

    def get_form(self, step=None, data=None, files=None):
        if step is None:
            step = self.steps.current

        prev_data = self.get_cleaned_data_for_step(self.get_prev_step(
                                                    self.steps.current))
        if step == '1':
            service_name = str(prev_data['provider']).split('Service')[1]
            form_class = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ProviderForm')
            form = form_class(data)
        elif step == '3':
            service_name = str(prev_data['consummer']).split('Service')[1]
            form_class = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ConsummerForm')
            form = form_class(data)
        else:
            form = super(UserServiceWizard, self).get_form(step, data, files)

        return form

rawDescription: Django FormWizard how to change the form_list dynamically


code: max(a, key=sum)

rawDescription: Finding maximum of a list of lists by sum of elements in Python


code:
def addWordHistory(words):
    current = [wordhistory, 0]
    for word in words:
        if current[0] is None:
            current[0] = dict()
        children = current[0]
        if word in children:
            children[word][1] += 1
        else:
            children[word] = [None, 1]
        current = children[word]

rawDescription: Python: reference and dereference of global variables in functions


code:
s = "abaccea"
[s[:key] + s[key+1:] for key,val in enumerate(s) if val == "a"]

rawDescription: Removing a character in a string one at a time


code:
x = Test()
y = x.returnTest()
y

rawDescription: Can a python class return a new instance of its class?


code:
import numpy as np
np.issubdtype(np.int32, int)
np.issubdtype(np.int32, float)
np.issubdtype(float, np.floating)
np.issubdtype(float, np.inexact)
np.issubdtype(np.float32, float)
np.issubdtype(np.float32, int)
np.issubdtype(np.float32, np.floating)

rawDescription: Comparing numpy datatypes to strings

description: Comparing numpy datatypes to strings


rawDescription: remove zero lines 2-D numpy array

description: Remove zero lines 2-D numpy array


code:
output = content.split('&')
x = output[0]
y = output[1]

rawDescription: Oauth Python twitter auth

description: Oauth Python twitter auth


code:
import pandas as pd
orig_df = pd.read_excel(orig_excel_path, sheetname=sheetname)
orig_df.head(10).to_excel(new_excel_path, sheet_name=new_sheetname)

rawDescription: Python to keep top 10 rows of Excel file


code:
from parse import *
parse("{}_{}_{}", "a_bc_def")
a,b,c  = parse("{}_{}_{}", "_1ad_das__")
a
b
c

rawDescription: Can str.format(**arg) be used to check for formatting?


code:
from django.forms import TextInput

class CategoriesForm(ModelForm):
    class Meta:
        model = Categories
        widgets = {
            'category_name': TextInput(attrs={'placeholder': 'PLACEHOLDER TEXT HERE'})
        }

rawDescription: how can i have a text field which have text in it and when the user clicks on the text field the text inside the field vanishes

description: Have a text field which have text in it and when the user clicks on the text field the text inside the field vanishes


code:
app = wx.App(redirect=False)
frame = wx.Frame(None)
static_box = wx.StaticBox(frame, label='Label')
sizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)

for i in range(5):
    sizer.Add(wx.Button(frame, label='Button ' + str(i)))

frame.Sizer = sizer
frame.Sizer.Fit(frame)
frame.Show()
app.MainLoop()

rawDescription: How to add widgets inside a StaticBox, wxPython?

description: Add widgets inside a StaticBox, wxPython


code:
import socket
import urlparse

hostname = urlparse.urlparse("%s://%s"
    % (self.request.protocol, self.request.host)).hostname

ip_address = socket.gethostbyname(hostname)

rawDescription: How to get server IP-address in Tornado?

description: Get server IP-address in Tornado


code:
from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))

rawDescription: Flask/Werkzeug how to attach HTTP content-length header to file download


rawDescription: plt.axis(): How to 'tight' axis hiding boundary NaNs?

description: Plt.axis(): How to 'tight' axis hiding boundary NaNs


code:
class ModelA(models.Model):
    name = models.CharField()

    def _greetings(self):
        return 'Hello ' + self.name
    _greetings.admin_order_field = "name"

class ModelAAdmin(admin.ModelAdmin):
    list_display = ["name", "_greetings"]

rawDescription: Assigning the model field values to a custom field in django?


code:
def product(number):
    return [number * i for i in range(2, 10)]

rawDescription: Multiply a range of numbers - Python2.x

description: Multiply a range of numbers - Python2.x


code:
def foo(zip,zipcodes):
    x=zipcodes.index(zip)
    if x==0 :
      return zipcodes [:2]
    elif x==len(zipcodes):
      return zipcodes [-2:]
    return zipcodes[x-1:x+2]

zipcodes = [11105,11102,11103,11104,11377,11373,11372,11368]
foo(11105,zipcodes)
foo(11368,zipcodes)
foo(11104,zipcodes)

rawDescription: Extracting index value from list, by passing a variable through a function


code:
st = NERTagger('stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz', 'stanford-ner/stanford-ner.jar')
tokenized_sents = [[word_tokenize(sent) for sent in sent_tokenize(filecontent)] for filename in filelist]
st.tag_sents(tokenized_sents)

rawDescription: how to speed up NE recognition with stanford NER with python nltk

description: Speed up NE recognition with stanford NER with python nltk


rawDescription: Convert SQL Query to ORM Query Django

description: Convert SQL Query to ORM Query Django


code:
# open the profile pic
im = PIL.Image.open(pic)
# resize it to dim of oblique box
im = im.resize((picX, picY), PIL.Image.ANTIALIAS)

# this is the degree of oblique box
degree = 13.67

# open the background
bg = PIL.Image.open(bgsrc)
bgosize = bg.size
bginfo = bg.info

# create a copy of the profile that is all white
mask = PIL.Image.new('L', im.size, 0xff)

# rotate the profile and the mask
im = im.rotate(degree, resample = PIL.Image.BICUBIC, expand = True)
mask = mask.rotate(degree, resample = PIL.Image.BICUBIC, expand = True)

# paste the profile pic to background
bg.paste(im, (px1, py1, px2, py2), mask)

PIL.ImageFile.MAXBLOCK = bg.size[0] * bg.size[1]
bg.save(dst, quality = 250, optimize = True, **bginfo)

rawDescription: Lower image quality after paste two files


rawDescription: Is there a simple way to create a hash of list of dictionaries?


code:
#!/usr/bin/python2
import json,pandas
from collections import OrderedDict
from bokeh.plotting import figure, show, output_file, ColumnDataSource
from bokeh.models import HoverTool
import math
user_by_country_count = pandas.read_csv('data.csv')

with open('countries.json','r') as f:
    geodata = json.load(f)

geodata_features = geodata['features']
country_xs = []
country_ys = []
country_names = []
country_num_users = []
country_colors = []
colors = ['#CCE5FF','#CCCCFF','#9999FF','#6666FF','#3333FF',
         '#0000FF','#0000CC','#000099','#000066','#0000CC']

for aCountry in geodata_features:
    cName = aCountry['properties']['name']
    country_names.append(cName)

    geometry_type = aCountry['geometry']['type']
    if geometry_type == "MultiPolygon":
        for poly_coords in aCountry['geometry']['coordinates']:
            coords = poly_coords[0]

            country_xs.append(map(lambda x:x[0],coords))
            country_ys.append(map(lambda x:x[1],coords))
    else:
        coords = aCountry['geometry']['coordinates'][0]
        country_xs.append(map(lambda x:x[0],coords))
        country_ys.append(map(lambda x:x[1],coords))

    if cName in user_by_country_count['Country'].values:
        num_users = user_by_country_count['Count'][user_by_country_count[user_by_country_count.Country==cName].index[0]]
        country_num_users.append(num_users)
        country_colors.append(colors[int(math.log(num_users))])
    else:
        country_num_users.append(0)
        country_colors.append("#00FF80")

source = ColumnDataSource(
    data = dict(
        x=country_xs,
        y=country_ys,
        color=country_colors,
        name=country_names,
        users=country_num_users,
    )
)
output_file("global.html", title="global.py example")
TOOLS="pan,wheel_zoom,box_zoom,reset,hover,save"
p = figure(title="Upwork Users Location", tools=TOOLS)
p.patches('x', 'y',
    fill_color='color', fill_alpha=0.7,
    line_color="white", line_width=0.5,
    source=source)
hover = p.select(dict(type=HoverTool))
hover.point_policy = "follow_mouse"
hover.tooltips = OrderedDict([
    ("Name", "@name"),
    ("Number of Users", "@users"),
])
show(p)

rawDescription: Python: bokeh not generating world's countries map as expected


code:
def display_node(node, indent=0):
    print ('.'*indent, node['class'])
    indent += 3
    for child in node['children']:
        display_node(child, indent)

# Create list of classes
classes = []
for item in lst:
    name = item['class']
    if name not in classes:
        classes.append(name)

treenodes = {}
root_node = None

for item in lst: # Create  tree nodes
    item['children'] = []
    name = item['class']
    treenodes[name] = item
    parent = item['parent']
    if parent not in classes: # parent is root node, create
        if parent not in treenodes:
            node = {}
            node['parent'] = None
            node['children'] = []
            node['class'] = parent
            root_node = node
            treenodes[parent] = node

# Connect parents and children
for item in lst: # Create  tree nodes
    parent = item['parent']
    parent_node = treenodes[parent]
    parent_node['children'].append(item)
display_node(root_node)

rawDescription: Construct hierarchy tree from python flat parent-children dict list


code:
class Wrapper:
    def wrap(self, obj):
        self.obj = obj
    def __getattr__(self, name):
        return getattr(self.obj, name)

a = list()
b = Wrapper()
b.wrap(a)

b.append(10)

rawDescription: What is the best pythonic way of wrapping an object?


code:
y = numpy.linspace(50.8,50.9,4800)
x = numpy.linspace(4.3,4.4,4800)
x,y = numpy.meshgrid(x,y)

rawDescription: Transforming coordinates in python

description: Transforming coordinates in python


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

tau = np.arange(-5, 5, 0.01)
a = 0.4

sigma = a*tau
x = 1/a*np.cosh(sigma)
y = 1/a*np.sinh(sigma)

fig, ax = plt.subplots()
ax.plot(x, y, c='black')

# approximate the curve by a cubic
dxds = np.poly1d(np.polyfit(sigma, x, 3)).deriv()
dyds = np.poly1d(np.polyfit(sigma, y, 3)).deriv()

xs, ys, dxs, dys = [], [], [], []
for s in np.linspace(-1, 1, 5):
    # evaluate the derivative at s
    dx = np.polyval(dxds, s)
    dy = np.polyval(dyds, s)

    # record the x, y location and dx, dy tangent vector associated with s
    xi = 1/a*np.cosh(s)
    yi = 1/a*np.sinh(s)
    xs.append(xi)
    ys.append(yi)
    dxs.append(dx)
    dys.append(dy)
    if s == 0:
        ax.text(xi-0.75, yi+1.5, '$u$', transform=ax.transData)
        ax.annotate('$a^{-1}$',
                    xy=(xi, yi), xycoords='data',
                    xytext=(25, -5), textcoords='offset points',
                    verticalalignment='top', horizontalalignment='left',
                    arrowprops=dict(arrowstyle='-', shrinkB=7))

ax.quiver(xs, ys, dxs, dys, scale=1.8, color='black', scale_units='xy', angles='xy',
          width=0.01)
ax.plot(xs, ys, 'ko')

# http://stackoverflow.com/a/13430772/190597 (lucasg)
ax.set_xlim(-0.1, x.max())
left, right = ax.get_xlim()
low, high = ax.get_ylim()
ax.arrow(0, 0, right, 0, length_includes_head=True, head_width=0.15 )
ax.arrow(0, low, 0, high-low, length_includes_head=True, head_width=0.15 )
ax.text(0.03, 1, '$t$', transform=ax.transAxes)
ax.text(1, 0.47, '$x$', transform=ax.transAxes)

plt.axis('off')
ax.set_aspect('equal')
plt.show()

rawDescription: How to totally remove x-axis (and y-axis) from the plot and also draw tangent lines at certain points using Python or R-programming?

description: Totally remove x-axis (and y-axis) from the plot and also draw tangent lines at certain points using Python or R-programming


code:
sys.stdout.write('\r' + str(hpi) + ' ' * 20)
sys.stdout.flush() # important

rawDescription: python overwrite previous line

description: Python overwrite previous line


code:
cond2 = (SPN >= -alpha) & (SPN <= 0)
SPN[cond2] = -np.cos(SPN[cond2]*np.pi/(2*alpha))

rawDescription: Apply formula to specific numpy array values


code:
db.coll.group(
    key='function(doc) { return {"dt": doc.dt.toDateString()} }',
    condition={'dt': {'$gt': datetime_obj_30_days_ago}},
    initial={'downloads': 0},
    reduce='function(curr, prev) { prev.downloads = Math.max(curr.downloads, prev.downloads) }'
)

rawDescription: MongoDB: Limiting results from a $gt query (from pymongo)


code:
points = [(a.time, a.argv) for a in l]
plt.plot(points, "rs-")

rawDescription: How to connect points in python plot?

description: Connect points in python plot


rawDescription: Creating sub-lists from a list

description: Creating sub-lists from a list


code:
def after_login(self, response):
    # check login succeed before going on
    if "Invalid user or password. Please try again." in response.body:
        self.logger.error("Login failed")
    for href in response.selector.xpath('//a/@href').extract():
        url = response.urljoin(href)
        yield request(url, callback=self.parse_item)

rawDescription: Scrapy Link Extractors

description: Scrapy Link Extractors


code:
import netifaces
def is_connected_to_an_internet():
    ifaces = netifaces.interfaces()
    for iface in ifaces:
        addrs = netifaces.ifaddresses(iface)
        for addr in addrs.get(netifaces.AF_INET, []):
            if addr['addr'].startswith('127'): continue
            return True
        for addr in addrs.get(netifaces.AF_INET6, []):
            if addr['addr'] == '::1': continue
            if addr['addr'].lower().startswith('fe80'): continue
            return True
    return False

rawDescription: System network connectivity? WITHOUT reaching out [Windows, MacOS, Ubuntu]


code:
import time, sys
import urllib2
url = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio1_mf_p"
print ("Connecting to "+url)
response = urllib2.urlopen(url, timeout=10.0)
fname = "Sample"+str(time.clock())[2:]+".wav"
f = open(fname, 'wb')
block_size = 1024
print ("Recording roughly 10 seconds of audio Now - Please wait")
limit = 10
start = time.time()
while time.time() - start < limit:
    try:
        audio = response.read(block_size)
        if not audio:
            break
        f.write(audio)
        sys.stdout.write('.')
        sys.stdout.flush()
    except Exception as e:
        print ("Error "+str(e))
f.close()
sys.stdout.flush()
print("")
print ("10 seconds from "+url+" have been recorded in "+fname)

#
# here run the finger print test to identify the audio recorded
# using the sample you have downloaded in the file "fname"
#

rawDescription: Record and Recognize music from URL

description: Record and Recognize music from URL


code:
import matplotlib.pyplot as plt
plt.rcParams['savefig.dpi'] = 500

rawDescription: Increase resolution of figure for saving


code:
from twisted.protocols.basic import Int32StringReceiver

class YourProtocol(Int32StringReceiver):
    def connectionMade(self):
        self.sendString('This string will automatically have its length '
            'prepended before it\'s sent over the wire!')

    def stringReceived(self, string):
        print ('Received %r, which came in with a prefixed length, but which '
            'has been stripped off for convenience.' % (string,))

rawDescription: Reading fixed amount of bytes from socket with python asyncore


code:
import collections as co

def countWords(arg):
    dd = co.defaultdict(int) # since we want counts we use int
    for i in arg.split():    # split on whitespace
        dd[i] += 1           # when a new key is encountered the default value is entered
    return dd

rawDescription: Python: dictionaries and word counting

description: Python: dictionaries and word counting


code:
oneLat = ['53.8041778', '59.8149016457', '51.1289412359']
oneLong = ['1.5192528', '1.57945488999', '8.57262235411']

# Do the negation here, instead of in the string formatting later
coordPairs = zip((-float(x) for x in oneLong), (float(x) for x in oneLat))

with open("file",'w') as f:
    f.write(xmlHeaderStuff) # I've left out your string literal for brevity

    #I assume the purpose of the two loops, the while loop and for loop,
    #is for the purpose of repeating the group of 3 coord pairs each time?

    for i in range(len(coordPairs)):
        for coord in coordPairs:
            f.write("\t\t<coordinates>{}, {}</coordinates>\n".format(*coord))
            # break <-- this needs to go

    f.write(xmlFooterStuff)

# f.close() <-- this is unnecessary, since the `with` block takes care of
# file closing automatically

rawDescription: Iterating through a list or tuple?

description: Iterating through a list or tuple


code:
def create_point_cloud_vectorized(self,depth_image):
    im_shape = depth_image.shape

    # get the depth
    d = depth_image[:,:,0]

    # replace the invalid data with np.nan
    depth = np.where( (d > 0) & (d < 255), d /256., np.nan)

    # get x and y data in a vectorized way
    row = (np.arange(im_shape[0])[:,None] - self.cx) / self.fx * depth
    col = (np.arange(im_shape[1])[None,:] - self.cy) / self.fy * depth

    # combine x,y,depth and bring it into the correct shape
    return array((row,col,depth)).reshape(3,-1).swapaxes(0,1)

rawDescription: Optimize numpy point cloud creation script


code:
# Identify the matching rows
matches = df['column_1'].isin(my_list)
# Set the column_2 entries to column_1 in the matching rows
df.loc[matches,'column_2'] = df.loc[matches,'column_1']

rawDescription: Modify a Data Frame column with list comprehension


code:
url(r'^items/(?P<year>\d{4})/week/(?P<week>\d{1,2})/$', ItemArchiveView.as_view(
    week_format='%W'
)),

rawDescription: Monday as first day of week for WeekArchiveView


rawDescription: How to make this python script memory efficient

description: Make this python script memory efficient


code:
import re
title = "Marielizabeth's Diary Chapter 9"
re.sub('Chapter (\d)', lambda m: "0" + m.group(1), title)

rawDescription: Get characters after a word in Python

description: Get characters after a word in Python


code:
receiveddata=ser.readline().strip()
for r in receiveddata:
     firstdata=r[0]
     seconddata=r[1]
if firstdata=='yourdata':
      fun1()

rawDescription: how to separate 1st byte from receiveddata of serial port in python

description: Separate 1st byte from receiveddata of serial port in python


code:
def tuple2dict(data):
    d = {}
    for item in data:
        if len(item) == 1 and isinstance(item, tuple):
            # remove the nested structure, you may need a loop here
            item = item[0]
            key = item[0]
            value = item[1]
            d[key] = value
            continue
        key = item[0]
        value = item[1]
        if hasattr(value, '__getitem__'):
            value = tuple2dict(value)
        d[key] = value
    return d

rawDescription: Python: Convert a nested list of tuples of lists into a dictionary?


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QHBoxLayout(self)
        self.button = QtGui.QToolButton(self)
        self.button.setPopupMode(QtGui.QToolButton.MenuButtonPopup)
        self.button.setMenu(QtGui.QMenu(self.button))
        self.textBox = QtGui.QTextBrowser(self)
        action = QtGui.QWidgetAction(self.button)
        action.setDefaultWidget(self.textBox)
        self.button.menu().addAction(action)
        layout.addWidget(self.button)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(100, 60)
    window.show()
    sys.exit(app.exec_())

rawDescription: Qt/PyQt: How do I create a drop down widget, such as a QLabel, QTextBrowser, etc.?


code:
d = unit_d.reset_index()
{k: v.tolist() for k, v in d.groupby("store_nbr")["item_nbr"]}

rawDescription: Pivot Table to Dictionary

description: Pivot Table to Dictionary


code: pip --version

rawDescription: Which version of Pip to use with my Python installs?


code:
def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    initial = super(SignUpView, self).get_initial()

    initial['my_form_field1'] = self.request.something

    return initial

rawDescription: Django: How to pre-populate FormView with dynamic (non-model) data?


code: p4 = map(float, searchlines[i+1].split()[1:3])

rawDescription: Print only a part of a whole line in Python


code:
getattr(__builtins__, 'int')
foo = getattr(__builtins__, 'int')
isinstance(foo, type)

rawDescription: Get int-type from 'int' string

description: Get int-type from 'int' string


code:
np.frombuffer(buffer("\0\0"), dtype=np.float16)[0]
np.frombuffer(buffer("\x00\x3c"), dtype=np.float16)[0]

rawDescription: Half-Precision (2 byte) cast to Float in Python


code:
import datetime

def search_results(request):
    from_age = form.cleaned_data['from_age']
    to_age = form.cleaned_data['to_age']

    now = datetime.date.today()
    from_date = datetime.date(now.year-int(to_age), now.month, now.day)
    to_date = datetime.date(now.year-int(from_age), now.month, now.day)

    query_set = profiles.objects.filter(gender=gender,
                                        birthday__range=(from_date, to_date))

rawDescription: search profiles between two ranges

description: Search profiles between two ranges


code:
TempDay = pd.DataFrame(TemperatureArray)
TempDay['Dates'] = AllDays
TempDay.to_csv('C:\MyFile.csv')

rawDescription: Python: Writing and printing to CSV a dataframe


code:
import pandas as pd
import numpy as np

N = 10
M = 0.8

df = pd.DataFrame(data={'Col1':np.random.random(N), 'Col2':np.random.random(N),
                        'Col3':np.random.random(N), 'Col4':np.random.random(N)})

cols = ['Col1', 'Col2', 'Col3']

mask = (df[cols] > M).any(axis=1)

print(df[mask].index)
# Int64Index([0, 1, 4, 5, 6, 7], dtype='int64')

rawDescription: select rows from dataframe where any of the columns is higher 0.001

description: Select rows from dataframe where any of the columns is higher 0.001


code:
from PIL import Image

# Separate RGB arrays
im = Image.open(file(filename, 'rb'))
R, G, B = im.convert('RGB').split()
r = R.load()
g = G.load()
b = B.load()
w, h = im.size

# Convert non-black pixels to white
for i in range(w):
    for j in range(h):
        if(r[i, j] != 0 or g[i, j] != 0 or b[i, j] != 0):
            r[i, j] = 255 # Just change R channel

# Merge just the R channel as all channels
im = Image.merge('RGB', (R, R, R))
im.save("black_and_white.png")

rawDescription: Python - Remove(convert to white) non black pixels of an image


code:
from app.models import Result

optionResult = someTestsThatRuns
reverseResult = someOtherTestThatRuns
c = Result()
c.options = optionResult
c.reverse = reverseResult
c.save()

rawDescription: Can the models.py file created by Django be used by another python file to fill in a database?


code:
from django.db.models import Count
statuses = Status.objects.all().annotate(Count('task'))

rawDescription: Django: Display a model and a count of how often another model uses it


code:
scores = []
for n in range(class_size):
    scores.append(int(raw_input("Student {0}: ".format(n+1))))
average = sum(scores) / float(len(scores))

rawDescription: How to automatically assign input?

description: Automatically assign input


code:
import os
files = os.listdir('.')
natsort(files)
index = 0
for filename in files:
    os.rename(filename, str(index).zfill(7)+'.png')
    index += 1

rawDescription: batch renaming 100K files with python

description: Batch renaming 100K files with python


code:
import collections
q = collections.deque(["herp", "derp", "blah", "what", "da.."])
q.appendleft('wuggah')
q.pop()
q

rawDescription: Add entry to list and remove first one in Python


code:
from PySide import QtCore

class A(QtCore.QObject):
    status = QtCore.Signal(bool)

    def func1(self, *args):
        self.status.emit(*args)

# later...

@QtCore.Slot(bool)
def update(self, bool_args):
    pass  # insert what you need to do here.

rawDescription: Send signal with boolean argument

description: Send signal with boolean argument


code:
mdb.models[name].SubstructureGenerateStep(modeRange=((1, 60, 1), ), name=
    name, previous=previousName, retainedEigenmodesMethod=MODE_RANGE,
    substructureIdentifier=1)

rawDescription: Creating a SubstructureGenerateModes object in ABAQUS?


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)

Z = -(abs(X) + abs(Y))

## 1) Initial surface
# Flatten mesh arrays, necessary for plot_trisurf function
X = X.flatten()
Y = Y.flatten()
Z = Z.flatten()

# Plot initial 3D surface with triangles (more flexible than quad)
#surfi = ax.plot_trisurf(X, Y, Z, cmap=cm.jet, linewidth=0.2)

## 2) Cut off
# Get desired values indexes
cut_idx = np.where(Z > -5)

# Apply the "cut off"
Xc = X[cut_idx]
Yc = Y[cut_idx]
Zc = Z[cut_idx]

# Plot the new surface (it would be impossible with quad grid)
surfc = ax.plot_trisurf(Xc, Yc, Zc, cmap=cm.jet, linewidth=0.2)

# You can force limit if you want to compare both graphs...
ax.set_xlim(-5,5)
ax.set_ylim(-5,5)
ax.set_zlim(-10,0)

plt.show()

rawDescription: How to do a 3D revolution plot in matplotlib?

description: Do a 3D revolution plot in matplotlib


code:
from ftplib import FTP
from time import sleep

ftp = FTP('localhost')
ftp.login()

def changemon(dir='./'):
    ls_prev = set()

    while True:
        ls = set(ftp.nlst(dir))

        add, rem = ls-ls_prev, ls_prev-ls
        if add or rem: yield add, rem

        ls_prev = ls
        sleep(5)

for add, rem in changemon():
    print('\n'.join('+ %s' % i for i in add))
    print('\n'.join('- %s' % i for i in remove))

ftp.quit()

rawDescription: Monitor remote FTP directory

description: Monitor remote FTP directory


code:
if formset.is_valid():
    formset.save()
    return HttpResponseRedirect("")

rawDescription: Django form submission not refreshing what user sees


code:
begin = int(input('Enter begin: '))
end = int(input('Enter end: '))

palindromes = 0
#Add your code here. You will want to start with a "for x in range" style loop.
for x in range(begin, end):
    if str(x) == str(x)[::-1]:
        palindromes += 1

print('There are', palindromes, 'palindrome(s) between', begin, 'and', end)

rawDescription: Palindrome Checker for numbers

description: Palindrome Checker for numbers


code: my_instance = MyModel(email='test')

rawDescription: Django Prevent Automatic Save During Object.Create


code:
n = range(16)
s = ''.join(map(chr, n))
np.fromstring(s, dtype=np.uint64)
sum((256**i)*x for i,x in enumerate(n[:8]))
sum((256**i)*x for i,x in enumerate(n[8:]))

rawDescription: typecast bytes to array of uint64 in Python+numpy

description: Typecast bytes to array of uint64 in Python+numpy


code:
connector = aiohttp.ProxyConnector(proxy="http://some.proxy.com")
session = aiohttp.ClientSession(connector=connector)
async with session.post("http://example.com/post", data=b"binary data") as resp:
    print(resp.status)

session.close()

rawDescription: send aiohttp post request with headers through proxy connection

description: Send aiohttp post request with headers through proxy connection


code:
a = 256
b = 256
a is b
a = 257
b = 257
a is b
a = "hey"
b = "hey"
a is b
a = "hey!"
b = "hey!"
a is b

rawDescription: Create two immutable objects with the same value in Python


code:
outputfile = open('output.plist', 'w')
outputfile.write(p["ProductVersion"])
outputfile.close()

rawDescription: Save python plistlib data

description: Save python plistlib data


code:
def p():
    print(p.__dict__.get('smuggled_value',0))

def q():
    p.smuggled_value = getattr(p,'smuggled_value',0) + 1

rawDescription: Accessing to a nonlocal variable by the following limitations


code:
your_list = ['one', 'two', 'one']
len(your_list) != len(set(your_list))

rawDescription: In python, how to check if there are any duplicates in list


code: pytest_plugins = ['module1', 'module2']

rawDescription: Splitting a conftest.py file into several smaller conftest-like parts


rawDescription: Convert String to Decimal in Python

description: Convert String to Decimal in Python


code:
import pandas as pd

df = pd.DataFrame(some_list, index=None)

df = df.groupby(by='race').count().transpose()

for col in df.columns:
    rw = df.loc[df[col] == 0]
    dic = {rw.index[0]: 0, 'race': col}
    some_list.append(dic)

# output:
# some_list = [
#     {'blond': 3, 'race': 'WHITE'},
#     {'black': 4, 'race': 'WHITE'},
#     {'light brown': 6, 'race': 'WHITE'},
#     {'black': 2, 'race': 'AFRICAN_AMERICAN'},
#     {'blond': 1, 'race': 'AFRICAN_AMERICAN'},
#     {'dark brown': 1, 'race': 'AFRICAN_AMERICAN'},
#     {'light brown': 0, 'race': 'AFRICAN_AMERICAN'},
#     {'dark brown': 0, 'race': 'WHITE'}
# ]

rawDescription: Python transform list of dictionaries into another list of dictionaries


code:
def random_color():
    rgbl=[255,0,0]
    random.shuffle(rgbl)
    return tuple(rgbl)

rawDescription: Generate random colors (RGB)

description: Generate random colors (RGB)


rawDescription: Python Regex For Capturing Dates in Url

description: Python Regex For Capturing Dates in Url


code:
X[index] = set()    # because the default set is the empty set
X[index] = set('')  # because it iterates the empty string!
X[index] = {x for x in []}  # "set comprehension" version

rawDescription: Understanding Python list and set

description: Understanding Python list and set


code:
def __str__(self):
     return "foo"

rawDescription: How do I change the string representation of a Python class?

description: Change the string representation of a Python class


code:
class MyModelAdmin(admin.ModelAdmin):
    ...

    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return super(MyModelAdmin, self).get_readonly_fields(request, obj)
        else:
            return ('created_at', 'created_by')

rawDescription: Understanding django admin readonly_fields


code:
query = None
for tag in F:
    if query is None:
        query = Q(tags=tag)
    else:
        query &= Q(tags=tag)

PhotoSet.objects.filter(query)

rawDescription: django conjunctive filter __in query

description: Django conjunctive filter __in query


code: desired_array = [int(numeric_string) for numeric_string in current_array]

rawDescription: Python: How do I convert an array of strings to an array of numbers?


code: pd.merge(df1, df2, on='record_ID', how='left')

rawDescription: Joining 2 dataframes on a specific column with IDs


code:
from django.core import management
management.call_command('runserver')

rawDescription: Importing and running Django development server


code:
import math

eaters = input("How many people are attending the party?")

pieces = input("How many pieces will everyone eat on average?")

pizzas = float(eaters) * float(pieces)
orders_needed = math.ceil(pizzas/8)
print(orders_needed)

rawDescription: How to get a pizza program to round to a full pizza In PYTHON

description: Get a pizza program to round to a full pizza In PYTHON


code:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('stat.ripe.net', 43))
sock.sendall('as3333\r\n'.encode('utf-8'))

response = b''
while True:
    tmp = sock.recv(65536)
    if not tmp:
        break
    response += tmp

print(response.decode('utf-8'))
sock.close()

rawDescription: Python socket strange behavior

description: Python socket strange behavior


code:
# just join the strings...
showmessage = message + " from " + name

# or string formatting
showmessage = "{0} from {1}".format(message,name)

rawDescription: Python convert Json to string decoding

description: Python convert Json to string decoding


code:
class FTPConnection(object):
    def __init__(self, server):
        self._ftp = FTP(server)

    def connect(self):
       self._ftp.login()
       self._ftp.cwd('/path')

    def getFileList():
        files = self._ftp.nlst()
        print(files)

ftp = FTPConnection('server')
ftp.connect()
ftp.getFileList()

rawDescription: Function variable scope in python

description: Function variable scope in python