code:
class BaseHandler(webapp.RequestHandler):

    def get(self, CSIN=None):
        self.response.headers['Content-Type'] = 'text/html'
        render('Views/header.html', self, {'title' : 'Store'})
        self.response.out.write('<h1>%s</h1> '% self.h1(CSIN))
        self.do_body(CSIN)
        render('Views/footer.html', self, {})

class MainPage(BaseHandler):

    def h1(self, CSIN):
        return 'This is going to be the best Store app EVER!'

    def do_body(self, CSIN):
        items = Item.all().order('name').fetch(10)
        render('Views/table.html', self, {'items': items})

class Detail(BaseHandler):

    def h1(self, CSIN):
        return 'DETAILS %s' % CSIN

    def do_body(self, CSIN):
        # no risk whatsoever of SQL injection here;-)
        item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", int(CSIN)).get()
        if (item):
            render('Views/item_detail.html', self, {'item': item})
        else:
            render('Views/item_not_found.html', self, {'CSIN': CSIN})

rawDescription: Google App Engine: How can I DRY this basic request handling?


code:
from win32com.client import Dispatch
wkbk1 = "...\workbook1.xlsx"
wkbk2 = "...\workbook2.xlsx"
excel = Dispatch("Excel.Application")
excel.Visible = 1
source = excel.Workbooks.Open(wkbk1)
excel.Range("A1:A3").Select()
excel.Selection.Copy()
copy = excel.Workbooks.Open(wkbk2)
excel.Range("A1:A3").Select()
excel.Selection.PasteSpecial(Paste=-4163)

rawDescription: How to paste special in excel with python

description: Paste special in excel with python


code:
curve_1.extend(curve_2)
curve_1.show()

rawDescription: Plotting 2 or more functions in the same graph using sympy (python)


code: ('a' or 'e' or 'i' or 'o' or 'u')

rawDescription: Why does one method for comparing strings work, but another doesn't?


code:
happy_set = set([":)",":-)","=)",":D",":-D","=D"])
sad_set = set([":(",":-(","=("])

# happy is your existing set of potentially happy tweets. To remove any tweets with sad tokens...
happy = [tweet for tweet in happy if sad_set.isdisjoint(set(tweet.split()))]

rawDescription: Pythonic way to find 2 items from two lists existing in a another list


code:
# Setup
dropdown_id = 'DropDownList1'
button_id = 'Button1'
table_id = 'table1'
browser = webdriver.Chrome('C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe')
browser.get(url)

# Data getting
dropdown = _browser.find_element_by_id(dropdown_id)
for option in dropdown.dropdown.find_elements_by_tag_name('option'):
    select = Select(browser.find_element_by_id(dropdown_id))
    select.select_by_value(option.text)
    button = browser.find_element_by_id(button_id)
    button.click()
    table = browser.find_element_by_id(table_id)
    html = table.get_attribute('outerHTML')
browser.close()

rawDescription: Selecting from dropdown list using urllib


code:
mainWidget.setUpdatesEnabled(False)
# do a bunch of operations that would trigger expensive events
# like repaints
mainWidget.setUpdatesEnabled(True)

rawDescription: Turn off PyQt Event Loop While Editing Table


rawDescription: Make format string align integer after character


code:
with open('one.txt', 'r') as in_file, open('two.txt', 'w') as out_file:
    for in_string in in_file.readlines():
        out_file.write(in_string.split()[0])
        out_file.write('\n')

rawDescription: In python, how to loop and get from a file a particular integers or strings?


code:
import argparse
import sys

class Extender(argparse.Action):
    def __call__(self,parser,namespace,values,option_strings=None):
        #Need None here incase `argparse.SUPPRESS` was supplied for `dest`
        dest = getattr(namespace,self.dest,None)
        #print dest,self.default,values,option_strings
        if(not hasattr(dest,'extend') or dest == self.default):
            dest = []
            setattr(namespace,self.dest,dest)
            #if default isn't set to None, this method might be called
            # with the default as `values` for other arguements which
            # share this destination.
            parser.set_defaults(**{self.dest:None})

        try:
            dest.extend(values)
        except ValueError:
            dest.append(values)

        #another option:
        #if not isinstance(values,basestring):
        #    dest.extend(values)
        #else:
        #    dest.append(values) #It's a string.  Oops.

def new_parser(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('foo', nargs='*',action=Extender)
    parser.add_argument('--foo', nargs='*', dest='foo', action=Extender)
    parser.set_defaults(foo = [['spam']])
    return parser.parse_args(args.split())

tests = {'a b c --foo 1 --foo 2 --foo 3':['a','b','c','1','2','3'],
         '':[['spam']],
         'a b c --foo 1 2 3':['a','b','c','1','2','3'],
         '--foo 1':['1'],
         'a':['a']}

for s,r in tests.items():
    print ( "parsing: {0}".format(s) )
    args = new_parser(s)
    if(args.foo != r):
        print ("ERROR")
        print (args.foo)
        print (r)
        sys.exit(1)
    print ( args )
    print ('*'*80)

rawDescription: argparse: How can I allow multiple values to override a default

description: Argparse: How can I allow multiple values to override a default


code:
def defaultval(error, value):
    def decorator(func):
            def defaulted(*args, **kwargs):
                    try:
                            return func(*args, **kwargs)
                    except error:
                            return value
            return defaulted
    return decorator
@defaultval(NameError, "undefined")
def get_var():
    return name
get_var()

rawDescription: Is there an analogue of this function in Python standard modules?


code:
total_campaigns = {}
for day in days:
    total_campaigns[day] = Email.objects.filter(day_of_week=day).count()

rawDescription: Filtering Objects in Database by Keyword


rawDescription: How to Swap First and Last Characters from Input in Python


code:
fig, ax = plt.subplots()
fig.subplots_adjust(left=0.2)  #Adjust 0.2 to find the right margin for your plot

rawDescription: y ticks cutting off in matplotlib in ipython

description: Y ticks cutting off in matplotlib in ipython


code:
def endOverlap(a, b):
    for i in range(0, len(a)):
        if b.startswith(a[-i:]):
            return i
    return 0

a = "Hey there"
b = "there is a ball"
c = "here is a ball"
d = "not here is a ball"

print(a, b, endOverlap(a, b))
print(a, c, endOverlap(a, c))
print(a, d, endOverlap(a, d))

rawDescription: Check if string ends with the beginning of another string


code:
TIMEOUT= 10 #seconds
from datetime import datetime, timedelta
from time import sleep

timeout= datetime.now() + timedelta(seconds=TIMEOUT)

socket1 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
socket2 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

socket2.bind(socket2_filename)

s1_done= False

while (not s1_done) and (datetime.now() < timeout):
    try:
        socket1.connect(socket1_filename)
        s1_done= True
    except socket.error:
        sleep(1)

if not s1_done:
    raise Exception("Failed to connect")

rawDescription: Interconnection between two processes

description: Interconnection between two processes


code:
class BasePlayer(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)
    hash = models.CharField(max_length=128, null=True, blank=True)
    bookmark_url = models.CharField(max_length=300, null=True, blank=True)

    class Meta:
        abstract = True

class Player(BasePlayer):
    """ player model """
    pass

class BookmarkPlayer(BasePlayer):
    """ bookmark player model """
    pass

rawDescription: Create a new model which have all fields of currently existing model


code:
p = subprocess.Popen(['sed', '-l', 's/a/x/g'],
                     stdout=subprocess.PIPE,
                     stdin=subprocess.PIPE)

rawDescription: Reading/writing to a Popen() subprocess

description: Reading/writing to a Popen() subprocess


code:
total = 0
total_transaction = 0
count = 0
for rec in records:
    if rec[1] == branch:
        total = total + rec[2]
        total_transaction = total_transaction + rec[3]
        count += 1
if count > 0:
    average = total/count
    ave_transaction = total_transaction/count
else:
    average = 0
    ave_transaction = 0

rawDescription: How to calculate the average from a list of records

description: Calculate the average from a list of records


code: round(random.uniform(num1, num2), 6)

rawDescription: How do you generate a random double between these points?

description: Generate a random double between these points


code:
arrays = []
with open('normRowsRaw.txt') as f:
    f = f.read().split(',')
    for n in f:
        arrays.append(float(n.strip()))

rawDescription: Import a txt file into a 2d list of floats


code:
class Foo(object):
    def method(self, bar):
        def inner(magic):
            class Madness(object):
                def __init__(inself, foo): inself.foo = foo
            return Madness(magic)
        return inner(bar)

rawDescription: Is it possible to have a function within a method in Python?


code:
import os
import csv

path=os.getcwd()

filenames = os.listdir(path)

for filename in filenames:

    if filename.endswith('.csv'):
        r=csv.reader(open(filename))
        new_data = []
        for row in r:
            row[-1] = row[-1].replace("S-D", "S")
            new_data.append(row)

        newfilename = "".join(filename.split(".csv")) + "_edited.csv"
        with open(newfilename, "w") as f:
            writer = csv.writer(f)
            writer.writerows(new_data)

rawDescription: Batch editing of csv files with Python

description: Batch editing of csv files with Python


code:
from nose.tools import nottest

@nottest
def test_server_init():
    drop_all_tables()

rawDescription: Prevent a function or a file from being run with nose?


code:
from pylab import *
import matplotlib.pyplot as plt
from datetime import datetime
import time
from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
     DayLocator, MONDAY
from matplotlib.finance import candlestick,\
     plot_day_summary, candlestick2

mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays    = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')      # e.g., 12

#starting from dates expressed as strings...
Date1 = '01/01/2010'
Date2 = '02/01/2010'
#...you convert them in float numbers....
Date1 = date2num(datetime.strptime(Date1, "%d/%m/%Y"))
Date2 = date2num(datetime.strptime(Date2, "%d/%m/%Y"))
#so redefining the Prices list of tuples...
Prices = [(Date1, 1.123, 1.212, 1.463, 1.056), (Date2,1.121, 1.216, 1.498, 1.002)]
#and then following the official example.
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
candlestick(ax, Prices, width=0.6)

ax.xaxis_date()
ax.autoscale_view()
plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

plt.show()

rawDescription: How to create a candlestick chart with Matplotlib (Python 2.7) and your own data

description: Create a candlestick chart with Matplotlib (Python 2.7) and your own data


rawDescription: Python String to List with RegEx

description: Python String to List with RegEx


code:
import time
import Tkinter as tk

import threading

class MyTimer(threading.Thread):

    def __init__(self, t):
        super(MyTimer,self).__init__()
        self.txt = t
        self.running = True

    def run(self):
        while self.running:
            self.txt['text'] = time.time()

mgui = tk.Tk()
mgui.title('Test')

txt = tk.Label(mgui, text="time")
txt.grid(row=0,columnspan=2)

timer = None
def cmd1():
    global timer
    timer = MyTimer(txt)
    timer.start()
def cmd2():
    global timer
    if timer:
        timer.running = False
        timer= None

btn = tk.Button(mgui, text="Start", command =cmd1)
btn.grid(row=1,column=1)
btn2 = tk.Button(mgui, text="Stop", command =cmd2)
btn2.grid(row=1,column=2)

mgui.mainloop()

rawDescription: How to add timer with start/stop GUI in python

description: Add timer with start/stop GUI in python


code:
import pandas as pd
import datetime

dateparse = lambda x: pd.datetime.strptime(x, '%m/%d/%Y')

df = pd.read_csv('Sample.csv', index_col='date',
                 parse_dates=[0], date_parser=dateparse)

def last52weeks(x):
    ser = df['sales'][(df.index >= x.name - datetime.timedelta(weeks=52)) &
                      (df.index <= x.name) &
                      (df['wholesaler'] == x[0]) &
                      (df['product'] == x[1])]
    return ser.mean()

df['avg_sales_last52weeks'] = df.apply(last52weeks, axis=1)
df = df.sort_values(['wholesaler', 'product'])

#             wholesaler product  sales    avg_sales_last52weeks
# date
# 2013-12-31       11209   UME24      4                      4.0
# 2012-12-31       13131   UPE55      1                      1.0
# 2013-02-23       13131   UPE55   1156                    578.5
# 2013-04-24       13131   UPE55      1                    386.0
# 2013-12-18       52237   UPE54      9                      9.0
# 2013-12-31       52237   UPE54      1                      5.0
# 2013-12-19       53929   UME24      1                      1.0
# 2012-12-31       53929   UPE54      4                      4.0
# 2013-12-31       82204   UPE55      9                      9.0
# 2013-12-01       83389   UPE54      9                      9.0
# 2013-12-17       83389   UPE54      1                      5.0

rawDescription: How to find the average of last 52 weeks sales at each time in python

description: Find the average of last 52 weeks sales at each time in python


code:
import os

def list_files(dir):
    r = []
    subdirs = [x[0] for x in os.walk(dir)]
    for subdir in subdirs:
        files = os.walk(subdir).next()[2]
        if (len(files) > 0):
            for file in files:
                r.append(subdir + "/" + file)
    return r

rawDescription: Python: Iterate through folders, then subfolders and print filenames with path to text file


code:
import numpy as np
right = np.array([8,5,9,2,4])
np.vstack([np.arange(1, len(right) + 1), right]).T

rawDescription: addding a counting colum to a numpy array in python

description: Addding a counting colum to a numpy array in python


code:
from django.conf import settings

urlpatterns += patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)

rawDescription: Serving static media during Django development: Why not MEDIA_ROOT?


code:
end_trimm = 3
myList = myList[:-end_trimm]

rawDescription: How to delete a fixed number of items from end of list in python

description: Delete a fixed number of items from end of list in python


code:
s=subprocess.Popen(['coresendmsg',
    'exec',
    '-s', '47854',
    'node=2',
    'num=1001',
    'cmd=ifconfig eth0 192.168.0.1'])

rawDescription: Script arguments not parsed correctly when script called from Popen()


code:
from collections import defaultdict, OrderedDict

dic = defaultdict(OrderedDict)
rowKeys = ['1','2','3']
columnKeys = ['alfa', 'omega', 'bravo', 'charlie']

# Filling up the dictionary with values
from random import randrange

for rKey in rowKeys:
    for cKey in columnKeys:
        dic[rKey][cKey] = randrange(50)

rawDescription: Python dict: get values sorted by a list of keys


code:
import numpy as np
array1 = np.arange(12).reshape((2, 6))
array2 = np.ones(18).reshape((3, 6))
with open('outputfile.csv', 'ab') as f:
    np.savetxt(f, array1, delimiter=',')
    np.savetxt(f, array2, delimiter=',')

rawDescription: Saving several numpy arrays to one csv

description: Saving several numpy arrays to one csv


code:
#!/usr/bin/env python3
#-*- coding:utf-8 -*-

import os.path
import urllib.request
from urllib.parse import urlencode
from http.cookiejar import CookieJar,MozillaCookieJar

cj = MozillaCookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)

cookie_file=os.path.abspath('./cookies.txt')

def load_cookies(cj,cookie_file):
    cj.load(cookie_file)
def save_cookies(cj,cookie_file):
    cj.save(cookie_file,ignore_discard=True,ignore_expires=True)

def dorequest(url,cj=None,data=None,timeout=10,encoding='UTF-8'):
    data = urlencode(data).encode(encoding) if data else None

    request = urllib.request.Request(url)
    request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')
    f = urllib.request.urlopen(request,data,timeout=timeout)
    return f.read()

def dopost(url,cj=None,data=None,timeout=10,encoding='UTF-8'):
    body = dorequest(url,cj,data,timeout,encoding)
    return body.decode(encoding)

rawDescription: how can set headers (user-agent), retrieve a web page, capture redirects and accept cookies?

description: How can set headers (user-agent), retrieve a web page, capture redirects and accept cookies


code:
import dis
def foo():
    (a, b) = (2, 3)

dis.dis(foo)

rawDescription: Lifetime of variables created when assigning to something that looks like a tuple


code:
sio = StringIO()
PandasDataFrame = pandas.DataFrame(self.csvdict)
PandasWriter = pandas.ExcelWriter(sio, engine='xlsxwriter')
PandasDataFrame.to_excel(PandasWriter, sheet_name=sheetname)
PandasWriter.save()

sio.seek(0)
workbook = sio.getvalue()

response = StreamingHttpResponse(workbook, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename

rawDescription: Django Pandas to http response (download file)


code:
import urllib
from twisted.internet import reactor
from twisted.web import client

client.getPage('http://requestb.in/vvs5qdvv', method='POST',
               headers={'Content-Type': 'application/x-www-form-urlencoded'},
               postdata=urllib.urlencode({'doc':'data'}));

reactor.run()

rawDescription: Is there any way to async post some data with twisted?


code:
AUTH_SERVER_URL = "https://login.microsoftonline.com/common/oauth2/authorize"
AUTH_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/token"

rawDescription: OneDrive API Python SDK - points to login.live.com not mydomain.sharepoint.com


code:
default_address = relationship('Address',
                       secondary=ACC_ADD_TABLE,
                       primaryjoin="acc.c.id==acc_add_rel.c.acc_id",
                       secondaryjoin="and_(address.c.id==acc_add_rel.c.add_id, address.c.type=='default')",
                       #uselist = True,
                       )

rawDescription: Use of M2M Table and relationship to get specific data in sqlalchemy


code:
def fill_empty(parent,row,column):
    empty = Label(parent)
    empty.grid(row=row,column=column)
    return empty

rawDescription: Python tkinter same Label called multiple times


rawDescription: Executing a python line of code using eval() from a map


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

# make the data as sequential sections of a circle
theta = np.linspace(np.pi, 0, 120)
y = np.reshape(np.sin(theta), (10,12))
x = np.repeat(np.arange(12)[None,:], 10, axis=0)

# fit the line
m = lambda x: np.mean(x, axis=1)
beta = ( m(y*x) - m(x)*m(y) )/(m(x*x) - m(x)**2)
alpha = m(y) - beta*m(x)

# plot the data and fits
plt.plot([y[:,i] for i in range(12)], ".")  # plot the data
plt.gca().set_color_cycle(None) # reset the color cycle
fits = alpha[:,None] + beta[:,None]*x  # make lines from the fits for the plots
plt.plot(fits.T)
plt.show()

rawDescription: Simultaneously fit linearly every line of a 2d numpy array


code:
def enthread(target, args):
    q = queue.Queue()
    def wrapper():
        q.put(target(*args))
    t = threading.Thread(target=wrapper)
    t.start()
    return q

q1 = enthread(target = derivative,  args=(lst[0], var))
q2 = enthread(target = derivative,  args=(lst[2], var))
return [q1.get(), '+', q2.get()]

rawDescription: return values with thread.start() in python (using queue)

description: Return values with thread.start() in python (using queue)


code:
import Tkinter as tk

tk.Tk()

textbox = tk.Text(height=10, width=10)
textbox.insert(tk.END, "Default")
textbox.pack()

# This is for demonstration purposes
tk.Text(height=10, width=10).pack()

def default(event):
    current = textbox.get("1.0", tk.END)
    if current == "Default\n":
        textbox.delete("1.0", tk.END)
    elif current == "\n":
        textbox.insert("1.0", "Default")

textbox.bind("<FocusIn>", default)
textbox.bind("<FocusOut>", default)

tk.mainloop()

rawDescription: Disappearing text in GUI prompt for Python Tkinter


code:
import asyncio, random

q = asyncio.Queue()

@asyncio.coroutine
def produce():
    while True:
        yield from q.put(random.random())
        yield from asyncio.sleep(0.5 + random.random())

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

loop = asyncio.get_event_loop()
loop.create_task(produce())
loop.create_task(consume())
loop.run_forever()

rawDescription: Equivalent of asyncio.Queues with worker "threads"


code:
my_dict = {}
for obj in my_objects:
    my_dict.setdefault(obj.year, []).append(obj)

rawDescription: django create list from a queryset list

description: Django create list from a queryset list


code:
data = """Lead Attorney: John Doe
Staff Attorneys: John Doe Jr. Paralegal: John Doe III
Geographic Area: Wisconsin
Affiliated Offices: None
E-mail: blah@blah.com"""

result = {}
data = data.replace('Paralegal:', '\nParalegal:')
for line in data.splitlines():
    key, val = line.split(':', 1)
    result[key.strip()] = val.strip()

print(result)

rawDescription: Regular Expressions task

description: Regular Expressions task


code:
import wx
import wx.lib.dragscroller

#-------------------------------------------------------------------------------

def runTest(frame, nb, log):
    win = DragScrollerExample(nb, -1)
    return win

class DragScrollerExample(wx.ScrolledWindow):
    def __init__(self, parent, id=-1):
        wx.ScrolledWindow.__init__(self, parent, id)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)

        self.SetScrollbars(1, 1, 2000, 2000, 0, 0)

        self.scroller = wx.lib.dragscroller.DragScroller(self)

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        self.DoPrepareDC(dc)

        pen = wx.Pen(wx.BLACK, 5)
        dc.SetPen(pen)

        for y in range(10):
            for x in range(10):
                dc.DrawCircle(x*400+20, y*400+20, 200)

        dc.DrawText('Right click and drag in the direction you want to scroll.',
                    20, 20)
        dc.DrawText('The distance from the start of the drag determines the speed.',
                    20, 50)

    def OnRightDown(self, event):
        self.scroller.Start(event.GetPosition())

    def OnRightUp(self, event):
        self.scroller.Stop()

#-------------------------------------------------------------------------------

overview = """

DragScroller

A helper class that adds scrolling to a wx.ScrolledWindow in the direction
of the drag.

"""

if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])])

rawDescription: wxPython (wxWidgets): how to customize scrollbars look'n'feel?

description: WxPython (wxWidgets): how to customize scrollbars look'n'feel


code:
try:
    import Image
except ImportError:
    from PIL import Image
import pytesseract as tes

results = tes.image_to_string(Image.open('test.png'),boxes=True)

rawDescription: To detect digits from an image using cv2 and python


code: inAC.seek(0, 0)

rawDescription: Re-using variables with regards to csv files in python


code: sorted(a, key=lambda v: (v, random.random()))

rawDescription: python randomly sort items of the same value

description: Python randomly sort items of the same value


code:
date = datetime.date.today()
YourModel.objects.filter(bar__range=(
                                datetime.datetime.combine(
                                        date,
                                        datetime.time.min
                                    ),
                                datetime.datetime.combine(
                                        date,
                                        datetime.time.max
                                    ),
                            ))

rawDescription: How to list all the objects with a specific date no matter the time in a DateTime Field

description: List all the objects with a specific date no matter the time in a DateTime Field


code:
if settings.DEBUG:
    from django.views import debug
    response = debug.technical_404_response(request, e)

rawDescription: Who generates the default page of django welcome page?


code:
def insert_between(iterable, fill, cond):
    iterable = iter(iterable)
    prev = next(iterable)
    yield prev
    for cur in iterable:
            if cond(prev, cur):
                    yield fill
            yield cur
            prev = cur
list(insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y))

rawDescription: Insert an element between two adjacent list elements which meet a condition


code:
from itertools import chain

for word, cls in chain(self.spam.items(), self.ham.items()):
    print(word, cls)

rawDescription: How can loop over two dictionaries at once?


code:
from collections import Counter

# read in original records
with open("account_names.csv", "rt") as f:
    rows = sorted(line.strip() for line in f)

# count how many times each row appears
counts = Counter(rows)

# get a list of tuples of (count, row) that only includes count > 1
dups = [(count, row) for row, count in counts.items() if count > 1]
dup_count = sum(count-1 for count in counts.values() if count > 1)

# sort the list from largest number of dups to least
dups.sort(reverse=True)

# print a report showing how many dups
for count, row in dups:
    print("{}\t{}".format(count, row))

# get de-duped list
unique_rows = sorted(counts)

# read in de-duped list
with open("account_de_ex.csv", "rt") as f:
    de_duped = sorted(line.strip() for line in f)

print("List lengths: rows {}, uniques {}/de_duped {}, result {}".format(
        len(rows), len(unique_rows), len(de_duped), len(de_duped) + dup_count))

# lists should match since we sorted both lists
if unique_rows == de_duped:
    print("perfect match!")
else:
    # if lists don't match, find out what is going on
    uniques_set = set(unique_rows)
    deduped_set = set(de_duped)

    # find intersection of the two sets
    x = uniques_set.intersection(deduped_set)

    # print differences
    if x != uniques_set:
        print("Rows in original that are not in deduped:\n{}".format(sorted(uniques_set - x)))
    if x != deduped_set:
        print("Rows in deduped that are not in original:\n{}".format(sorted(deduped_set - x)))

rawDescription: List Comprehension Mystery - Python

description: List Comprehension Mystery - Python


code:
result = None
with open('input.txt') as f:
    result = [tuple(line.split()) for line in f]

for t in result:
    print(t)

rawDescription: Import list of strings to tuples

description: Import list of strings to tuples


code:
N = { 'd' : 3 }
four = Template(u'number:{{ d + 1 }}').render(**N)

rawDescription: Can I do math inside Python's string formatting "language"?

description: Do math inside Python's string formatting "language"


code:
#!/usr/bin/env python3

import inspect
from json import JSONEncoder

class TreeNode:

    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class ObjectJSONEncoder(JSONEncoder):

    def default(self, reject):
        is_not_method = lambda o: not inspect.isroutine(o)
        non_methods = inspect.getmembers(reject, is_not_method)
        return {attr: value for attr, value in non_methods
                if not attr.startswith('__')}

if __name__ == '__main__':
    tree = TreeNode(42,
        TreeNode(24),
        TreeNode(242),
    )
    print(ObjectJSONEncoder().encode(tree))

rawDescription: Easy JSON encoding with Python

description: Easy JSON encoding with Python


code:
school_name = "your school name"
Students_in_school = Student.objects.filter(grade__school__name = school_name)

rawDescription: How to filter by field of field (multi level relationship) in django admin?

description: Filter by field of field (multi level relationship) in django admin


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

v1 = np.random.rand(50,150)
v2 = np.random.rand(150)

fig = plt.figure()

# create a 2 X 2 grid
gs = grd.GridSpec(2, 2, height_ratios=[1,10], width_ratios=[6,1], wspace=0.1)

# image plot
ax = plt.subplot(gs[2])
p = ax.imshow(v1,interpolation='nearest',aspect='auto') # set the aspect ratio to auto to fill the space.
plt.xlabel('Day')
plt.ylabel('Depth')
plt.xlim(1,140)

# color bar in it's own axis
colorAx = plt.subplot(gs[3])
cb = plt.colorbar(p, cax = colorAx)
cb.set_label('RWU')

# line plot
ax2 = plt.subplot(gs[0])

ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.xaxis.set_ticks_position('bottom')
ax2.yaxis.set_ticks_position('left')
ax2.set_yticks([0,1])
x=np.arange(1,151,1)
ax2.plot(x,v2,'k',lw=0.5)
plt.xlim(1,140)
plt.ylim(0,1.1)

plt.show()

rawDescription: Align vertically two plots in matplotlib provided one is an imshow plot?


code:
if "initializer" not in globals():
    initialize()

rawDescription: Py.test: Run initialization method before pytest_generate_tests


code:
from django.contrib.auth.signals import user_logged_in

import datetime

def reauthentication(sender, user, request, **kwargs):
    request.session['last_login_time'] = str(datetime.datetime.now())
    request.session.save()

user_logged_in.connect(reauthentication)

rawDescription: Re-Authenticate / Confirm credentials of User


rawDescription: Python split iterables into combinations


code:
rounds = input("Number of rounds: ")
scores = []
for i in range(int(rounds)):
    score = input("Scores separated by a space: ").split()
    scores.append((int(score[0]), int(score[1]))) #Append pairs of scores to a list

antonia = 100
david = 100

for score in scores:
    a,d = score # Split the pair into a and d
    if a < d:
        antonia -= int(a)
    if a > d:
        david -= int(d)
    elif a == d:
        pass

print(antonia)
print(david)

rawDescription: Python Dice Game Points Variables Not Changing


code:
import boto3

def get_aws_account_id(access_key, secret_key):
    sts = boto3.client(
        "sts", aws_access_key_id=access_key, aws_secret_access_key=secret_key,
    )
    user_arn = sts.get_caller_identity()["Arn"]
    return user_arn.split(":")[4]

rawDescription: Get AWS Account ID from Boto

description: Get AWS Account ID from Boto


rawDescription: How to not specify default parameters in python?

description: Not specify default parameters in python


rawDescription: Python: How to sort a list by the count of specific character


code:
class MyHandler(logging.Handler):

    def close(self):
       # Write XML epilog.
       # ...
       super(MyHandler, self).close()

rawDescription: does Python logging inform a handler when it is removed with removeHandler?

description: Does Python logging inform a handler when it is removed with removeHandler


code:
def m(s):
  return [s*[0] for _ in xrange(s)]

rawDescription: Matrix of zeroes and ones without numpy

description: Matrix of zeroes and ones without numpy


code:
#!/usr/bin/env python

"""Forms

A simple example showing how to deal with data forms.
"""

from circuits.web import Server, Controller

FORM = """

  <title>Basic Form Handling</title>

Basic Form Handling

   Example of using
   circuits and its
   Web Components to build a simple web application that handles
   some basic form data.

  <form action="/save" method="POST">

     First Name:
     <input type="text" name="firstName">

     Last Name:
     <input type="text" name="lastName">

       <input type="submit" value="Save">

  </form>

"""

class Root(Controller):

    def index(self):
        """Request Handler

        Our index request handler which simply returns a response containing
        the contents of our form to display.
        """

        return FORM

    def save(self, firstName, lastName):
        """Save Request Handler

        Our /save request handler (which our form above points to).
        This handler accepts the same arguments as the fields in the
        form either as positional arguments or keyword arguments.

        We will use the date to pretend we've saved the data and
        tell the user what was saved.
        """

        return "Data Saved. firstName={0:s} lastName={1:s}".format(
            firstName, lastName
        )

app = Server(("0.0.0.0", 8000))
Root().register(app)
app.run()

rawDescription: How do I retrieve the server address via a button

description: Retrieve the server address via a button


code: x2, y2, _ = proj3d.proj_transform(x1,y1,z1, ax.get_proj())

rawDescription: matplotlib: get projection coordinates

description: Matplotlib: get projection coordinates


code:
for li in my_list:
    li[4] = int(li[4])

rawDescription: Convert certain values in list to int

description: Convert certain values in list to int


rawDescription: Django - Pass URL "name" attribute to view


code:
import struct
struct.pack('<HBB', 12345, 97, 66)

rawDescription: Python: num to bytes

description: Python: num to bytes


rawDescription: Finding best possible combination of 8 elements, one from each of 8 lists


code:
def filter_nodes(self, **kwargs):
    return [n for n in self.pcode
            if all(getattr(n, k) == v for k, v in kwargs.iteritems())]

rawDescription: python kwargs: how to use best as a filter for objects?

description: Python kwargs: how to use best as a filter for objects


code:
from osgeo import ogr

ds = ogr.Open("somelayer.shp")
lyr = ds.GetLayerByName("somelayer")
lyr.ResetReading()

point = ogr.CreateGeometryFromWkt("POINT(4 5)")

for feat in lyr:
    geom = feat.GetGeometryRef()
    if geom.Contains(point):
        sm = feat.GetField(feat.GetFieldIndex("surface_material"))
        # do stuff...

rawDescription: How to use python to lookup information at specific latitude/longitude in a ESRI shapefile?

description: Use python to lookup information at specific latitude/longitude in a ESRI shapefile


rawDescription: How can I store a list of number inside a number in Python?

description: Store a list of number inside a number in Python


code:
# first, make a function to linearly interpolate the data
f = scipy.interpolate.interp1d(x,y)

# resample with 1000 samples
xx = np.linspace(-20,19, 1000)

# compute the function on this finer interval
yy = f(xx)

# make a gaussian window
window = scipy.signal.gaussian(200, 60)

# convolve the arrays
smoothed = scipy.signal.convolve(yy, window/window.sum(), mode='same')

# get the maximum
xx[np.argmax(smoothed)]

rawDescription: Smooth Data and Find Maximum

description: Smooth Data and Find Maximum


code:
def next(n):
    if n % 2 != 0:
        return 3*n + 1
    else:
        return n/2

def collatz(n):
    count = 0
    i = n
    while i not in table:
        count += 1
        i = next(i)
    count += table[i]
    i = n
    while i not in table:
        table[i] = count
        count -= 1
        i = next(i)
    return table[n]

rawDescription: Iteration vs recursion when dynamic lookup table is required


code:
def normal_method(): #nothing gets autoinserted
    pass

class Foo:
    def instance_method(self): #self gets autoinserted
        pass

    @staticmethod
    def static_method(): # nothing is inserted
        pass

    @classmethod
    def class_method(cls): #cls is autoinserted
        pass

rawDescription: Why is Eclipse python autocomplete adding the self parameter?


rawDescription: Python - Make sure string is converted to correct Float


code:
# calcuate normalization factor
factor = 1.0 / sum(in_degree_dist.itervalues())

# sort the dictionary
sorted_in_degree_dist = OrderedDict((key, in_degree_dist[key] * factor)
    for key in sorted(in_degree_dist))

# or
sorted_in_degree_dist = OrderedDict((key, value * factor)
    for key, value in sorted(in_degree_dist.iteritems()))

rawDescription: sorting and summing up a dictionary in python

description: Sorting and summing up a dictionary in python


code:
l = [10,5,3]
s = reduce(lambda x, y: x - y, l)

rawDescription: Subtract each value of a list Python

description: Subtract each value of a list Python


code:
import magic
magic.from_file('renamed.pdf')
magic.from_file('renamed.pdf', mime=True)

rawDescription: check if the file format is different with the file name extension in Python, Javascript?

description: Check if the file format is different with the file name extension in Python, Javascript


code:
from itertools import izip

fig, axeses = plt.subplots(3,1,sharex=False)
#3X3 Top to bottom

for yl, cl, ax in izip([yearList1, yearList2, yearList3],
                       [chartList1, chartList2, chartist3],
                       axeses):
    ax.bar(range(len(cl)), cl, align='center')
    ax.set_ylim(0,30)
    ax.set_yticks(np.arange(0, 31, 5))
    ax.yaxis.set_minor_locator(minorLocator)

    xlabels = [dateFmt(xl) for xl in yl]  # make a list of formatted labels
    ax.set_xticks(range(len(cl)))  # put the tick markers under your bars
    ax.set_xticklabels(xlabels)    # set the labels to be your formatted years
    #Rotate tick labels 90 degrees
    for label in ax.get_xticklabels():
        label.set_rotation(90)

# you only need to do this once
fig.tight_layout()

fig.subplots_adjust(right=0.925)
fig.savefig('%s\\run.pdf' % outDir)

rawDescription: Custom X-Axis Date Range Using Matplotlib


code:
def get_counts(sequence):  # Defines the function.
   counts = {}             # Creates an empty dictionary.
   for x in sequence:      # Loops through each item in sequence
      if x in counts:      # If item already exists in dictionary
          counts[x] += 1   # Add one to the current item in dictionary
      else:                # Otherwise...
          counts[x] = 1    # Add item to dictionary, give it a count of 1
   return counts           # Returns the resulting dictionary.

rawDescription: I don't understand this simple loop

description: I don't understand this simple loop


code: amount = getattr(user.week_one, 'squats')

rawDescription: Selecting a Field With a String Name Only


code:
import numpy as np
import matplotlib.pyplot as plt
im = np.random.randint(0, 255, (16, 16))
I = np.dstack([im, im, im])
x = 5
y = 5
I[x, y, :] = [1, 0, 0]
plt.imshow(I, interpolation='nearest' )
plt.imshow(im, interpolation='nearest', cmap='Greys')

rawDescription: How to draw a colored pixel on a grayscale image?

description: Draw a colored pixel on a grayscale image


code:
numbers = [1,2,3,4,5,6]

with open('output.txt', 'w') as f:
  f.write('\t'.join(numbers))

rawDescription: how to write to a text file using python ?

description: Write to a text file using python


code:
import csv

with open(youcsvfilename, 'rb') as csvf:
    csvwriter = csv.writer(csvf)
    for filename, values in dictionary.items():
        csvwriter.writerow([filename] + values)

rawDescription: Write in csv file with dict

description: Write in csv file with dict


rawDescription: how to get today's start time?

description: Get today's start time


code:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = "http://www.weatheronline.co.uk/weather/maps/current?LANG=en&DATE=1354104000&CONT=euro&LAND=UK&KEY=UK&SORT=1&INT=06&TYP=sonne&ART=tabelle&RUBRIK=akt&R=310&CEL=C"
response = opener.open(url)
page = response.read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(page)

rawDescription: Issue scraping with Beautiful Soup

description: Issue scraping with Beautiful Soup


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('Your resource<title>hi</title>')
soup.title.string # Your title string.

rawDescription: Processing HTML files Python

description: Processing HTML files Python


rawDescription: How to compare standard Python 9-tuple time format?

description: Compare standard Python 9-tuple time format


code:
import seaborn as sns, matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips, palette="PRGn")

# statistical annotation
x1, x2 = 2, 3   # columns 'Sat' and 'Sun' (first column: 0, see plt.xticks())
y, h, col = tips['total_bill'].max() + 2, 2, 'k'
plt.plot([x1, x1, x2, x2], [y, y+h, y+h, y], lw=1.5, c=col)
plt.text((x1+x2)*.5, y+h, "ns", ha='center', va='bottom', color=col)

plt.show()

rawDescription: How does one insert statistical annotations (stars or p-values) into matplotlib / seaborn plots?

description: Insert statistical annotations (stars or p-values) into matplotlib / seaborn plots


code:
def format_mail_plain(value, from_address):
    value = re.compile(r'^On.*?wrote:\s*', re.IGNORECASE | re.MULTILINE | re.DOTALL).sub('', value)
    res = [re.compile(r'From:\s*' + re.escape(from_address), re.IGNORECASE),
           re.compile('<' + re.escape(from_address) + '>', re.IGNORECASE),
           re.compile(r'-+original\s+message-+\s*$', re.IGNORECASE),
           re.compile(r'^from:', re.IGNORECASE),
           re.compile(r'^>')]

    lines = filter(None, [line.rstrip() for line in value.split('\n')])

    result = []
    for line in lines:
        result.append(line)
        for reg_ex in res:
            if reg_ex.search(line):
                result.pop()
                break

    return '\n'.join(filter(None, result))

rawDescription: Regular expression not stripping text from quoted reply


code:
inp = raw_input("Enter space separated values of form 'a b 2 5' \n")
vars = [int(i) if i.isdigit() else i for i in inp.split()]
vars

rawDescription: Take space separated input having different data types


code:
def processDataSet (module):
    print (module.baz)

for m in ['data1.py', 'data2.py', 'data69.py']:
    processDataSet (__import__ (m) )

rawDescription: Modules as function arguments

description: Modules as function arguments


code:
number = 1337

with open('filename.txt', 'w') as f:
  f.write('%d' % number)

rawDescription: Python, writing an integer to a '.txt' file


rawDescription: Access name of python objects

description: Access name of python objects


code:
list1 = [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz']
tuple1 = (8,5,'f')

def my_contains(first, second):
    return bool(set(first).intersection(second))

my_contains(list1, tuple1) # True
my_contains(list1, [1]) # True
my_contains(list1, (125,178,999)) # False

rawDescription: Multiple parameters for the __contains__ function


rawDescription: Using Pandas to Iteratively Add Columns to a Dataframe


rawDescription: Replace booleans randomly in a pandas series


code:
bin(a & ~15 | (a & 3) << 2 | (a & 12) >> 2)

# a & ~15          -- a with the last 4 bits cleared
# | (a & 3) << 2   -- or with the lowest 2 bits (0 & 1) shifted 2 steps to the left
# | (a & 12) >> 2  -- or with bits 2 and 3 shifted 2 steps to the right.

a = 0b11101011
bin(a & ~15 | (a & 3) << 2 | (a & 12) >> 2)
# '0b11101110'

rawDescription: Swap binary bits in python

description: Swap binary bits in python


code:
class ProfilForm(ModelForm):
    categories  = CategoriesField(queryset=Category.objects.all().order_by('group'), label=_(u'Catégories'))

rawDescription: How to add optgroups to a django ModelMultipleChoiceField?

description: Add optgroups to a django ModelMultipleChoiceField


code:
import multiprocessing

process1 = multiprocessing.Process(target=perform_uk_analysis)
process2 = multiprocessing.Process(target=perform_de_analysis)
# you can optionally daemoize the process
process2.daemon = True
# run the tasks concurrently
process1.start()
process2.start()
# you can optionally wait for a process to finish
process2.join()

rawDescription: Simple example of Multiprocessing and multi-threading


code:
data = {}
data['id'] = 3
# ...
data['display_name'] = 'Chem 101'
# ...
summary = course_summary_struct._make([data[x] for x in course_summary_struct._fields])

rawDescription: Creating namedtuple instance from already set values


code:
#!/usr/bin/env python3
import threading
import time
import sys

def strings():
    yield "hello"
    time.sleep(.5)
    yield "world"
    time.sleep(.5)

def print_line():
    while True:
        time.sleep(.1)
        print('+++', line, file=sys.stderr)

threading.Thread(target=print_line, daemon=True).start()
for line in strings():
    print('---', line)
time.sleep(1)

rawDescription: Memory usage when reading lines from a piped subprocess stdout in python


code: [x['theint'] + y['theint'] for x, y in zip(*[iter(sorted(adict['key1'].values(), key=operator.itemgetter('thedec')))] * 2)]

rawDescription: performing calculations on dictionary values

description: Performing calculations on dictionary values


code:
import pandas as pd
d1 = pd.DataFrame({'i1': [1, 2, 2], 'i2': [1, 1, 2], 'a': [10, 20, 30]}
                  ).set_index(['i1', 'i2'])
d2 = pd.DataFrame(
    {'i1': [3, 3], 'i2': [1, 2], 'b': [40, 50]}).set_index(['i1', 'i2'])
try:
    d1.join(d2, how='inner')
except Exception as err:
    # Change this to however you wish to handle this case.
    print(err)

rawDescription: Inner join with MultiIndex fails if no overlap


code:
import pybel

for mol in pybel.readfile('sdf', 'many_molecules.sdf'):
  for atom in mol:
    coords = atom.coords
    for neighbor in pybel.ob.OBAtomAtomIter(atom.OBAtom):
      neighbor_coords = pybel.atom(neighbor).coords

rawDescription: Python Progam to read SDF (chemistry) file


code:
lst = []
s = input()
while s != 'END':
    lst.append(s)
    s = input()

rawDescription: Python - converting a series of unknown number of input() entries into a list or an array?


rawDescription: Python ASCII to binary

description: Python ASCII to binary


code:
#scatter plot one factor
import seaborn as sns
grid1 = sns.FacetGrid(df, col='c1')
grid1.map(plt.scatter, 'x1', 'x2')

#scatter plot with column and hue factor
grid2 = sns.FacetGrid(df, col='c1', hue='c2')
grid2.map(plt.scatter, 'x1', 'x2')

#histogram with one factor
grid3 = sns.FacetGrid(df, col='c1')
grid3.map(plt.hist, 'x1', alpha=.7)

rawDescription: R Lattice like plots with Python, Pandas and Matplotlib


code: A.compress(mask, axis=1)

rawDescription: masking array with logical values along an arbitrary axis

description: Masking array with logical values along an arbitrary axis


code:
class node(object):
    def __init__(self, value, children = None):
        self.value = value
        self.children = children or []
        self.parent = None
        for child in self.children:
            child.parent = self

rawDescription: Implement a tree where children and parents can refer to each other


code:
if __name__ == '__main__':
    obj = GetOneMachineDataFromDatabase()

    make_transient(obj)
    obj._oid = None
    _session.add(obj)
    # this include a flush() and create a new primary key
    _session.commit()

rawDescription: How to use make_transient() to duplicate an SQLAlchemy mapped object?

description: Use make_transient() to duplicate an SQLAlchemy mapped object


code:
default_weight = W
G = nx.Graph()
for nodes in node_list:
    n0 = nodes[0]
    n1 = nodes[1]
    if G.has_edge(n0,n1):
       G[n0][n1]['weight'] += default_weight
    else:
       G.add_edge(n0,n1, weight=default_weight)

rawDescription: Weight for edges according to number of occurence in NetworkX


code:
import sys, os
sys.atexit.register( os.remove, path_to_file )

rawDescription: Easy way to delete a shelve .dat file left behind by my Python program?


code:
from pandas import *
df = DataFrame( np.random.randn(5,3), index = list( "ABCDE"), columns = list("abc") )
df.groupby(lambda x: True).agg({'a' : np.sum, 'b' : np.mean } )

df['total'] = 'total'
df.groupby(['total']).agg({'a' : np.sum, 'b' : np.mean } )

rawDescription: How to do a groupby on an empty set of columns in Pandas?

description: Do a groupby on an empty set of columns in Pandas


code:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                "django.contrib.auth.context_processors.auth",
            ]
        }
    }
]

description: Django.core.exceptions.ImproperlyConfigured: Enable 'django.contrib.auth.context_processors.auth'


code:
for i, values in enumerate(combinations):
  fruit, letter, class_, list_, dict_, animal, language = values

rawDescription: What's the accepted Python style for long tuples on the left-hand side of for loops?


code:
from itertools import repeat
# open the file, create a reader
for row in reader:
    row_ = [i for item in row for i in itertools.repeat(item,2)]
# now do whatever you want to do with row_

rawDescription: Add one identical column to next column respectively


code:
def __unicode__(self):
    return u'Unit: {name:s} -- {base.name:s} * {mul:f}'.format(**self.__dict__)

rawDescription: Django: More pythonic __unicode__

description: Django: More pythonic __unicode__


code:
from string import Formatter

s="""<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>"""

print([ele[1] for ele in Formatter().parse(s) if ele[1]])
['PrimaryKey', 'orientation']

rawDescription: Function to get list of all identifiers in String Template (Python)


code:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
save_dir = tkFileDialog.asksaveasfilename()

rawDescription: Python: Tkinter file dialogues

description: Python: Tkinter file dialogues


code: self.view.window().run_command('exec', {'cmd': ['sh', 'script.sh'], 'quiet': False})

rawDescription: Sublime Text Build System With Options

description: Sublime Text Build System With Options


code:
line1 = ax1.plot(
          x, myvalues,
          marker = 'o',
          linestyle = '-',
          markerfacecolor='#333399',
          markeredgecolor='k',
          label='My Blue values')

rawDescription: Matplotlib: how to plot with a specific hex color and a specific marker?


code:
xml = r"""
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
      <listName>PyTest</listName>
      <updates>
        <Batch OnError="Continue" ListVersion="0">
           <Method ID="1" Cmd="New">
              <Field Name="ID">New</Field>
              <Field Name="Title">{0}</Field>
              <Field Name="Sex">{1}</Field>
              <Field Name="FirstName">{2}</Field>
              <Field Name="LastName">{3}</Field>
              <Field Name="CustomerNum">{4}</Field>
           </Method>
        </Batch>
      </updates>
    </UpdateListItems>
  </soap:Body>
</soap:Envelope>
    """.format(st, sex, fname, lname, costname)

res = client.service.UpdateListItems(__inject={'msg': xml})

rawDescription: Update sharepoint list items with suds in python


code:
from scipy.interpolate import griddata

Angles = [-180, -90, 0 , 90, 180, -135,
          -45,45, 135, 180,-90, 0, 90, 180 ]

Radii = [0,0.33,0.33,0.33,0.33,0.5,0.5,
         0.5,0.5,0.5,0.6,0.6,0.6,0.6]

Angles = np.array(Angles)/180.*np.pi
x = np.array(Radii)*np.sin(Angles)
y = np.array(Radii)*np.cos(Angles)

Values = [30.42,24.75, 32.23, 34.26, 26.31, 20.58,
          23.38, 34.15,27.21, 22.609, 16.013, 22.75, 27.062, 18.27]

Xi = np.linspace(-1,1,100)
Yi = np.linspace(-1,1,100)

#make the axes
f = plt.figure()
left, bottom, width, height= [0,0, 1, 0.7]
ax  = plt.axes([left, bottom, width, height])
pax = plt.axes([left, bottom, width, height],
                projection='polar',
                axisbg='none')
cax = plt.axes([0.8, 0, 0.05, 1])
ax.set_aspect(1)
ax.axis('Off')

# grid the data.
Vi = griddata((x, y), Values, (Xi[None,:], Yi[:,None]), method='cubic')
cf = ax.contour(Xi,Yi,Vi, 15, cmap=plt.cm.jet)

#make a custom colorbar, because the default is ugly
gradient = np.linspace(1, 0, 256)
gradient = np.vstack((gradient, gradient))
cax.xaxis.set_major_locator(plt.NullLocator())
cax.yaxis.tick_right()
cax.imshow(gradient.T, aspect='auto', cmap=plt.cm.jet)
cax.set_yticks(np.linspace(0,256,len(cf1.get_array())))
cax.set_yticklabels(map(str, cf.get_array())[::-1])

rawDescription: Interpolation differences on polar contour plots in Matplotlib


code:
def findit(word, lst):
    return [el[0] for el in lst if el[1] == word][0]

rawDescription: Is there a python special character for a blank value?


code:
old_list = json.loads(old_json)
new_list = json.loads(new_json)

new_items_list = list(set(new_list) - set(old_list))

rawDescription: Seeing what's new in json list in Python


code:
df
df["col3"] = df.groupby("col1")["col2"].transform(np.random.permutation)
df

rawDescription: Shuffle column in panda dataframe with groupby


code:
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash

class LolResource(ModelResource):

    class Meta:
        resource_name = 'lol'
        allowed_methods = ['post']  # note that this resource just accept posts

    def base_urls(self):
        return [
            url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('lol_api_function'), name="api_lol_api_function"),
        ]

    def lol_api_function(self, request, **kwargs):
        # you function
        pass

rawDescription: How to run a function with Tastypie API request?

description: Run a function with Tastypie API request


rawDescription: How to create a bytes or bytearray of given length filled with zeros in Python?

description: Create a bytes or bytearray of given length filled with zeros in Python


code: my_usable_string = my_string.replace("\n", "\\\\n")

rawDescription: Adding string with new line characters in a file to upload to an SQL UTF8 database


code:
from requests import get

url = "http://download.thinkbroadband.com/5MB.zip"
headers = {"Range": "bytes=0-100"}  # first 100 bytes

r = get(url, headers=headers)

rawDescription: Only download a part of the document using python requests


code: [peaks([x,y]) for x,y in zip(xscat,yscat)]

rawDescription: Function with arguments in two lists

description: Function with arguments in two lists


rawDescription: Problem with the size of the arrows on a vector field plot


code:
#!/usr/bin/python

from flask import Flask, Response
app = Flask(__name__)

@app.route("/")
def hello():
    return '''

        Hello. Click me.

        '''

@app.route("/getPlotCSV")
def getPlotCSV():
    # with open("outputs/Adjacency.csv") as fp:
    #     csv = fp.read()
    csv = '1,2,3\n4,5,6\n'
    return Response(
        csv,
        mimetype="text/csv",
        headers={"Content-disposition":
                 "attachment; filename=myplot.csv"})

app.run(debug=True)

rawDescription: Flask: Download a csv file on clicking a button


code:
x = (1, 2)
x
x.__init__([3, 4])
x # tuple.__init__ does nothing
y = [1, 2]
y
y.__init__([3, 4])
y # list.__init__ reinitialises the object

rawDescription: Python (and Python C API): __new__ versus __init__


code: sum(item['price'] for item in list)

rawDescription: How can I add all values in a list of dictionaries?

description: Add all values in a list of dictionaries


code:
import ntplib
c = ntplib.NTPClient()
response = c.request('europe.pool.ntp.org', version=3)
response.offset

rawDescription: Find offset between system-time and Internet time using Python


code:
from scipy.io.wavfile import read, write
from scipy.fftpack import rfft, irfft
import np as numpy

rate, input = read('input.wav')

transformed = rfft(input)

filtered = function_that_does_the_filtering(transformed)
output = irfft(filtered)

write('output.wav', rate, output)

rawDescription: Python NumPy Convert FFT To File

description: Python NumPy Convert FFT To File


code:
elm = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
                      elm,
                      "attr_name",
                      "attr_value")

rawDescription: setAttribute() method for WebElement

description: SetAttribute() method for WebElement


code:
from chaco.api import ArrayPlotData, Plot
from enable.component_editor import ComponentEditor

from traits.api import HasTraits, Instance
from traitsui.api import View, Item

class MyPlot(HasTraits):
    plot = Instance(Plot)
    traits_view = View(Item('plot', editor = ComponentEditor(), show_label = False),
                   width = 500, height = 500, resizable = True)

    def __init__(self, x, y, *args, **kw):
        super(MyPlot, self).__init__(*args, **kw)
        plotdata = ArrayPlotData(x=x,y=y)
        plot = Plot(plotdata, padding=25)
        plot.plot(("x","y"), type = "line", color = "blue", name='abc')
        self.plot = plot
        # watch for changes to the bounding boxes of the tick labels
        self.plot.underlays[2].on_trait_change(self._update_size, '_tick_label_bounding_boxes')
        self.plot.underlays[3].on_trait_change(self._update_size, '_tick_label_bounding_boxes')
    def _update_size(self):
        if len(self.plot.underlays[2]._tick_label_bounding_boxes) > 0:
            self.plot.padding_bottom = int(np.amax(np.array(self.plot.underlays[2]._tick_label_bounding_boxes),0)[1]+8+4)
        if len(self.plot.underlays[3]._tick_label_bounding_boxes) > 0:
            self.plot.padding_left = int(np.amax(np.array(self.plot.underlays[3]._tick_label_bounding_boxes),0)[0]+8+4)

import numpy as np
x = np.linspace(-300,300,10000)
y = np.sin(x)*x**3
lineplot = MyPlot(x,y)
lineplot.configure_traits()

rawDescription: Automatic paddings in Chaco?

description: Automatic paddings in Chaco


code:
from argparse import ArgumentParser,Action

class Foo(object):
    def __init__(self,*args):
        self.args=args
    def __str__(self):
        return str(self.args)

class FooAction(Action):
    def __call__(self,parser,namespace,values,option_string=None):
        setattr(namespace,self.dest,Foo(*values))  #Add Foo to the options...
class BarAction(Action):
    def __call__(self,parser,namespace,values,option_string=None):
        FooObj=getattr(namespace,'foo')  #raises an error if foo isn't in namespace...
                                         #In this way, BarAction is like a filter on the
                                         #object created by foo.
        FooObj.args=tuple(list(FooObj.args)+list(values)) #append to the list of args.

parser=ArgumentParser()
parser.add_argument('--foo',nargs='*',action=FooAction,help="Foo!")
parser.add_argument('--bar',nargs='*',action=BarAction,help="Bar! : Must be used after --foo")

namespace=parser.parse_args("--foo Hello World --bar Nice Day".split())
print (namespace)
print (namespace.foo)

rawDescription: Python: parse commandline

description: Python: parse commandline


rawDescription: Break down this list using list comprehension


code:
import sys
s1, s2, s4 = sys.argv[1:4]

rawDescription: How to access comman-line arguments from a Python script?

description: Access comman-line arguments from a Python script


code:
a = ('chicken',1,'lemon','watermelon','camel')
d = {0:'apple',1:'banana',2:'lemon',3:'watermelon'}
b = tuple(d.get(x, x) for x in a)
b
type(b)

rawDescription: how to rebuild a tuple with some modification?

description: Rebuild a tuple with some modification


code: return "{}\n=======\n\nOptions :[{}]".format(self.label, ", ".join(self.options))

rawDescription: How can I return a list in __repr__ function?

description: Return a list in __repr__ function


code: 'Hello, World!'.center(30)

rawDescription: Python opposite of strip()

description: Python opposite of strip()


code:
class EventType(models.Model):
    name = models.CharField()
    include_in_search = models.BooleanField()

class Event(models.Model):
    ...
    event_type = models.ForeignKey('EventType')

rawDescription: Best practice for storing custom value instead of foreignkey?


code:
class FooSerializer(models.ModelSerializer):
    bars = serializers.SlugRelatedField(slug_field='bar_text')

rawDescription: Serialize custom field from an object in a list using the Django Rest Framework


code:
import glob
import numpy as np
import pandas as pd
from sklearn.cross_validation import KFold

allFiles = glob.glob("./dataset/*.txt")
kf = KFold(len(allFiles), n_folds=3, shuffle=True)

for train_files, cv_files in kf:
    dataTrain = pd.concat((pd.read_csv(allFiles[idTrain], header=None) for idTrain in train_files))
    dataTest = pd.concat((pd.read_csv(allFiles[idTest], header=None) for idTest in cv_files))

rawDescription: Cross validation of dataset separated on files


code:
import Tkinter as tk
import tkSimpleDialog

class CustomDialog(tkSimpleDialog.Dialog):

    def __init__(self, parent, title=None, text=None):
        self.data = text
        tkSimpleDialog.Dialog.__init__(self, parent, title=title)

    def body(self, parent):

        self.text = tk.Text(self, width=40, height=4)
        self.text.pack(fill="both", expand=True)

        self.text.insert("1.0", self.data)

        return self.text

def show_dialog():
    fromonk_text = "this is an example"
    CustomDialog(root, title="Example", text=fromonk_text)

root = tk.Tk()
button = tk.Button(root, text="Click me", command=show_dialog)
button.pack(padx=20, pady=20)
root.mainloop()

rawDescription: Is there a message box which displays copy-able text in Python 2.7?


rawDescription: Python [Errno 98] Address already in use


rawDescription: Image transformation in OpenCV

description: Image transformation in OpenCV


code: new_list = [x[1] for x in my_list]

rawDescription: Make a list from some of the properties of other list


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

wait = WebDriverWait(driver, 10)
wait.until(EC.title_is("title"))
wait.until(EC.title_contains("part of title"))

rawDescription: what is the best way to check url change with selenium in python?

description: What is the best way to check url change with selenium in python


code:
from tkinter import *

def find_isbn(isbn, lbl):
    if len(isbn) == 10:
        mult = 11
        total = 0
        for i in range(len(isbn)):
            total += int(isbn[i]) * mult
            mult -= 1
        digit_11 = 11 - (total % 11)
        if digit_11 == 10:
            digit_11 = 'X'
        isbn += str(digit_11)
        lbl.config(text=isbn)

top = Tk()
top.geometry("450x450+500+300")
top.title("Test")

button = Button(top, text="OK", command=lambda: find_isbn(mEntry.get(), mlabel2), fg="red", bg="blue")
button.pack()

label = Label(top, text="Please enter the 10 digit number")
label.pack()

mEntry = Entry(top)
mEntry.pack()

mlabel2 = Label(top, text='')
mlabel2.pack()

top.mainloop()

rawDescription: Tkinter ISBN Converter Need a way of printing results on Tkinter page


code:
from pyicloud import PyiCloudService
api = []
api.append(PyiCloudService('JAppleseedAppleIdEmailHere', 'password'))
api.append(PyiCloudService('SomeOtherAppleIdEmailHere', 'psadfsdfassword'))
PeerIp = '127.0.0.1'
PeerPort = 2028
ThreadRunCount = -1
InfoEveryRunTime = 10
import time, threading, socket, json
def update_device_position():
    smsg = '{\n'
    global ThreadRunCount
    ThreadRunCount += 1
    MESSAGE = json.dumps([dict(device=str(device), location=device.location()) for a in api for device in a.devices.values()]).encode()
    DevCount = 0
    for a in api:
        for key, value in a.devices.items():
            DevCount += 1
    sock.sendto(MESSAGE, (PeerIp, PeerPort))
    tmst = time.strftime('%H:%M:%S')
    if (ThreadRunCount % InfoEveryRunTime) == 0:
        ThreadRunCount = 1
        print('[' + tmst+ '] JSON of ' + str(len(MESSAGE))  +' bytes from ' + str(DevCount) + ' devices sent to ' + PeerIp + ':' + str(PeerPort))
                     # Internet      # UDP
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
stopped = threading.Event()
while not stopped.wait(10):
    update_device_position()

rawDescription: PYTHON for loop through dict_keys and UDP send


code:
def map_function(combo):
    a = combo[0]
    b = combo[1]
    c = combo[2]
    return a + b + c

if '__name__' == '__main__':
    combo = []
    combo[0] = arg_1
    combo[1] = arg_2
    combo[2] = arg_3

    pool = Pool(processes=4)
    pool.map(map_function, combo)

rawDescription: Does multiprocessing.pool.imap has a variant (like starmap) that allows for multiple arguments?


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

fig = plt.figure()
ax = fig.add_subplot(211, projection='3d')
ax.plot([1,2,3,4,5],[7,4,6,2,8],[4,6,8,9,2],'*')
ax.grid(True)
ax.set_title('grid on')

ax2 = fig.add_subplot(212, projection='3d')
ax2.plot([1,2,3,4,5],[7,4,6,2,8],[4,6,8,9,2],'*')
ax2.grid(False)
ax2.set_title('grid off')
plt.show()

rawDescription: matplotlib: grid in 3D plots

description: Matplotlib: grid in 3D plots


code:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# Load the time series
ts = pd.read_csv('EUR_CHF_daily.csv',sep=';', parse_dates=['time'], index_col = 'time',decimal=',')
ts = ts['EUR/CHF']
ts = ts.sort_index(ascending=True)

# Plot
fig = plt.figure(figsize=(14,5))
ax = plt.axes()
ax.plot(ts)

# Label the axis
ax.set_xlabel('')
ax.set_ylabel('EUR/CHF')

#I want to select the x-range for the zoomed region. I have figured it out suitable values
# by trial and error. How can I pass more elegantly the dates as something like
x1 = 1543.90
x2 = 1658.80

# select y-range for zoomed region
y1 = 1.15
y2 = 1.25

# Make the zoom-in plot:
axins = zoomed_inset_axes(ax, 2, loc=1) # zoom = 2
axins.plot(ts)
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()

rawDescription: Zoomed Plot with Time Series

description: Zoomed Plot with Time Series


code:
# This script copies the video frame by frame
import cv2
import subprocess as sp

input_file = 'input_file_name.mp4'
output_file = 'output_file_name.mp4'

cap = cv2.VideoCapture(input_file)
ret, frame = cap.read()
height, width, ch = frame.shape

ffmpeg = 'FFMPEG'
dimension = '{}x{}'.format(width, height)
f_format = 'bgr24' # remember OpenCV uses bgr format
fps = str(cap.get(cv2.CAP_PROP_FPS))

command = [ffmpeg,
        '-y',
        '-f', 'rawvideo',
        '-vcodec','rawvideo',
        '-s', dimension,
        '-pix_fmt', 'bgr24',
        '-r', fps,
        '-i', '-',
        '-an',
        '-vcodec', 'mpeg4',
        '-b:v', '5000k',
        output_file ]

proc = sp.Popen(command, stdin=sp.PIPE, stderr=sp.PIPE)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    proc.stdin.write(frame.tostring())

cap.release()
proc.stdin.close()
proc.stderr.close()
proc.wait()

rawDescription: Pipe opencv images to ffmpeg using python


rawDescription: Couldn't rename field in python list (key, value structure)


code:
import math
distance = 0
for count in range(1,len(y_smooth)):
    distance += math.sqrt(math.pow(x_smooth[count]-x_smooth[count-1],2) + math.pow(y_smooth[count]-y_smooth[count-1],2))

rawDescription: Matplotlib How to get length line

description: Matplotlib How to get length line


code:
test = [(1,1),(3,1),(5,0),(3,0),(2,1)]
crit = operator.itemgetter(1)
test.sort(key=crit)
result = [list(group) for key, group in itertools.groupby(test, crit)]
result

rawDescription: grouping list of tuples with itertools

description: Grouping list of tuples with itertools


rawDescription: Django queryset traversal (without evaluation)


code:
class SymmetricArray:
    '''
    Attributes:
        A (np.ndarray): an [m, (a,b,c...)] array.
        idx (np.ndarray): an [n,] array where idx[n] points to A[idx[n], ...]
            to be used.
        reflect (np.ndarray): an [n, d] array where every entry is 1 or -1 and
            reflect[n, i] indicates whether or not the ith dimension of
            A[idx[n], ...] should be reflected, and d = len(A.shape - 1).
    '''
    def __init__(self, A, idx, reflect):
        self.A = np.asarray(A)
        self.idx = np.asarray(idx, dtype=int)
        self.reflect = np.asarray(reflect, dtype=int)

    def __getitem__(self, ii):
        '''
        Returns:
            np.ndarray: appropriately reflected A[idx[ii], ...]
        '''
        a_mask = [slice(None, None, a) for a in self.reflect[ii, :]]
        return self.A[self.idx[ii], ...][a_mask]

rawDescription: Exploiting Symmetry in Large Numpy Array


code:
import numpy as np
X = np.random.normal(size=[20,18])
P, D, Q = np.linalg.svd(X, full_matrices=False)
X_a = np.dot(np.dot(P, np.diag(D)), Q)
print(np.std(X), np.std(X_a), np.std(X - X_a))

rawDescription: Using Numpy (np.linalg.svd) for Singular Value Decomposition


code:
s = """Row 1
apple
bob
cat
dog
ear
fun

Row 2
glow
horse
idea
joke
kick
lemon

Row 3
money
new
odd
park
queen
run"""

lines = s.split('\n\n')
for line in lines:
    words = line.splitlines()
    print([ [i, j] for i, j in zip(words[1::2], words[2::2]) ])

[['apple', 'bob'], ['cat', 'dog'], ['ear', 'fun']]
[['glow', 'horse'], ['idea', 'joke'], ['kick', 'lemon']]
[['money', 'new'], ['odd', 'park'], ['queen', 'run']]

rawDescription: How to split text in a data file with an even sequence? Python 3x

description: Split text in a data file with an even sequence? Python 3x


code:
import re
re.findall(r'\b(pizza|cheese|tomatoes)\b', 'I want eat a pizza with cheese')

rawDescription: Regex for two words

description: Regex for two words


code: profile = Profile(**all_practices)

rawDescription: Can a dictionary be passed directly to instantiate another object in python


code:
words = []
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
     for word in line.split():
          if word not in words:
               words.append(word)
fh.close()

# Now you should sort the words list and continue with your assignment

rawDescription: How do i read, append and sort all the words of a text file in python?

description: Read, append and sort all the words of a text file in python


code:
import json

def int_please_object_hook(obj):
    """If a value in obj is a string, try to convert it to an int"""
    rv = {}
    for k, v in obj.items():
        if isinstance(v, basestring):
            try:
                rv[k] = int(v)
            except ValueError:
                rv[k] = v
        else:
            rv[k] = v
    return rv

j = '{"key1": "value1", "key2": "10", "key3": "-10"}'

print(json.loads(j))
# {'key1': 'value1', 'key2': '10', 'key3': '-10'}

print(json.loads(j, object_hook=int_please_object_hook))
# {'key1': 'value1', 'key2': 10, 'key3': -10}

rawDescription: How i make json.loads turn str into int

description: How i make json.loads turn str into int


rawDescription: Opening Idle with a python script

description: Opening Idle with a python script


rawDescription: How to change tab delimited in to comma delimited in pandas

description: Change tab delimited in to comma delimited in pandas


code:
def func2(qtWnd): # Self should go here if func2 is beloning to some class, if not, then it is not necessary
   qtWnd.ui.statusbar.showMessage("This should work now!")

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

rawDescription: Accessing GUI elements from outside the GUI class


code:
import math
import wave
import struct

nchannels = 1
sampwidth = 2
framerate = 44100
nframes = 44100
comptype = "NONE"
compname = "not compressed"
amplitude = 4000
frequency = 15000

wav_file = wave.open('15khz_sine.wav', 'w')
wav_file.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
for i in xrange(nframes):
    sample = math.sin(2*math.pi*frequency*(float(i)/framerate))*amplitude/2
    wav_file.writeframes(struct.pack('h', sample))
wav_file.close()

rawDescription: Generate a Sound file with a 15Khz tone

description: Generate a Sound file with a 15Khz tone


code:
handlers = [
    (r'/(favicon.ico)', tornado.web.StaticFileHandler, {"path": ""}),
 ]

rawDescription: how to get favicon.ico work on tornado

description: Get favicon.ico work on tornado


code:
dirpath = '/Users/Desktop/Xfiles'
for filename in os.listdir(dirpath):
    os.system('/sw/bin/python2.7 pythonCode.py {}/{}'.format(dirpath, filename))

rawDescription: process a directory of files using python

description: Process a directory of files using python


code:
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

# Create your models here.
class Status(models.Model):
    status_name = models.CharField(max_length="50")
    status_description = models.CharField(max_length="1000", blank=True, null=True)

    def __str__(self):
        return self.status_name

@receiver(post_save, sender=Status)
def status_desc(sender, instance, **kwargs):
    if instance.status_description in [None, '']:
        instance.status_description = str(instance.id)
        instance.save()

rawDescription: Create description of field using primary key on save


code:
try:
    reloading
except NameError:
    reloading = False # means the module is being imported
else:
    reloading = True # means the module is being reloaded

rawDescription: How to tell if a Python modules I being reload()ed from within the module

description: Tell if a Python modules I being reload()ed from within the module


rawDescription: Convert one row of a pandas dataframe into multiple rows


code:
matches = re.findall(r'(-.+?-)', 'This is a -string- with a -foo bar-')
print(matches) # ['-string-', '-foo bar-']

rawDescription: Grab certain words and phrases from a text file in Python


code:
class MyUserCreationForm(forms.ModelForm):
    class Meta:
        model = User
        exclude = ('user',)
        # Exclude 'user' because we will set it manually

class MyView(View):

    def get(self, request):
        user_form = UserCreationForm(prefix='user')
        myuser_form = MyUserCreationForm(prefix='myuser')
        # Use prefix to avoid name conflicts
        return render(...)

    def post(self, request):
        user_form = UserCreationForm(request.POST, prefix='user')
        myuser_form = MyUserCreationForm(request.POST, prefix='myuser')
        user_form_is_valid = user_form.is_valid()
        myuser_form_is_valid = myuser_form.is_valid()
        # Do form.is_valid() here in order to always call both
        if user_form_is_valid and myuser_form_is_valid:
            user = user_form.save()
            myuser = myuser_form.save(commit=False)
            myuser.user = user
            myuser.save()
            ...
        ...
        return ...

rawDescription: Form for (extended) User

description: Form for (extended) User


code:
import pylab as pl
fig = pl.figure()
ax1 = pl.subplot(111,ylabel='A')
#ax2 = gcf().add_axes(ax1.get_position(), sharex=ax1, frameon=False, ylabel='axes2')
ax2 =ax1.twinx()
ax2.set_ylabel('B')
ax1.bar(df.index,df.A.values, width =0.4, color ='g', align = 'center')
ax2.bar(df.index,df.B.values, width = 0.4, color='r', align = 'edge')
ax1.legend(['A'], loc = 'upper left')
ax2.legend(['B'], loc = 'upper right')
fig.show()

rawDescription: How to create bar chart with secondary_y from dataframe

description: Create bar chart with secondary_y from dataframe


rawDescription: lxml/Python : get previous-sibling

description: Lxml/Python : get previous-sibling


code:
def getDataFromServer():
    if serverNotResponding():
        return
    # do important stuff here which requires the server to be running

rawDescription: What does return with nothing mean in python?


code:
def plot(reader):
    channels=[]
    for i in reader:
        channels.append(i)

    fig, ax = plt.subplots(len(channels), sharex=True, figsize=(50,100))

    plot=0
    for j in reader:

        ax[plot].plot(reader["%s" % j])
        plot=plot+1

    plt.tight_layout()
    plt.show()

rawDescription: Size of figure when using plt.subplots

description: Size of figure when using plt.subplots


code:
# html is your input string
start = html.find( '' )
end = html.find( '	', start )
result = html[start:end]

rawDescription: how to print everything after keyword ? for instance print everything between word "Apple" and word "Pen"

description: Print everything after keyword ? for instance print everything between word "Apple" and word "Pen"


code:
import numpy as np
import scipy as sp
import scipy.interpolate
import matplotlib.pyplot as plt

# Generate some random data
y = (np.random.random(10) - 0.5).cumsum()
x = np.arange(y.size)

# Interpolate the data using a cubic spline to "new_length" samples
new_length = 50
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

# Plot the results
plt.figure()
plt.subplot(2,1,1)
plt.plot(x, y, 'bo-')
plt.title('Using 1D Cubic Spline Interpolation')

plt.subplot(2,1,2)
plt.plot(new_x, new_y, 'ro-')

plt.show()

rawDescription: Add more sample points to data

description: Add more sample points to data


code:
a = {'a': (1, 2, 3), 'b': (3, 2, 1)}
b = a.items()
b
b.sort(key=lambda x:x[1][2])  # sorting by the third item in the tuple
b

rawDescription: Sorting a dictionary of tuples in Python


code:
from sympy import *
a,b,x = symbols('a b x')
mu = Symbol('mu', nonzero=True)
psi = a * cos( sqrt(2/mu)*x ) + b * sin( sqrt(2/mu)*x )
Psi = integrate(psi, x)

rawDescription: Declare a SymPy symbol non-zero

description: Declare a SymPy symbol non-zero


code:
import sys
sys.path.insert(0, '/my/path/file.zip')
import my_module
my_module.caLL_something()

rawDescription: How to use zip file which have all the package of nltk?

description: Use zip file which have all the package of nltk


code:
def parse_dialog(self, elem):
    self.out('')
    self.out("item_dialog(id='{0}', text='{1}', type='{2}')".format(
       escape_string(elem.attrib['id']),
       escape_string(elem.attrib['text']),
       escape_string( elem.attrib['type']) ))

def escape_string(s):
  ...

rawDescription: Maintaining special characters when parsing XML with Python?


code:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
random.choice(d.keys())

rawDescription: How to get a random value in python dictionary

description: Get a random value in python dictionary


rawDescription: Run multiprocess

description: Run multiprocess


code:
plt.plot(x, y, marker='.', lw=1)
d = scipy.zeros(len(y))
ax.fill_between(xs, ys, where=ys>=d, interpolate=True, color='blue')
ax.fill_between(xs, ys, where=ys<=d, interpolate=True, color='red')

rawDescription: Filling above/below matplotlib line plot


code:
import pandas
import json

# note if this actually works your json file is not correctly formed
df = pandas.DataFrame([json.loads(l) for l in open('Aberdeen2005.json')])

# Parse dates and set index
df.date = pandas.to_datetime(df.date)
df.set_index('date', inplace=True)

# match keywords
matchingbodies = df[df.body.str.contains("|".join(keywords))].body

# Count by month
counts = matchingbodies.groupby(lambda x: x.month).agg(len)

rawDescription: Grouping month in a json file

description: Grouping month in a json file


rawDescription: How does zero-padding work for 2D arrays in scipy.fftpack?


code:
for row in reader:
    for value in row:
        edbresults = api.exploitdb.search(value)
        print (edbresults)

rawDescription: Iterate Through Dictionary Values, Assign to Variable


code:
# import your data here
import math
figfit = plt.figure(); axfit = figfit.gca()

cdea = zip(cdeax,cdeay)
cdea = np.array(sorted(cdea, key = lambda x: x[0]))

gsi = zip(gsix,gsiy)
gsi = np.array(sorted(gsi, key = lambda x: x[0]))

cdeafit2 = np.polyfit(cdea[:,0],cdea[:,1],1)
gsifit2 = np.polyfit([x[0] for x in gsi],[math.log(x[1]) for x in gsi],1)

cdeafit = [x*cdeafit2[0] + cdeafit2[1] for x in cdea[:,0]]

gsifit = [math.exp(y) for y in [x*gsifit2[0] + gsifit2[1] for x in gsi[:,0]]]

axfit.plot(cdea[:,0],cdea[:,1],'ko', alpha=.5); axfit.plot(gsi[:,0],gsi[:,1], 'kx')
axfit.plot(cdea[:,0],cdeafit,'k-',dashes = [10,10]); axfit.plot(gsi[:,0],gsifit,'k:',dashes=[10,10])
#longevityregplot[1].plot(gsix,np.log(reich_l),'k-.') # not sure what this is
axfit.set_yscale('log')
plt.show()

rawDescription: Matplotlib linestyle inconsistent dashes


code:
from datetime import datetime
formatted_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

rawDescription: python datetime swapping day month

description: Python datetime swapping day month


code:
class example(QtGui.QWidget):
    def __init__(self, parent= None):
        super(example, self).__init__()

        grid = QtGui.QGridLayout()
        grid.setSpacing(10)

        self.widget = QtGui.QWidget()

        # set the widget as parent of its own layout
        self.layout = QtGui.QGridLayout(self.widget)

        for i in range(5):
            btn = QtGui.QPushButton("test"+str(i))
            self.layout.addWidget(btn,i,0)
            btn.clicked.connect(self.buttonClicked)

        # following lines are redundant
        # self.count = i
        # self.widget.setLayout(self.layout)

        self.scroll = QtGui.QScrollArea()
        # need this so that scrollarea handles resizing
        self.scroll.setWidgetResizable(True)
        # these two lines may not be needed now
        self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        self.scroll.setWidget(self.widget)

        grid.addWidget(self.scroll, 3, 0)
        self.setLayout(grid)

    def buttonClicked(self):
        title = QtGui.QLabel('Title' + str(self.layout.count()))
        self.layout.addWidget(title)
        # following lines are redundant
        # self.layout.addWidget(title, self.count + 1, 0)
        # self.count += 1
        # self.widget.addLayout(self.layout,0)
        # self.scroll.addWidget(self.widget,0)

rawDescription: Add widgets on the fly in pyside

description: Add widgets on the fly in pyside


code: ' '.join(string.split()[::-1])

rawDescription: How to reverse a string in python

description: Reverse a string in python


code:
def partitionby(f, iterable):
    return (g[1] for g in groupby(iterable, f))

rawDescription: Feeling stupid while trying to implement lazy partitioning in Python


code:
def run(self):
    #Sends the new information to the Update Function
    for i in range(105):
        self.notifyProgress.emit(i)
        time.sleep(0.01)

rawDescription: PyQt Progressbar QThread does not work correct


code:
import pygame
import random
import time
score = 0
def StartScreen():
    global score

    pygame.init()

    white = 230,230,230
    blue = 0,0,200
    water = 0,255,255
    red = 255,0,0

    WaterLevel = 400
    Depth = 150

    Move = True

    Location = 825

    TextTop = 350

    rise = True
    TextSink = False

    CLOCK = pygame.time.Clock()
    FPS = 60

    gameDisplay = pygame.display.set_mode((272,552))
    pygame.display.set_caption('Boat Game')

    BoatFloat = pygame.image.load("BoatFloatCut.png").convert_alpha()
    BoatFloat = pygame.transform.scale(BoatFloat, (220,50))

    boat = pygame.image.load("BoatLogoCut.png").convert_alpha()
    boat = pygame.transform.scale(boat, (140,100))

    stop = False

    while not stop:

###### Screen Setup ##############################################

        gameDisplay.fill(white)

###### Rising Water ##############################################

        pygame.draw.rect(gameDisplay,water,(0,WaterLevel,272,Depth))

###### Button ####################################################

        pygame.draw.rect(gameDisplay,water,(55,Location-10,160,120),2)

###### Score #####################################################

        ScoreFont = pygame.font.SysFont("monospace", 25)

        ScoreText = ScoreFont.render(str(score), 5, (red))
        gameDisplay.blit(ScoreText, (20, 30))

###### Text ######################################################

        gameDisplay.blit(BoatFloat, (35,TextTop))

###### Movement ##################################################
        if rise:
            TextTop -= 5

        WaterLevel -= 5
        Depth += 5

        if TextTop == 0:
            rise = False

        if rise == False:
            TextSink = True

        if TextSink == True:
            TextTop += 2

###### Float Down ################################################

        gameDisplay.blit(boat,(60,Location))

        if Move:
            Location -= 5

        if Location == 275:
            Move = False

###### Start Check 3##############################################

        for event in pygame.event.get():

            if event.type == pygame.MOUSEBUTTONDOWN:
                is_inside = pygame.Rect(55,Location-10,160,120).collidepoint(pygame.mouse.get_pos())

                if is_inside == 1:
                    MainGame()

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        CLOCK.tick(FPS)

        pygame.display.update()

def MainGame():
    global score

    pygame.init()

    blue = 0,255,255
    red = 255,0,0
    white = 255,255,255

    Location = 136
    Level = 382

    gate = 100

    gate2 = 100

    space1 = -30
    space1 = -30

    space2 = space1 - 200
    space2 = space1 -200

    WaterLevel = 402

    space1speed = 1
    space2speed = 1

    Left_Rect = pygame.Rect(0,402,185,150)
    Right_Rect = pygame.Rect(137,402,185,150)

    CLOCK = pygame.time.Clock()
    FPS = 80

    gate = random.randrange(20,222)
    gate2 = random.randrange(20,222)

    gameDisplay = pygame.display.set_mode((272,552))
    pygame.display.set_caption('Boat Game')

    boat = pygame.image.load("FinalBoat.png").convert_alpha()
    boat = pygame.transform.scale(boat, (40,25))

    stop = False
    sink = False
    gameOver = False

    is_Left = False
    is_Right = False

    while not stop:

####### Background ###############################################

        gameDisplay.fill(white)

###### Score #####################################################

        ScoreFont = pygame.font.SysFont("monospace", 25)

        ScoreText = ScoreFont.render(str(score), 5, (blue))
        gameDisplay.blit(ScoreText, (20, 30))

        score += 1

####### Barriers One  ############################################

        pygame.draw.line(gameDisplay,white,(gate,space1),(gate + 60,space1),2)

        pygame.draw.rect(gameDisplay,red,(0,space1,gate,25))

        pygame.draw.rect(gameDisplay,red,(gate + 60,space1,272 - gate + 60,25))

        space1 += space1speed

        if space1 == 402:
            space1 = -30
            gate = random.randrange(20,222)

###### Barriers two ##############################################

        pygame.draw.line(gameDisplay,white,(gate2,space2),(gate2 + 60,space2),2)

        pygame.draw.rect(gameDisplay,red,(0,space2,gate2,25))

        pygame.draw.rect(gameDisplay,red,(gate2 + 60,space2,272 - gate2 + 60,25))

        space2 += space2speed

        if space2 == 402:
            space2 = space1 - 200
            gate2 = random.randrange(20,222)

####### Controles ################################################

        pygame.draw.rect(gameDisplay, red, Left_Rect)

        pygame.draw.rect(gameDisplay, red, Right_Rect)

####### Boat #####################################################

        gameDisplay.blit(boat, (Location, Level))
        ####### Barrier 1 Effects ################################

        if space1 == Level - 25 and gate >= Location:
            sink = True

        if space1 == Level - 25 and gate + 50 <= Location + 25:
            sink = True

        if sink == True:
            Level += 1

        if Level == 402:
            stop = True

        ####### Barrier 2 Effects ################################
        if space2 == Level - 25 and gate2 >= Location:
            sink = True

        if space2 == Level - 25 and gate2 + 50 <= Location + 25:
            sink = True

        if sink == True:
            Level += 1

        if Level == 402:
            stop = True

####### Water #####################################################

        pygame.draw.rect(gameDisplay,blue,(0,WaterLevel,272,150))

####### Movement ##################################################

        for event in pygame.event.get():

            if event.type == pygame.MOUSEBUTTONDOWN:
                is_Left = Left_Rect.collidepoint(pygame.mouse.get_pos())
                is_Right = Right_Rect.collidepoint(pygame.mouse.get_pos())

            if event.type == pygame.MOUSEBUTTONUP:
                is_Left = False
                is_Right = False

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        if is_Left:
            Location -= 5

        elif is_Right:
            Location += 5

        CLOCK.tick(FPS)

        pygame.display.update()

StartScreen()

rawDescription: How do I get a variable in one function to cross over to another function

description: Get a variable in one function to cross over to another function


code:
label = Gtk.Label("some text")
label.set_text("some other text")

rawDescription: How to change a label in GUI repeatedly(often)?

description: Change a label in GUI repeatedly(often)


rawDescription: Re-open files in Python?

description: Re-open files in Python


code:
from flask import request
@app.route('/advanced_search_results')
def adv_search_results():
    country = request.args.get('country')
    code = request.args.get('code')
    title = request.args.get('title')
    products = models.Product.query.filter_by(code=code, country=country, title=title).all()
    return render_template('advanced_search_results.html', products=products)

rawDescription: Correct way to use forms to do an 'advanced search' with Flask?


rawDescription: Message middleware in Django not displaying in template


code:
ids = range(1,10)
placeholders = ','.join('%s' for i in ids)
req = "SELECT * FROM t1 where id in ({})".format(placeholders)
cursor.execute(req, ids)
res = cursor.fetchall()

rawDescription: Using cursor.execute arguments in pymssql with IN sql statement


code: map(None, *[range(x + 1, y) for x, y in zip(a, b)])

rawDescription: range between two lists

description: Range between two lists


code:
line = 'first {0}, second {1}'
l = [1, 2]
print(line.format(*l))

rawDescription: Using arrays with python's string.format()


code:
field_iter = ['title', 'link', 'desc']
for field_name in field_iter:
    if field_name in item:
        field = item.fields[field_name]
        value = self.serialize_field(field, field_name, item[field_name])
    else:
        value = default_value
    yield field_name, value

rawDescription: How to store data crawled in scrapy in specfic order?

description: Store data crawled in scrapy in specfic order