code:
def switch(ll, i):
  head = ll
  currentItem = ll      # The head again
  prevItem = None       # The item that links to tempItem
  for x in range(i):    # Find the item to swap
    prevItem = currentItem
    currentItem = currentItem.next

  # Now we swap. We're rotating three items' .next values, so we can't
  # do the really optimized way.
  temp = currentItem.next
  currentItem.next = head.next
  head.next = prevItem.next
  prevItem.next = temp

rawDescription: How to switch nodes at an index with the head of a list?

description: Switch nodes at an index with the head of a list


code:
all_compare_tables = {}
for i, Book in enumerate(rootNode.getBooks(), 1):
    CompareTables=[]
    CompareTables.append(Book.getName())
    for Table in Book.getTables():
        CompareTables.append(Table.getName())
    all_compare_tables['CompareTables{}'.format(i)] = CompareTables

rawDescription: Python list Merging

description: Python list Merging


code:
def _empty_buffer(self):
    while not self.stop_printing:
        if self.current_line_idx < len(self.buffer):
            while not self.stop_printing:
                logger.debug('waiting on ok_received')
                try:
                     val = self.recv_queue.get(timeout=2)
                except Queue.Empty:
                    pass
                else:
                    break
            line = self._next_line()
            self.s.write(line)
            self.current_line_idx += 1
        else:
            break

rawDescription: Possible Race Condition in Serial read/write Code


code:
import wx

# Create a .png image with something drawn on a white background
# and put the path to it here.
IMAGE_PATH = '/python26/projects/shapedwin/image.png'

class ShapedFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Shaped Window",
                style = wx.FRAME_SHAPED | wx.SIMPLE_BORDER )
        self.hasShape = False
        self.delta = wx.Point(0,0)

        # Load the image
        image = wx.Image(IMAGE_PATH, wx.BITMAP_TYPE_PNG)
        image.SetMaskColour(255,255,255)
        image.SetMask(True)
        self.bmp = wx.BitmapFromImage(image)

        self.SetClientSize((self.bmp.GetWidth(), self.bmp.GetHeight()))
        dc = wx.ClientDC(self)
        dc.DrawBitmap(self.bmp, 0,0, True)
        self.SetWindowShape()
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_RIGHT_UP, self.OnExit)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)

    def SetWindowShape(self, evt=None):
        r = wx.RegionFromBitmap(self.bmp)
        self.hasShape = self.SetShape(r)

    def OnDoubleClick(self, evt):
        if self.hasShape:
            self.SetShape(wx.Region())
            self.hasShape = False
        else:
            self.SetWindowShape()

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.bmp, 0,0, True)

    def OnExit(self, evt):
        self.Close()

    def OnLeftDown(self, evt):
        self.CaptureMouse()
        pos = self.ClientToScreen(evt.GetPosition())
        origin = self.GetPosition()
        self.delta = wx.Point(pos.x - origin.x, pos.y - origin.y)

    def OnMouseMove(self, evt):
        if evt.Dragging() and evt.LeftIsDown():
            pos = self.ClientToScreen(evt.GetPosition())
            newPos = (pos.x - self.delta.x, pos.y - self.delta.y)
            self.Move(newPos)

    def OnLeftUp(self, evt):
        if self.HasCapture():
            self.ReleaseMouse()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    ShapedFrame().Show()
    app.MainLoop()

rawDescription: What is the simplest way to create a shaped window in wxPython?


code:
from types import MethodType

func1 = type('func1', (FunctionModel,), {'number': 3})
func2 = type('func2', (FunctionModel,), {'number': 5})
func1_inst = func1()
func2_inst = func2()

Cls = type('Cls', (ClassModel,), {'number': 10})
setattr(Cls, 'func1', MethodType(func1_inst, Cls))
setattr(Cls, 'func2', MethodType(func2_inst, Cls))

rawDescription: Attach a method to a class while the class is being created


code:
def on_list_ItemSelectionChanged(self):
    if self.list.selectedItems():
        self.ui.actionDelete_Task.setEnabled(True)
    else:
        self.ui.actionDelete_Task.setEnabled(False)

rawDescription: Clear selected list item (so there's no selected list item) in Python/PySide


rawDescription: Learning loops and lists

description: Learning loops and lists


code:
import os

size = os.fstat(fileobj.fileno()).st_size

rawDescription: What exactly does tell() return, and how do I use it to calculate percent of file read?


code: [letter for letter, count in hand.iteritems() for i in range(count)]

rawDescription: going through a dictionary and printing its values in sequence

description: Going through a dictionary and printing its values in sequence


code: df[(df.sort_index(ascending=False) == 0).cumsum() < 2].dropna()

rawDescription: Pandas: complex filtering with apply

description: Pandas: complex filtering with apply


code: cs1st = list_cs[-1][1]

rawDescription: create variable for one tuple item at the end of a list

description: Create variable for one tuple item at the end of a list


code:
from collections import defaultdict

l = ["test1", "pattern", "test2", "pattern"]

d = defaultdict(list)
for index, key in enumerate(l):
    if key == "pattern":
        d[key].append(index)

print(d)

rawDescription: python comprehension for loop with if statement and other actions following that

description: Python comprehension for loop with if statement and other actions following that


code:
remove_from_zip('archive.zip', 'hello.txt')
with zipfile.ZipFile('archive.zip', 'a') as z:
    z.write('hello.txt')

rawDescription: overwriting file in ziparchive

description: Overwriting file in ziparchive


code: user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))

rawDescription: Writing a custom sum function that sums a list of numbers


code:
import django
django.get_version()

rawDescription: European date input in Django Admin

description: European date input in Django Admin


rawDescription: How to pass in a dictionary with additional elements in python?

description: Pass in a dictionary with additional elements in python


code:
import requests
from bs4 import BeautifulSoup

def main():
    url, name = "http://www.delfi.lt/news/daily/world/ukraina-separatistai-siauteja-o-turcynovas-atnaujina-mobilizacija.d?id=64678799","foo.csv"
    r = requests.get(url)

    page = BeautifulSoup(r.content)

    title = page.find("h1",{"itemprop":"headline"})
    category = page.find_all("span",{"itemprop":"title"})
    print(title)
    with open('output.txt', encoding='utf-8', mode='w') as f:
        f.write((title.text) + "\n")
        f.write(' > '.join([x.text for x in category]) + '\n')

rawDescription: Output doesn't display all utf-8 correctly


code:
res = [1,0,0,1,1]
proportion = float(res.count(1))/len(res)

rawDescription: python: help in calculation a proportion of 1's in binary sequence

description: Python: help in calculation a proportion of 1's in binary sequence


rawDescription: Efficient way to find similar items in a list in Python


code:
d = 'somestring'
d.isdigit()

rawDescription: Handling unexpected values in Python

description: Handling unexpected values in Python


rawDescription: PocketSphinx python and setting the acoustic model?


code:
mn_first, mn_last = float("inf"),float("inf")

for d in dates.values():
    f, l = int(d['first date']),int(d['last date'])
    if f < mn_first:
        mn_first = f
    if l < mn_last:
        mn_last = l

print([k for k,v in dates.iteritems()
       if int(v['first date']) == mn_first or int(v['last date']) == mn_last])

rawDescription: Python: Find smallest values in nested dict


code:
from __future__ import print_function
import multiprocess as multiprocessing
import sys

def get_pid():
    return multiprocessing.current_process().pid

def initialize(module):
    print('Got module {} in PID {}'.format(module, get_pid()))

def worker(module):
    print('Got module {} in PID {}'.format(module, get_pid()))

current_module = sys.modules[__name__]
work = [current_module]

print('Main process has PID {}'.format(get_pid()))
pool = multiprocessing.dummy.Pool(None, initialize, work)
pool.map(worker, work)

rawDescription: multiprocess initializer and pickling

description: Multiprocess initializer and pickling


rawDescription: finding non-numeric rows in dataframe in pandas?

description: Finding non-numeric rows in dataframe in pandas


rawDescription: Imitating 'ppoints' R function in python


code:
key2 = 'new_key'
col.update({'_id': 1}, {'$set': {'value.' + key2: 'blah'}})
col.find_one()

rawDescription: pymongo, mongodb add a new key to an existing dictionary

description: Pymongo, mongodb add a new key to an existing dictionary


code:
from StringIO import StringIO
content = form.getvalue('filename')
fileh = StringIO(content)
# You can now call fileh.read, or iterate over it

rawDescription: python receive file from html form

description: Python receive file from html form


rawDescription: Matching anything but the word, regex issue


code:
import nose.tools as nt
nt.assert_equal(4, 5)

rawDescription: TDD in Python for JSON file read

description: TDD in Python for JSON file read


code: max(ld, key=lambda d: d['size'])

rawDescription: Python list of dicts, get max value index


rawDescription: How to transfer SQL Group by results to a Pandas dataframe

description: Transfer SQL Group by results to a Pandas dataframe


code:
import lxml.etree as ET
doc = ET.fromstring(xml)
for item in doc.xpath('//item'):
    for elt in item.xpath('descendant::*'):
        print(ET.tostring(elt))

rawDescription: Parse all item elements with children from RSS feed with beautifulsoup


code:
pd.to_datetime(1379945743843,unit='ms')
pd.to_datetime(1379945743845,unit='ms')
df = df_s.set_index('time')

rawDescription: Getting rows from a data frame which satisfy a condition in pandas


rawDescription: find all files indirectory and sub-directories and provide the path from directory

description: Find all files indirectory and sub-directories and provide the path from directory


code:
def unique_list(mylist):
    copy = []
    for k in mylist:
            if k not in copy:
                    copy.append(k)
    return copy

unique_list([1])
unique_list([1, 1])
unique_list([1, 1, 2])
unique_list([1, 3, 1, 2])
unique_list(['dog','cat','dog','fish'])

rawDescription: How do I make a function that returns a list of unique strings, given a list of strings with duplicates?

description: Make a function that returns a list of unique strings, given a list of strings with duplicates


rawDescription: What is the fastest way to do this string patten substitution in python?


code:
def isprime(n):
    '''check if integer n is a prime'''
    n = abs(int(n))
    if n < 2:
        return False
    if n == 2:
        return True
    if not n & 1:
        return False
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

rawDescription: Python and the modulus operator with very large numbers


code:
import flask
import httplib2
from oauth2client import client
from logging import info as linfo
import atom.data
import gdata.gauth
import gdata.data
import gdata.contacts.client
import gdata.contacts.data

app = flask.Flask(__name__)

client_info = {
    "client_id": "<CLIENT_ID>",
    "client_secret": "<CONTACTS_CLIENT_SECRET>",
    "redirect_uris": [],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
}

scopes = 'https://www.google.com/m8/feeds/'

def create_contact(gd_client):
    new_contact = gdata.contacts.data.ContactEntry()
    # Set the contact's name.
    new_contact.name = gdata.data.Name(
        given_name=gdata.data.GivenName(text='Elizabeth'),
        family_name=gdata.data.FamilyName(text='Bennet'),
        full_name=gdata.data.FullName(text='Elizabeth Bennet'))
    new_contact.content = atom.data.Content(text='Notes')
    # Set the contact's email addresses.
    new_contact.email.append(gdata.data.Email(address='liz@gmail.com',
                                              primary='true',
                                              rel=gdata.data.WORK_REL,
                                              display_name='E. Bennet'))
    new_contact.email.append(gdata.data.Email(address='liz@example.com',
                                              rel=gdata.data.HOME_REL))
    # Set the contact's phone numbers.
    new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1212',
                                                           rel=gdata.data.WORK_REL,
                                                           primary='true'))
    new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1213',
                                                           rel=gdata.data.HOME_REL))
    # Set the contact's IM address.
    new_contact.im.append(gdata.data.Im(address='liz@gmail.com',
                                        primary='true', rel=gdata.data.HOME_REL,
                                        protocol=gdata.data.GOOGLE_TALK_PROTOCOL))
    # Set the contact's postal address.
    new_contact.structured_postal_address.append(gdata.data.StructuredPostalAddress(
        rel=gdata.data.WORK_REL, primary='true',
        street=gdata.data.Street(text='1600 Amphitheatre Pkwy'),
        city=gdata.data.City(text='Mountain View'),
        region=gdata.data.Region(text='CA'),
        postcode=gdata.data.Postcode(text='94043'),
        country=gdata.data.Country(text='United States')))
    # Send the contact data to the server.
    contact_entry = gd_client.CreateContact(new_contact)
    linfo('Contact\'s ID: %s' % contact_entry.id.text)
    return contact_entry

@app.route('/gdata/oauth')
def gdata_oauth():
    request_token = gdata.gauth.OAuth2Token(
        client_id=client_info['client_id'],
        client_secret=client_info['client_secret'],
        scope=scopes,
        user_agent=None)

    return flask.redirect(
        request_token.generate_authorize_url(
            redirect_uri=flask.url_for('gdata_oauth2callback', _external=True)))

@app.route('/gdata/oauth2callback')
def gdata_oauth2callback():
    if 'error' in flask.request.args:
        return str(flask.request.args.get('error'))
    elif 'code' not in flask.request.args:
        return flask.redirect(flask.url_for('gdata_oauth'))
    else:
        request_token = gdata.gauth.OAuth2Token(
            client_id=client_info['client_id'],
            client_secret=client_info['client_secret'],
            scope=scopes,
            user_agent=None)
        request_token.redirect_uri =\
            flask.url_for('gdata_oauth2callback', _external=True)
        request_token.get_access_token(flask.request.args.get('code'))
        gd_client = gdata.contacts.client.ContactsClient(
            source='project-id',
            auth_token=request_token)
        contact = create_contact(gd_client)
        return str(contact)

rawDescription: How to authorise a gdata contacts client in python

description: Authorise a gdata contacts client in python


code:
d = str.maketrans('', '', '.,!')  # 3rd arg is chars to delete
text = set(text.lower().translate(d).split())

rawDescription: elif statement combined with "and" or "or" not working

description: Elif statement combined with "and" or "or" not working


code:
import datetime as DT

s1 = '00:02:25'
s2 = '00:04:40'
FMT = '%M:%S:%f'

d1 = DT.datetime.strptime(s1, FMT)
d2 = DT.datetime.strptime(s2, FMT)

delta = (d2-d1)/2
mid = d1 + delta
print(mid)

rawDescription: Python: Calculate the average of datetime with milliseconds


code:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.native_events_enabled = False
driver = webdriver.Firefox(profile)
# synthesized events are now enabled for this
# driver instance... native events are disabled.
...

rawDescription: Selenium WebDriver - Disable Native Events (Enable Synthesized Events)


code:
from itertools import combinations
[j for i in range(len(foobar)+1) for j in combinations(foobar,i)
 if minval <= sum(f.bar for f in j) <= maxval]

rawDescription: Generating all possible subsets of a given QuerySet in Django


code:
0xa3
hex(163)
type(0xa3)
type(hex(163))
eval(hex(163))

rawDescription: Inserting optparse input into a function call


code:
from datetime import datetime

today = datetime.today()
today = datetime(today.year, today.month, today.day)

rawDescription: Implementing matching in database

description: Implementing matching in database


code:
name.string = 'John'
name
soup

rawDescription: Replace text content of XML element in Python


code:
def func1():
    my_list = []
    for line in open("foo.txt", "r"):
        for i in line.strip().split(' '):
            if i.isdigit():
                my_list.append(int(i))
    return my_list

def func1_1():
    return [int(i) for line in open("foo.txt", "r") for i in line.strip().split(' ') if i.isdigit()]

def func1_3():
    my_list = []
    with open("foo.txt", "r") as f:
        for line in f:
            for i in line.split():
                if i.isdigit():
                    my_list.append(int(i))
    return my_list

def func2():
    my_list = []
    for line in open("foo.txt", "r"):
        for i in line.split():
            try:
                my_list.append(int(i))
            except ValueError:
                pass
    return my_list

def func3():
    my_list = []
    with open("foo.txt","r") as f:
        cf = csv.reader(f, delimiter=' ')
        for row in cf:
            my_list.extend([int(i) for i in row if i.isdigit()])
    return my_list

rawDescription: efficient way of reading integers from file

description: Efficient way of reading integers from file


code:
p = re.compile(r'.*_(.*)\.log')

'\n{}, {}\n'.format(p.search(s1).group(1), p.search(s2).group(1))

rawDescription: how to split the text using python?

description: Split the text using python


code: [value for key in dictA for value in dictA[key]]

rawDescription: List Comprehension of Lists Nested in Dictionaries


code:
def rtext(line,x,y,s, **kwargs):
    from scipy.optimize import curve_fit
    xdata,ydata = line.get_data()
    dist = np.sqrt((x-xdata)**2 + (y-ydata)**2)
    dmin = dist.min()
    TOL_to_avoid_rotation = 0.3
    if dmin > TOL_to_avoid_rotation:
        r = 0.
    else:
        index = dist.argmin()
        xs = xdata[ [index-2,index-1,index,index+1,index+2] ]
        ys = ydata[ [index-2,index-1,index,index+1,index+2] ]
        def f(x,a0,a1,a2,a3):
            return a0 + a1*x + a2*x**2 + a3*x**3
        popt, pcov = curve_fit(f, xs, ys, p0=(1,1,1,1))
        a0,a1,a2,a3 = popt
        ax = pylab.gca()
        derivative = (a1 + 2*a2*x + 3*a3*x**2)
        derivative /= ax.get_data_ratio()
        r = np.arctan( derivative )
    return pylab.text(x, y, s, rotation=np.rad2deg(r), **kwargs)

rawDescription: Matplotlib, adding text with more than one line. Adding text that can follow the curve


rawDescription: How to logically combine integer indices in numpy?

description: Logically combine integer indices in numpy


rawDescription: converting iteration into a function

description: Converting iteration into a function


code:
from collections import Counter
c = Counter()
l = ['a', 'a', 'a', 'b', 'b', 'c', 'c']
out = []
for e in l:
    out.append((e, c[e]))
    c[e] += 1
print(out)

rawDescription: Append an incremental counter to duplicate values in list


code: ['We', 'are', 'one', 'the', 'world', 'UNIVERSE']

rawDescription: Python returning unique words from a list (case insensitive)


code: df

rawDescription: change column values in CSV using python

description: Change column values in CSV using python


code:
def start_proxying(result):
    """
    Callback to start proxies.
    """

    log.msg("Starting proxy")
    client_result, server_result = result
    success = True
    client_success, client = client_result
    server_success, server = server_result

    if not client_success:
        success = False
        log.err("Had issues on client side...")
        log.err(client)

    if not server_success:
        success = False
        log.err("Had issues on server side...")
        log.err(server)

    if not success:
        log.err("Had issues connecting, disconnecting both sides")
        if not isinstance(client, Failure):
            client.transport.loseConnection()
        if not isinstance(server, Failure):
            server.transport.loseConnection()
        return

    server.dataReceived = client.transport.write
    client.dataReceived = server.transport.write
    # Replay last bits of stuff in the pipe, if there's anything left.
    data = server._sful_data[1].read()
    if data:
        client.transport.write(data)
    data = client._sful_data[1].read()
    if data:
        server.transport.write(data)

    server.transport.resumeProducing()
    client.transport.resumeProducing()
    log.msg("Proxying started!")

rawDescription: How can I create a non-http proxy with Twisted

description: Create a non-http proxy with Twisted


rawDescription: Python basic count the different type in txt file


code: L[:] = [sum(i) for i in zip(L, things_to_add)]

rawDescription: Add to integers in a list

description: Add to integers in a list


code: pdfanchor = ''

rawDescription: Creating minimal LaTeX syntax from reStructuredText with docutils


code:
cur.execute("select timecol from test where timecol < ?",
            [DT.time(4,5,6)])
print(cur.fetchall())
# [(datetime.time(1, 2, 3, 4),)]

cur.execute("select timecol from test where timecol < ?",
            [DT.time(8,0,0)])
print(cur.fetchall())
# [(datetime.time(1, 2, 3, 4),), (datetime.time(5, 6, 7, 8),)]

con.commit()
cur.close()
con.close()

rawDescription: Best way to store python datetime.time in a sqlite3 column?

description: Store python datetime.time in a sqlite3 column


code:
def checkEqual(L1, L2):
    return len(L1) == len(L2) and sorted(L1) == sorted(L2)

rawDescription: How to assert two list contain the same elements in Python?

description: Assert two list contain the same elements in Python


rawDescription: Pandas DataFrame row wise comparison

description: Pandas DataFrame row wise comparison


rawDescription: how to add and sort multidimentional array in python?

description: Add and sort multidimentional array in python


code:
import logging
class Foo(object):
    def __init__(self):
            self.log.info('Meh')

def logged_class(cls):
    cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))

logged_class(Foo)
logging.basicConfig(level=logging.DEBUG)
f = Foo()

rawDescription: Naming Python loggers

description: Naming Python loggers


code: df = pd.read_csv("mwe.csv", index_col=0)

rawDescription: Weird behavior specifying date limits with pandas


code: filtered = [a for a in List if a.number in Numbers]

rawDescription: Fastest and pythonic way of deletion of objects in this code


code:
def bbox_rotate(bbox_in, angle, centre):

    rmin, rmax, cmin, cmax = bbox_in

    # bounding box corners in homogeneous coordinates
    xyz_in = np.array(([[cmin, cmin, cmax, cmax],
                        [rmin, rmax, rmin, rmax],
                        [   1,    1,    1,    1]]))

    # translate centre to origin
    cr, cc = centre
    cent2ori = np.eye(3)
    cent2ori[:2, 2] = -cr, -cc

    # rotate about the origin
    theta = np.deg2rad(angle)
    rmat = np.eye(3)
    rmat[:2, :2] = np.array([[ np.cos(theta),-np.sin(theta)],
                             [ np.sin(theta), np.cos(theta)]])

    # translate from origin back to centre
    ori2cent = np.eye(3)
    ori2cent[:2, 2] = cr, cc

    # combine transformations (rightmost matrix is applied first)
    xyz_out = ori2cent.dot(rmat).dot(cent2ori).dot(xyz_in)

    r, c = xyz_out[:2]

    rmin = int(r.min())
    rmax = int(r.max())
    cmin = int(c.min())
    cmax = int(c.max())

    return rmin, rmax, cmin, cmax

rawDescription: bounding box of numpy array

description: Bounding box of numpy array


code:
new = np.zeros((3,3))
vals = np.array([11, 12, 13, 22, 23, 33])
inds = np.triu_indices_from(new)
new[inds] = vals
new[(inds[1], inds[0])] = vals
new

rawDescription: transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format

description: Transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format


code: ['NAMETHEFIRST,' 'NAMEANOTHERNAME ']

rawDescription: Using csv modele to extract specific lines of text from a larger file


code:
from pprint import pprint as pp

def splitlists(logname):
    with open(logname) as logf:
        #sets = [set(transposedcolumn) for transposedcolumn in zip(*(line.strip().split(',') for line in logf))]
        mintokenset, minindex = \
            min(((set(transposedcolumn), i)
                 for i, transposedcolumn in
                 enumerate(zip(*(line.strip().split(',') for line in logf)))),
                key=lambda x:len(x[0]))
    mintokens = sorted(mintokenset)
    lists = [open(r'C:\Users\Me\Code\splitlists%03i.dat' % i, 'w') for i in range(len(mintokenset))]
    with open(logname) as logf:
        for innerlist in (line.strip().split(',') for line in logf):
                lists[mintokens.index(innerlist[minindex])].write(','.join(innerlist) + '\n')
    for filehandle in lists:
        filehandle.close()

if __name__ == '__main__':
    # File splitlists.log has the following input
    '''\
instructor,plb,error0992
instruction,address,00x0993
data,address,017x112'''

    logname = 'splitlists.log'
    splitlists(logname)

    # Creates the following two output files:
    #   splitlists000.dat
    '''\
instruction,address,00x0993
data,address,017x112'''
    #   splitlists001.dat
    '''\
instructor,plb,error0992'''

rawDescription: Python: separating a list by unique values


code:
def variance(values):
    mean = sum(values) / float(len(values))
    return sum((elem - mean)**2 for elem in values) / float(len(values))

rawDescription: Determing variance in length

description: Determing variance in length


code:
with open('spam.adpcm', 'rb') as f:
    adpcm = f.read()
pcm, _ = audioop.adpcm2lin(adpcm, 2, None)

rawDescription: Play ADPCM streams with Pygame

description: Play ADPCM streams with Pygame


code:
qry = (session.query(A).filter(
    exists(select([1]).where(B.a_id == A.id).where(B.flag == False)))
)

rawDescription: SQLAlchemy, select such A that has at least one B with raised flag


code:
temp = self.env.ref('your_module.event_YOUR_ID_mail_template')
if temp:
    # example: user - instance of res.users
    temp.sudo().with_context().send_mail(user.id, force_send=True)

rawDescription: how can I use a email template in the following function?

description: Use a email template in the following function


code:
class UserForm(FloatForm):
    action = url('save_user')
    submit = SubmitButton('Save user')
    user_id = HiddenField(validator=IntValidator())
    user_name = TextField(validator=UserNameValidator(max=16),
        size=20, maxlength=16, label=u'User name:')
    remote_account = CheckBox(validator=BoolValidator(),
        label=u'Remote account:', aside=True)
    new_password = PasswordField(
        validator=PasswordValidator(required=False),
        size=20, maxlength=16, label=u'Password:', aside=True)
    group_id = CheckBoxList(item_validator=IntValidator(),
        label=u'Roles:', css_class='inline')
    display_name = TextField(validator=NameValidator(max=255),
        size=64, maxlength=255, label=u'Real name:')
    mail = TextField(validator=EmailIfLocalValidator(),
        size=64, maxlength=255, label=u'Email address:')

rawDescription: TurboGears2 - how to customize layout for new user form?


code:
if reloading and time.clock() - lastReloadTime > TIME_TO_RELOAD: #1000
    reloading = False

rawDescription: How do I make a reload timer for my player's weapon in pygame?

description: Make a reload timer for my player's weapon in pygame


rawDescription: Reshaping the array returned by matplotlib.pyplot.imread(*args, **kwargs)


code:
def addr(x,y,m,n):
  """
  Given an MxN matrix stored in a 1-d sequence,
  return the index of (possibly wrapped) X,Y
  """
  return (y%n)*m+(x%m)

rawDescription: Finding adjacent cells in a wraparound matrix


code:
numLines = 1
print("Hello world!")
print("\033[<{0}>A".format(numLines), "This came AFTER hello world line")

rawDescription: Python hide already printed text

description: Python hide already printed text


rawDescription: Rescale axis on Seaborn JointGrid KDE marginal plots


code: subprocess.call(['cmd', 'pybot', 'AdminTests', '-v', 'LOGIN URL:_mylink', '-d', '.\\results'])

rawDescription: Using the subprocess module of Python to run a program with arguments from the command line


code:
from __future__ import print_function ##Need to import this for calling print inside lambda

def build(self):
    boxLayout = BoxLayout(spacing=10,orientation='vertical')
    g = TextInput(text='Enter gratulation',
                  multiline=False,
                  font_size=20,
                  height=100)
    button = Button(text='Send')
    buttoncallback = lambda:print(g.text)
    button.bind(on_press=buttoncallback)
    ...

rawDescription: Kivy button binding function with argument


code:
myObject1 = MyObject() # gets default values
myObject2 = MyObject(foo, bar) # overrides defaults

rawDescription: How to define a default list of attributes for a Python object?

description: Define a default list of attributes for a Python object


code:
import string

f = open("title.txt","r")
all_titles = f.readlines()                # Get the data
f.close()
all_titles = map(string.strip,all_titles) # Strip off newlines.

rawDescription: How to filter the file using another file's value in python

description: Filter the file using another file's value in python


code:
strs = '[<User: mr--adhikari>]'
strs = strs.lstrip('[<User: ')
strs
strs = strs.rstrip('>]')
strs

rawDescription: How to convert this list in a given format?

description: Convert this list in a given format


code:
class ProductionWorker(employee.Employee):
    SHIFT_NAMES = {
        '1': 'day',
        '2': 'night',
        'W': 'weekend',  # just an example how you could easily add other shifts
    }

    # ...other code...

    def display_shift(self):
        return self.SHIFT_NAMES[self.get_shift()]

# ...init code...

employee = ProductionWorker(name, number, shift, pay)
print(employee.display_shift())  # 'day' or 'night'

rawDescription: How do I take the users input and if it equals 1 it would be day and a 2 would be night?

description: Take the users input and if it equals 1 it would be day and a 2 would be night


code:
class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    title = models.CharField(max_length=50)
    author = models.ForeignKey(Author)
    pub_date = models.DateTimeField()

    class Meta:
        get_latest_by = 'pub_date'

rawDescription: How to retrieve the first X objects with unique attribute value

description: Retrieve the first X objects with unique attribute value


code:
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
plt.show()

for cumul, name in enumerate(name_list):
    if im is None:
        im = plt.imread(directory+name+'.png')

        # Already done this above.
        #fig = plt.figure()
        #ax = fig.add_subplot(111)

        img = ax.imshow(im)
    else:
        img.set_data(im)
    plt.draw()
    accept = raw_input('OK? ')
    im = None

rawDescription: how to make matplotlib draw sequence of images in same window

description: Make matplotlib draw sequence of images in same window


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

num = 5000
sizes = 0.2 * np.random.random(num)
xy = 50 * np.random.random((num, 2))

# Note that the patches won't be added to the axes, instead a collection will
patches = [plt.Circle(center, size) for center, size in zip(xy, sizes)]

fig, ax = plt.subplots()

coll = matplotlib.collections.PatchCollection(patches, facecolors='black')
ax.add_collection(coll)

ax.margins(0.01)
plt.show()

rawDescription: How can I plot many thousands of circles quickly?

description: Plot many thousands of circles quickly


code:
import random

def globaldec():
    state = random.random()
    def funcdec(func):
        def wrapper(*args, **kwargs):
            return func(state, *args, **kwargs)
        return wrapper
    return funcdec

rawDescription: Python "Multi-Level Decorator" - how does this work?


code:
def __init__(self, *args, **kwargs):
    super(Student, self).__init__(*args, **kwargs)
    self.location="sample"

rawDescription: Django admin form overrding the default value


rawDescription: Sum up over np.array or np.float

description: Sum up over np.array or np.float


code: func.datediff(text('month'), TableA.date, func.getDate()) >= 0

rawDescription: Python Sqlalchemy: Filter by datediff of months


code: s

rawDescription: pandas value_counts() with multiple values in list form?

description: Pandas value_counts() with multiple values in list form


code:
a1 = A.objects.create()
a2 = A.objects.create()
b1 = B.objects.create()
b2 = B.objects.create(ref_a=a2)

# then I call:
print(a1.get_b)  # No exception raised
print(a2.get_b)  # returns b2
print(b1.a)  # returns None
print(b2.a)  # returns a2

rawDescription: Check if a OneToOne relation exists in Django


rawDescription: how to apply a mask from one array to another array?

description: Apply a mask from one array to another array


code: js_convert(fig, 'test.html')

rawDescription: Plot 3D plots using plotly

description: Plot 3D plots using plotly


code: (function(s) for s in x if condition(s))

rawDescription: List to Dictionary

description: List to Dictionary


code:
names = df['author name:'].unique()
names
names[int(len(names) / 2.)]

rawDescription: pulling key by place from dictionary using pandas

description: Pulling key by place from dictionary using pandas


code: len("9P/Tempel 1                      ")

rawDescription: read a table according to a certain number of characters

description: Read a table according to a certain number of characters


code: newstr = oldstr.replace("M", "")

rawDescription: How to delete a character from a string using python?

description: Delete a character from a string using python


code:
def acorr(x, ax=None):
    if ax is None:
        ax = plt.gca()

    x = x - x.mean()

    autocorr = np.correlate(x, x, mode='full')
    autocorr = autocorr[x.size:]
    autocorr /= autocorr.max()

    return ax.stem(autocorr)

fig, ax = plt.subplots()
acorr(data)
plt.show()

rawDescription: bug of autocorrelation plot in matplotlib‘s plt.acorr?

description: Bug of autocorrelation plot in matplotlib‘s plt.acorr


code:
lis=['abc' , 'def', 'ghi']
[list(x) for x in zip(*lis)]

rawDescription: how to make a list of first characters in from list of strings

description: Make a list of first characters in from list of strings


code:
val = int("9a", base=16)
val
hex(val + 1)
str(val + 1)

rawDescription: how to do a hexadecimal increment?

description: Do a hexadecimal increment


code:
from collections import Counter
ls = [1, 2, 3, 3]
c = Counter(ls)
[x for x in ls if c[x] == 1]

rawDescription: Remove duplicates from list, including original matching item


code:
to = Suppress(Literal('to'))
src = Group(ZeroOrMore(Word(alphas) + ~FollowedBy(to)) + Word(alphas)).setResultsName('src')
dst = OneOrMore(Word(alphas)).setResultsName('dst')
exp = src + to + dest
phase = "Sao Paulo to Rio de Janeiro"

# parse input string
s = exp.parseString( phase )

rawDescription: How using literal to separate one or more words?


code:
h, l = ax.get_legend_handles_labels()
ax.legend(h, l)

rawDescription: Python's matplotlib legend in separate axis with gridspec


rawDescription: Simulating a simple physics related scenario


rawDescription: Sorting and reorganizing a CSV file as a python dictionary


code:
import inspect
{name: func
 for name, func in inspect.getmembers(filters, inspect.isfunction)
 if not name.startswith('__')}

rawDescription: Adding a modules functions automatically to a dict


code:
multiplication = 0
firstnumber = int(input("Enter a number: "))
number = firstnumber
number = firstnumber
for j in range(0, 1001):
    for i in range(0, 1001):
        multiplication = multiplication+1
        number = firstnumber * multiplication
        print(str(multiplication) + " times " + str(firstnumber) + " is " + str(number))

rawDescription: Loopin' multiplication in Python?

description: Loopin' multiplication in Python


code:
pos = b.trueCenter() - im_center
pos = galsim.PositionD(pos.x * pixel_scale , pos.y * pixel_scale)
# The image comes out as about 211 arcsec across, so we define our variable
# parameters in terms of (r/100 arcsec), so roughly the scale size of the image.
r = math.sqrt(pos.x**2 + pos.y**2) / 100
psf_fwhm = 0.9 + 0.5 * r**2   # arcsec
psf_e = 0.4 * r**1.5
psf_beta = (math.atan2(pos.y,pos.x) + math.pi/2) * galsim.radians

# Define the PSF profile
psf = galsim.Gaussian(fwhm=psf_fwhm)
psf.applyShear(e=psf_e, beta=psf_beta)

rawDescription: Interpolating PSF parameters with galsim


code:
obj.body
obj.body.createsessionresponse

rawDescription: How can i access element value in SOAP response with lxml objectify

description: Access element value in SOAP response with lxml objectify


code:
data = {}
for file in files:
    for key, value in get_data(file):
        data.setdefault([get_component(file)], {})[key] = value

rawDescription: How to associate elements in a set with multiple dict entries

description: Associate elements in a set with multiple dict entries


code:
myList = [[10, 5, 6, 7, 8], [9, 5, 6, 7, 8], [8, 5, 6, 7, 8]]
myList2 = []

for x in range(len(myList)):
        subList1 = []
        for y in range(len(myList[x])):
            subList2 = []
            for z in range(len(myList[x])):
                subList2.append(myList[x][y] - myList[x][z])
            subList1.append(subList2)
        myList2.append(subList1)

# - First loop goes through all lists in myList
# - Create an empty subList to append lists of subLists to
# - Second loop goes through all positions in list x of mylist
# - Create another empty subList2 to append the actual values to
# - Third loop does the same as loop 2.
# - Each value in myList from the second loop (y) gets - each value from myList
#        (including itself) from the third loop (z) and appended to a subList2
# - The subList2 is appended to subList1 creating a subList of subLists
# - Finally the list of subLists is appended to myList2 for each turn of the
#        first loop

rawDescription: Is there a way to divide a 2d list(list of lists) into 2 or more separate 1-dimensional lists with for loop?


rawDescription: Convert pandas df multi index to columns


code: logger = logging.getLogger("my logger")

rawDescription: Python - Avoid passing logger reference between functions?


code:
from django.db import models

class ActivityListView(ListCreateView):

    queryset = model_activity.objects.all()
    serializer_class = ActivityListSerializer
    filter_backends = (OrderingFilter,)
    # default ordering
    ordering = ('distance')

    def filter_queryset(self, queryset):
        cur_latitude, cur_longitude = self.get_cur_latitude_longitude()
        # add the distance field to sql dataset result, so that we can order by it
        queryset = queryset.annotate(
            distance=models.Func(cur_latitude, cur_longitude, 'latitude', 'longitude', function='get_distance')
        )

        return super(ActivityListView, self).filter_queryset(self, queryset)

rawDescription: Django Rest how to order on a model method


code:
for product in products(24):
    print('*'.join(map(str, product)))

rawDescription: How can I generate all possible divisor products for a number?

description: Generate all possible divisor products for a number


code: newls = [sum(ls[i:i+3]) for i in range(0, len(ls) - len(ls) % 3, 3)]

rawDescription: How to iterate through a list and sum members together

description: Iterate through a list and sum members together


rawDescription: Python: variable is undefined when calling function containing the variable


code: mylist * 2

rawDescription: numpy multiple ndarray creation at once

description: Numpy multiple ndarray creation at once


code:
try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

from Cython.Distutils import build_ext
import numpy as np

ext_modules = [Extension("CyBlack",["CyBlack.pyx"])]

setup(
    name= 'Generic model class',
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include()],
    ext_modules = ext_modules)

rawDescription: Cython program is slower than plain Python (10M options 3.5s vs 3.25s Black Scholes) - what am I missing?


code:
def distorted_inputs(data_dir, batch_size):
  """[...]"""
  filenames = ["/tmp/images.bin"]  # Or a list of filenames if you
                                   # generated multiple files in step 1.
  for f in filenames:
    if not gfile.Exists(f):
      raise ValueError('Failed to find file: ' + f)

  # Create a queue that produces the filenames to read.
  filename_queue = tf.train.string_input_producer(filenames)

  # Read examples from files in the filename queue.
  read_input = read_my_data(filename_queue)
  reshaped_image = tf.cast(read_input.uint8image, tf.float32)

  # [...] (Maybe modify other parameters in here depending on your problem.)

rawDescription: Attach a queue to a numpy array in tensorflow for data fetch instead of files?


code:
class IncludedUserSerializer(serializers.ModelSerializer):
      snippets = SnippetSerializer(source = 'snippet_set', many=True)
      comments = CommentSerializer(source = 'comment_set', many=True)

      class Meta:
          model=User
          fields = ('id','snippets', 'comments')

rawDescription: JSON API with Django Rest - 'included' attribute


rawDescription: Looking up 2nd value in a list based on a user input if first value


code:
for individual in self.population[:]:
    self.population.remove(individual)

rawDescription: updating a list in python

description: Updating a list in python


code:
s1 = Shop(name="First Shop", mall = Mall.objects.get(name="Super Mall"))
s2 = Shop(name="Second Shop", mall = Mall.objects.get(name="Super Mall"))
s1.save()
s2.save()
Shop.objects.all()

rawDescription: How do I create this object with the models I have set up?

description: Create this object with the models I have set up


code:
def main(f):
    pass

if __name__ == '__main__':
    files = sys.argv[1:] # the first argument is the name of the program
    for f in files:
        main(f)

rawDescription: Multiple if _name_ in python

description: Multiple if _name_ in python


code:
def test_dict_for_key(dictionary, key, function):
    for test_key, value in dictionary.items():
        if key == test_key:
            dictionary[key] = type(value)(map(function, value))
        if isinstance(value, dict):
            test_dict_for_key(value, key, function)

rawDescription: Iterate over a list inside a nested dictionary


code:
from registration.forms import RegistrationForm

class UserRegistrationForm(RegistrationForm):
    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields.pop('password2')

rawDescription: Removing second password input from django-registration form


code:
length=int(input("Enter the length of the sequence: "))
count=0
num1=int(input("Enter number "+str(1)+ ": "))
for i in range(length-1):
    num2=int(input("Enter number "+str(i+2)+ ": "))
    if((num1%2==1) and (num2%2==1)):
        count=count+1
    num1=num2

print("The number of pairs of adjacent odd numbers is "+str(count))

rawDescription: Calculating number of adjacent odd numbers


code:
def isIt(arg):
    return (lightweightFunction(arg) and superExpensiveFunction(arg))

rawDescription: In var = func(), Is func() evaluated right away or when var is needed?


code: (value, regtype) = wreg.QueryValueEx(key, "DefaultConnectionSettings")

rawDescription: Editing a REG_BINARY using _winreg

description: Editing a REG_BINARY using _winreg


rawDescription: What does python3 do with the methods passed to the "key" argument of sorted()?


code:
import re

extract_number = re.compile('\[(\d+\.\d+)\]')

def sort_key(entry):
    return float(extract_number.search(entry).group(1))

rawDescription: Very specific sorting in Python

description: Very specific sorting in Python


code:
c.execute('''
    create table x2_new (
        freq INT, w1 INT, w2 INT,
        FOREIGN KEY(w1) REFERENCES lex(wID),
        FOREIGN KEY(w2) REFERENCES lex(wID),
        PRIMARY KEY(w1, w2) )
''')
c.execute('insert into x2_new select * from x2')
c.execute('drop table x2')
c.execute('alter table x2_new rename to x2')
conn.commit()

rawDescription: Trouble with a join statement in SQLite

description: Trouble with a join statement in SQLite


code:
import sys
from __future__ import print_function
try:
    # Python 3
    import builtins
except ImportError:
    # Python 2
    import __builtin__ as builtins

def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
    builtins.print(*args, sep=sep, end=end, file=file)
    if flush:
        file.flush()

rawDescription: Need Python 3.4 version of print() from __future__


code:
import os

def index(request):
        os.chdir("/home/ubuntu/newproject/static")
        files = []
        for file in os.listdir("."):
            files.append(file)
        return render(request, 'sslcert/index.html',dict(files=files))

rawDescription: Django: Use a variable from a view in a template


code: my_array = np.ones((100,3), dtype=float)

rawDescription: how to deal in a pythonic way with list of arrays or single array

description: Deal in a pythonic way with list of arrays or single array


code:
amount = int(input("How many employees?: "))
if amount <= 0:
    print("You cannot have 0 or less.")
name = []
salary = []
length = len(salary)
MAX_SALARY = 200000
mini = MAX_SALARY + 1
maxi = -1
mini_idx = -1
maxi_idx = -1

for i in range(amount):
    employee = input("What is the employee's name?: ")
    name += [employee]
    earned = -1
    while earned >= 0 and earned <= MAX_SALARY:
        earned = int(input("How much is the salary? It cannot be less than 0 or over $200,000: "))
    salary += [earned]
    total += earned
    if earned < mini:
        mini = earned
        mini_idx = i
    if earned > maxi:
        maxi = earned
        maxi_idx = i

rawDescription: Printing Employee and Salary from parallel array in Python


code: '|this is|my|made up        string '

rawDescription: How can I trim the whitespace immediately preceding and following a given character in python?

description: Trim the whitespace immediately preceding and following a given character in python


code:
filename = "EPG CRO 24 Kitchen 09.2013.xsl"
filename.find("2013|09 ")

rawDescription: Python Regex or Filename Function

description: Python Regex or Filename Function


code:
syn0 = (np.random.random((784,len(train_sample))) - 0.5) / 4
syn1 = (np.random.random((len(train_sample),1)) - 0.5) / 4

rawDescription: Neuro Network on MNIST--Result is not expected


code:
with open("myfile.txt") as fh:
    coords = []
    for line in fh:
        line = line.strip('()\n')  # Get rid of the newline and  parentheses
        line = line.split(', ')  # Split into two parts
        c = tuple(float(x) for x in line)  # Make the tuple
        coords.append(c)

rawDescription: Converting text document coordinates 'x, y' to float point list object


code: radecs.dec > - 10 * u.degree

rawDescription: How to sort through a list of observable coordinates?

description: Sort through a list of observable coordinates


code: (5 + computer_throw - thrw) % 5;

rawDescription: Values not returning correctly when playing Rock-Paper-Scissors type game


code: libpd_float('recvr', 323.290)

rawDescription: Sending messages from Python to a Pure Data patch via libPd


code:
from collections import Counter

with open(fileName, "rb") as inputFile:
    wordCount = Counter(w.replace('?', '')
        for line in inputFile for w in line.split())

rawDescription: Removing a char from String in Python

description: Removing a char from String in Python


code:
def main():
    directory = load_data()
    threshold, fft_size = 10, 1000

    prescreen_fn(directory,threshold)
    plot_prescreen_hits(directory)
    extract_features(directory,fft_size)
    generate_train_test(directory)
    SVM_train_test(directory)

def prescreen_fn(directory, threshold):
    """A prescreen function that is run. Ideally this would be a
    more informative docstring."""
    pass

def plot_prescreen_hits(directory):
    pass

def extract_features(directory,fft_size):
    pass

def generate_train_test(directory):
    pass

def SVM_train_test(directory):
    pass

def load_data():
    pass

if __name__ == '__main__':
    main()

rawDescription: Pythonian structure?

description: Pythonian structure


code:
from itertools import groupby
from operator import itemgetter

A = ['T', 'D', 'Q', 'D', 'D']
sessionid = [1, 1, 1, 2, 2]

for k, g in groupby(zip(sessionid, A), itemgetter(0)):
    print('{}: {}'.format(k, list(list(zip(*g))[1])))

rawDescription: Python group two lists

description: Python group two lists


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

class Player(models.Model):
    name = models.CharField()
    team = models.ForeignKey(Team)

class Match(models.Model):
    number = models.IntegerField()
    who = models.ForeingKey(Team,related_name="as_host")
    guest = models.ForeingKey(Team,related_name="as_guest")

class PlayerStats(models.Model):
    player = models.ForeignKey(Player)
    goals = models.IntegerField('Strzelone Bramki')
    match = models.ForeignKey(Match)

    class Meta:
        unique_together = ('player', 'match')

rawDescription: Django collect elements from database

description: Django collect elements from database


rawDescription: Most efficient Django query to return results spanning multiple tables


code:
def mean(samplelists):
    means = []
    n = float(len(samplelists[0]))
    for sample in samplelists:
        mean = sum(sample)/n
        means.append(mean)
    return means

calc_means(repeat_sample(large_array))

rawDescription: Python 3.1 - Memory Error during sampling of a large list


code:
Output
{'administrator': {'is_admin': True,
                   'is_author': False,
                   'name': 'Admin',
                   'pw': '33e7cb694fb6fb2f848af6774d9ff138'},
 'berit': {'is_admin': False,
           'is_author': False,
           'name': 'berit',
           'pw': '00c10978330d65eb0cb739a629b6ed15'}}

rawDescription: changing data in a struct in python

description: Changing data in a struct in python


code: [random.uniform(1.0e5, 3.0e10) < 1e8 for _ in range(10000)].count(True)

rawDescription: Generate random scientific notation float in python


code:
lst = ['a', 'b', 'c', 'd']
dict([ x for x in enumerate(lst) ])

rawDescription: Labelling nodes in networkx

description: Labelling nodes in networkx


code:
# first, generate some fake data:
m, n = 5, 4            # rows & cols, represents dimensions of original image
D = NP.random.randint(0, 10, m*n).reshape(m, n)
D

rawDescription: Efficiently re-shaping a numpy ndarray from 2-D to 3-D based on elements from 2-D


code:
class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello world! About.
')

class AboutPage_v2(webapp2.RequestHandler):
    def get(self):
        template_values = {

        }

        template = env.get_template('about_v2.html')
        self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/about_v2.html', AboutPage_v2)],

                              debug=True)

rawDescription: Using Google App Engine how do I open an html page?


rawDescription: Python - return tuple with integer range where multiple lists of integers match


code:
Peso
Ruble

rawDescription: Split one txt to several txt files with particular name in Python


code:
aBackSlash = '\\'
print(aBackSlash)

rawDescription: python prefix string with backslash

description: Python prefix string with backslash


code:
from pyramid.security import Authenticated

@view_config(route_name='home', effective_principals=Authenticated, renderer='dashboard.jinja2')
def dashboard_view(request):
    return {}

@view_config(route_name='home', renderer='login.jinja2')
def login_from_home_view(request):
    return {}

rawDescription: python pyramid, render user dashboard at root url when logged in

description: Python pyramid, render user dashboard at root url when logged in


code:
#path is the string that you want to do replacements in.
#replacementDict is the dict containing the key-value pairs mentioned in your post.
def iterateLSystem(path, replacementDict):
    #strings aren't mutable, so we make a mutable list version of path
    listPath = list(path)
    for i in range(len(listPath)):
        currentChar = listPath[i]
        if currentChar in replacementDict:
            listPath[i] = replacementDict[currentChar]
    #glob listPath back into a single string
    return "".join(listPath)

rawDescription: Working with python dictionary notation

description: Working with python dictionary notation


code:
idx1 = np.argmin(dist, axis = 0)
idx1

rawDescription: Interleave two numpy arrays based on element distances (python)


code:
def _mapkey(self, key):
    return struct.pack('>II', key)
def _unmapkey(self, key):
    return struct.unpack('<II', key)

rawDescription: Python dictionary with two keys with shelve


code:
savefile = file("backup.json", "w")
savefile.write(json.dumps(li))

rawDescription: Saving an Element in an Array Permanently


code:
class Question(db.Model):
    text = db.StringProperty()

class Answer(db.Model):
    text = db.StringProperty()
    question = db.ReferenceProperty(Question,
                               required=True,
                               collection_name='answers')

rawDescription: how to create a survey that has 5 multiple choices

description: Create a survey that has 5 multiple choices


code:
sheet = book.get_sheet(0)
sheet.header_str = 'what you prefer'
sheet.footer_str = 'things'

rawDescription: header/footer in xlwt (python).

description: Header/footer in xlwt (python).


rawDescription: Python: Print first dictionary value for all keys on first line, second on second etc


code:
x = u + at
y = v + bt
z = w + ct

rawDescription: Detect if a cube and a cone intersect each other?


code: d = dict(chunk.split(None,1) for chunk in denfile.split('>') if chunk)

rawDescription: Search name and extract corresponding entries from huge file - Fastest possible approach - Python and Regex


code:
with open('output.txt','w') as outfile:
    for k in sorted(d.keys()):
        v = d[k]
        print('{}\t{}\t{}\t{}'.format(k[0],k[1],k[2],','.join(v)),file=outfile)

rawDescription: python: merge lines with common fields

description: Python: merge lines with common fields


code:
pymongo.MongoClient(
    "mongodb://user:password@host1,host2,host3/dbname?replicaSet=rsname",
    read_preference=pymongo.ReadPreference.SECONDARY)

rawDescription: Non-Localhost PyMongo Client

description: Non-Localhost PyMongo Client


code:
link_name = [link for link in open('links.txt', 'r')]
print(link_name)

rawDescription: How do I store all the links into the variable while allowing them to be read separately? (Python)

description: Store all the links into the variable while allowing them to be read separately? (Python)


rawDescription: python String interpolation vs another method

description: Python String interpolation vs another method


code:
d = {'a': 1}
extras = [{'b':2}, {'c':4}]
map(d.update, extras)
d

rawDescription: Python 3 map dictionary update method to a list of other dictionaries


code:
objectId = 'someIdentifier'

info = cluster[objectId]

rawDescription: Python clustering from .csv file as input


rawDescription: Get files and put into list in another method


code:
class Foo(object):
    def __format__(self, spec):
        if spec == 'f':
            return 'fractions used'
        else:
            return 'decimals used'

format(Foo(), 'f')
format(Foo(), 'g')

rawDescription: String output modifiers in Python

description: String output modifiers in Python


rawDescription: How do you calculate correlation between all columns in a DataFrame and all columns in another DataFrame?

description: Calculate correlation between all columns in a DataFrame and all columns in another DataFrame


code:
deltas = [d for _, d in get_time_deltas(INFILE)]
average = sum(deltas) / len(deltas)

rawDescription: How do I create a list of timedeltas in python?

description: Create a list of timedeltas in python


rawDescription: python - looping through values in a string

description: Python - looping through values in a string


code:
d = {'AL' : 'Alabama', 'AK' : 'Alaska',}
d.items()

rawDescription: A more elegant way of creating tuples of tuples from lists


code:
subprocess.Popen(["ssh", user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./prerun"])
time.sleep(5)
subprocess.Popen(["ssh", user@machine2, "cd /dcd-netapp1/test/test-priority-v6; ./run"])
time.sleep(1800)
subprocess.Popen(["ssh", user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./postrun"])
subprocess.Popen(["ssh", user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./graph_results"])

rawDescription: Zombie ssh process using python subprocess.Popen


code: t = threading.Timer(300,send_email('Tank temperature Overheat',tank_temp))

rawDescription: Python, threading.timer object will not run function timer?


rawDescription: Convert a jpg to a list of lists

description: Convert a jpg to a list of lists


code:
def recur(v, times):
    if (times != 0):
        v = vclass.makesomething(v,a).attribute1()
        return recur(v, times-1)
    return v

rawDescription: writing a recurring code that takes previous defined instance and creates new one

description: Writing a recurring code that takes previous defined instance and creates new one


code:
def scrape_prices(self):
    self.driver.get(link)

    WebDriverWait(self.driver, 200).until(wait_for_price((By.CLASS_NAME, "olpOfferPrice")))
    s = BeautifulSoup(self.driver.page_source)

    return s

rawDescription: Amazon web scraping

description: Amazon web scraping


code:
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7',
     'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'}

order = {
    'file_name':    0,
    'item_name':    1,
    'item_height':  2,
    'item_width':   3,
    'item_depth':   4,
    'texture_file': 5
}

rawDescription: sort dictionary by another dictionary

description: Sort dictionary by another dictionary


rawDescription: How to change colours of nodes and edges of bipartite graph in networkX?

description: Change colours of nodes and edges of bipartite graph in networkX


code:
initList = [b'script', b'-compiler', b'123cds', b'-algo', b'timing']
resultList = [str(x) for x in initList ]

rawDescription: editing List content in Python

description: Editing List content in Python


rawDescription: Converting Pandas groupby.groups result into dataframe, using index tuple value as row and columns name of dataframe


code:
class A(object):
    def m(self):
        print('m')

class B(A): pass

rawDescription: Usage of Python 3 super()

description: Usage of Python 3 super()


code:
import re
re.findall(r"(?<=@)\w+", "@dasweo where you at?")

rawDescription: Simple regex to get a twitter username from a string


code: tree = nx.dfs_tree(G, 4)

rawDescription: How can i get directed tree from graph?

description: Get directed tree from graph


code:
for i in range(10):
    foo(i)

rawDescription: Does Python have a default Caching service


code:
import pytz
import datetime
naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
localtz = pytz.timezone('America/Los_Angeles')
date_aware_la = localtz.localize(naive_date)
print(date_aware_la)   # 2013-10-21 08:44:08-07:00

rawDescription: Python: How to convert a timezone aware timestamp to UTC without knowing if DST is in effect


rawDescription: Extracting elements from dictionary of list of dictionaries


code:
from numpy import array
a = array( [[2,3,4], [3,4,5]] )

rawDescription: How to save a list as numpy array in python?

description: Save a list as numpy array in python


rawDescription: Split and retain character of split python


code: P

rawDescription: For Loop alternative Pandas Python

description: For Loop alternative Pandas Python


code: {{ raw|unquote_raw }}

rawDescription: Django urldecode in template file

description: Django urldecode in template file


rawDescription: merge sift descriptor matrix, numpyarray

description: Merge sift descriptor matrix, numpyarray


code:
# roll the nth axis to the 0th position
np.rollaxis(a, n, 0)

# index odd-numbered slices along the 0th axis
np.rollaxis(a, n, 0)[1::2]

# roll the 0th axis back so that it lies before position n + 1 (note the '+ 1'!)
np.rollaxis(np.rollaxis(a, n, 0)[1::2], 0, n + 1)

rawDescription: numpy take can't index using slice

description: Numpy take can't index using slice


code:
class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

rawDescription: Python enum, when and where to use?

description: Python enum, when and where to use


code:
from pyparsing import *
field_name = field_val = Word(alphanums)
colon = Suppress(Literal(':'))

expr = Dict(Group(
    field_name +
    nestedExpr(content =
        Dict(delimitedList(
            Group(field_name + colon + field_value),
            delim = ';'
        ))
    )
))

rawDescription: Can't get pyparsing Dict() to return nested dictionary


code:
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.styles import Color, Fill
from openpyxl.cell import Cell

# Load the workbook...
book = load_workbook('foo.xlsx')

# define ws here, in this case I pick the first worksheet in the workbook...
#    NOTE: openpyxl has other ways to select a specific worksheet (i.e. by name
#    via book.get_sheet_by_name('someWorksheetName'))
ws = book.worksheets[0]

## ws is a openpypxl worksheet object
_cell = ws.cell('C1')

# Font properties
_cell.style.font.color.index = Color.GREEN
_cell.style.font.name = 'Arial'
_cell.style.font.size = 8
_cell.style.font.bold = True
_cell.style.alignment.wrap_text = True

# Cell background color
_cell.style.fill.fill_type = Fill.FILL_SOLID
_cell.style.fill.start_color.index = Color.DARKRED

# You should only modify column dimensions after you have written a cell in
#     the column. Perfect world: write column dimensions once per column
#
ws.column_dimensions["C"].width = 60.0

rawDescription: Setting styles in Openpyxl

description: Setting styles in Openpyxl


code:
def my_view(request):
    pdf_stream = process_latex(
        'latex_template.tex',
        context=RequestContext(request, {'context_obj': context_obj})
    )
    return HttpResponse(pdf_stream, content_type='application/pdf')

rawDescription: Automating PDF generation

description: Automating PDF generation


code:
import importlib
exec(compile(importlib.util.find_spec('http.server').loader.get_source(
    'http.server'), 'server.py', 'exec'), dict(__name__='__main__'))

rawDescription: Start SimpleHTTPServer in python

description: Start SimpleHTTPServer in python


code: print(datName, file=out)

rawDescription: write to file in python3

description: Write to file in python3


code: result = [ [ 1 if (r[0] <= age <= r[1]) else 0 for r in ( (i-2,i) for i in range(50,100,2)) ] for age in ages]

rawDescription: Python List with ranges

description: Python List with ranges


code:
for c in data:
    g.append(c['club_name'])
    identity.append(c['url'])

rawDescription: Consuming JSON into django view

description: Consuming JSON into django view


code:
list_products = []
for i in range(3):
     list_products.append(input("First Product: "))
product1, product2, product3 = list_products

rawDescription: Python: list problens

description: Python: list problens


code:
BIT_LEN = 6
NUM_INTS = 1 << BIT_LEN         # 0b1000000
BIT_MASK = NUM_INTS - 1         #  0b111111
HIGH_BIT = 1 << (BIT_LEN - 1)   #  0b100000

def to2c(num):
    """Returns the two's complement representation for a signed integer."""
    return num & BIT_MASK

def from2c(bits):
    """Returns the signed integer for a two's complement representation."""
    bits &= BIT_MASK
    if bits & HIGH_BIT:
        return bits - NUM_INTS

rawDescription: What is good way to negate an integer in binary operation in python?


rawDescription: Need help in understanding how the solution to rotate N*N matrice by 90 degree in place works


code:
import heapq
heapq.nlargest(2, list_of_t, key=lambda x:x[1])

rawDescription: extracting tuples based on values in python

description: Extracting tuples based on values in python


code: players = [player1, player2]

rawDescription: I am having trouble exiting my infinite loop in pygame


code:
def find_files(root,filename):
    for directory,subdirs,files in os.walk(root):
        if filename in files:
            yield os.join(root,directory,filename)

rawDescription: Python Glob.glob: a wildcard for the number of directories between the root and the destination


code: found = re.findall(r'\n*(A.*?\n\$\$)\n*', data, re.M | re.S)

rawDescription: How can I split a text file into multiple text files using python?

description: Split a text file into multiple text files using python


code:
class TestMyProgram(unittest.TestCase):

    def setUp(self):
        from program import Program
        self.program = Program()

    def test_write_tokens_to_config(self):
        from mock import mock_open
        from mock import call
        self.program._access_token = 'aaa'
        self.program._refresh_token = 'bbb'
        with mock.patch('program.ConfigParser.SafeConfigParser.read'):
            m = mock_open()
            with mock.patch('__builtin__.open', m, create=True):
                self.program.write_tokens_to_config()
                m.assert_called_once_with(self.program.CONFIG_PATH, 'wb')
                handle = m()
                handle.write.assert_has_calls(
                    [
                        call('[Token]\n'),
                        call('access_token = aaa\n'),
                        call('refresh_token = bbb\n'),
                    ]
                )

rawDescription: Python SafeConfigParser mocking

description: Python SafeConfigParser mocking


code:
for k, v in counts.items():
    print("{}  and {} are paired {} time(s)".format(k[0], k[1], v))

rawDescription: Count the elements in a csv file with python


code:
from fnmatch import fnmatch

def namesearch(pattern, dictionaries):
    return [d for d in dictionaries if fnmatch(d['name'], pattern)]

rawDescription: How to retrieve dicts from a list of dicts using wildcard key value

description: Retrieve dicts from a list of dicts using wildcard key value


code:
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
plt.savefig('test.png', bbox_inches='tight')

rawDescription: Reduce left and right margins in matplotlib plot


code: from important import dothis, dothat

rawDescription: Always include file when importing module in python


code:
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FuncFormatter
fig, ax = plt.subplots(1, 1)

def minor_formatter(x, ind):
    # only format if we don't overlap with a major tick
    if np.mod(x, 1) < .1:
        return ''
    return '{:.1f}'.format(np.mod(x, 1))

ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(MultipleLocator(.5))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_formatter))
# label size sets the font size, pad sets the distance from the spine
ax.xaxis.set_tick_params(which='minor', labelsize=8, pad=8)

ax.set_xlim(0, 10)

rawDescription: Manipulate xticks, need every second xtick to just be the decimal and smaller font


code:
import logging
logging.basicConfig(datefmt="%A %d, %B %Y %I:%M:%S %p %Z", format='Log Created: %(asctime)-15s %(message)s')
logging.warn('Foo bar baz!')

rawDescription: Writing variables with .write() Python 3


code:
import Tkinter as tk
from PIL import ImageTk

root = tk.Tk()

im = ImageTk.PhotoImage(file='test.png')
panel = tk.Label(root, image=im)
panel.pack(fill=tk.BOTH, expand=True)

root.mainloop()

rawDescription: How can I display a matplotlib interactive window without any of the controls visible?

description: Display a matplotlib interactive window without any of the controls visible


rawDescription: Is there a way to access the context from everywhere in Django?


code:
with open('FILE1') as file:
    file1_contents = { tuple(line.split()) for line in file }

rawDescription: Speed the process of matching two columns using python


code:
def make_rgb_transparent(rgb, bg_rgb, alpha):
    return [alpha * c1 + (1 - alpha) * c2
            for (c1, c2) in zip(rgb, bg_rgb)]

rawDescription: calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib

description: Calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib


code:
import json
import re
import requests
from bs4 import BeautifulSoup

url = 'https://xueqiu.com/yaodewang'
headers = {
    'user-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'
}
r = requests.get(url, headers=headers).content
soup = BeautifulSoup(r, 'lxml')

pattern = re.compile(r"SNB\.data\.statuses = ({.*?});", re.MULTILINE | re.DOTALL)
script = soup.find("script", text=pattern)

data = json.loads(pattern.search(script.text).group(1))
for item in data["statuses"]:
    print(item["description"])

rawDescription: Scrap the article with Python 3.4 and BeautifulSoup ,Requests


code:
def first_read():
    codecs.open(file, 'r', 'utf8').readlines()

def line_by_line():
    for i in codecs.open(file, 'r', 'utf8'):
        pass

def at_once():
    for i in codecs.open(file, 'r', 'utf8').readlines():
        pass

first_read()
cProfile.run('line_by_line()')
cProfile.run('at_once()')

rawDescription: If RAM isn't a concern, is reading line by line faster or reading everything into RAM and access it? - Python


code:
with open('output.csv', 'wb') as f:
    w = csv.writer(f, delimiter='\t')
    w.writerow([''] + od.keys())
    for key in keys:
        w.writerow([key] + [subdct.get(key, '') for subdct in od.values()])

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code:
height,direction,speed
1,2,3
3,2,1

rawDescription: Write text from EXCEL to text as a LIST using PYTHON or other programming method


code:
r = ET.fromstring('a')
ET.tostring(r)
ET.register_namespace('','blah')
r = ET.fromstring('a')
ET.tostring(r)

rawDescription: Saving XML using ETree in Python. It's not retaining namespaces, and adding ns0, ns1 and removing xmlns tags


code: df2 = df1.groupby(f(df['ColA'], df['ColB'])).sum()

rawDescription: pandas: groupby using a generic key function acting on one of more columns

description: Pandas: groupby using a generic key function acting on one of more columns


code:
with open('ex4.txt') as inf:
    data = set()
    for line in inf:
            line = line.split()
            if len(line)==3:
                    data.add(tuple(line))

data
list(data)

rawDescription: Sorting items in a text file in python

description: Sorting items in a text file in python


code:
@category(Test)
def f():
    ...

rawDescription: How can I know from where the method is called?

description: Know from where the method is called


code: result = result.most_common()

rawDescription: counting common key-value pairs in a list of dictionaries

description: Counting common key-value pairs in a list of dictionaries


code:
s='N=1,E=4,S=7'
dict(t.split('=') for t in s.split(','))

rawDescription: From string in a csv cell to dict

description: From string in a csv cell to dict


code:
# Get a copy of input as the output
out = initial_values.copy()

# Get sorted indices
sorted_index = np.argsort(out)

# Mask of elements that would be made zero for sure and zero them
mask = out.sum() < out[sorted_index].cumsum()
out[sorted_index[mask]] = 0

# There might be one element left to make the sum absolutely zero.
# Make it less negative to make the absolute sum zero.
out[sorted_index[np.where(mask)[0][-1]+1]] -= out.sum()

rawDescription: Limit sum of entries in numpy array by adjusting negative entries


code:
print("What do you wanna do?")

input1 = input()

complex_inputs = ["stab this guy", "punch this guy"]

while input1.lower() not in complex_inputs:
    print("Sorry didn't catch that")
    print("What do you wanna do?")
    input1 = input()

if input1 == "Stab this guy" or input1 == "stab this guy":
    print("You stabbed that guy and killed him.")

elif input1 == "Punch this guy" or input1 == "punch this guy":
    print("You punched him...")

rawDescription: I would like to implement a loop but I don't know how to go about it


code:
from itertools import izip
i = iter(a)
b = dict(izip(i, i))

rawDescription: Convert a list to a dictionary in Python


code: queryset = organisation.datapoint_set.filter(timestamp__gte=startDate, timestamp__lte=endDate).values_list('timestamp', flat=True)

rawDescription: Return a list of missing values?

description: Return a list of missing values


rawDescription: How to tell if AWS Elastic Network Interface (ENI) has a public IP address using Python boto?

description: Tell if AWS Elastic Network Interface (ENI) has a public IP address using Python boto


code:
all_ids = [ each['obj_id'] for each in ds ] # get 'ds' from above snippet
unique_stuff = [ ds[ all_ids.index(id) ] for id in set(ids) ]

rawDescription: Remove duplicates from json data

description: Remove duplicates from json data


code:
sentence = ['AASFG', 'BBBSDC', 'FEKGG', 'SDFGF']
[word for word in sentence.split() if word.endswith("GF")]

rawDescription: Searching for Unicode characters in Python


code:
min_index = bst.min()
old_index=lookup[curr_term] # O(1)
bst.delete(old_index) # O(logk)
bst.insert(new_index) # O(logk)

rawDescription: Implementing Basic Efficient "Search" Algorithm: Python


code:
myClassName = types['extension1']
myClass = mappingDict[myClassName]

rawDescription: Dynamically call python-class defined in config-file


code: df['date'] = [i.date() for i in df.index]

rawDescription: FX Data - analyse intraday data

description: FX Data - analyse intraday data


code: regex = re.compile('((\d+,?)+)')

rawDescription: python - regex search and findall

description: Python - regex search and findall


code:
def find_files(directory, pattern):
    directory = "c:\\TEST"
    for root, dirs, files in os.walk(directory):
        for basename in fnmatch.filter(files, pattern):
            yield os.path.join(root, basename)

rawDescription: Match data in two files

description: Match data in two files


code: instance.remove_tag('foo', 'bar')

rawDescription: How to update/change tag values of classic EC2 instances using boto library

description: Update/change tag values of classic EC2 instances using boto library


code:
def combinations(input_list, acc=''):

    if not input_list:
        yield acc
        return

    next_val = input_list[0]

    for rest in combinations(input_list[1:], acc):
        yield rest

    acc += next_val

    # In python 3.2, you can use "yield from combinations(input_list[1:], acc)"
    for rest in combinations(input_list[1:], acc):
        yield rest

rawDescription: What's the most memory efficient way to generate the combinations of a set in python?


code:
#---------------------------------------------------
class TextControl(ScalarControl):
    """Textual input control.

    Covers:

    INPUT/TEXT
    INPUT/PASSWORD
    INPUT/HIDDEN
    TEXTAREA

    """
    def __init__(self, type, name, attrs, index=None):
        ScalarControl.__init__(self, type, name, attrs, index)
        if self.type == "hidden": self.readonly = True
        if self._value is None:
            self._value = ""

    def is_of_kind(self, kind): return kind == "text"

rawDescription: Filling textarea with Python mechanize module


code:
def relocate_path(new_root, path):
    return os.path.join(new_root, path.lstrip('/'))

rawDescription: Most pythonic way to relocate a path to a new root directory


code:
# capture
s = "Example {String}"
replaced = re.sub(r'({).*?(})', r'\1a\2', s)

# lookaround
s = "Example {String}"
replaced = re.sub(r'(?<={).*?(?=})', r'a', s)

rawDescription: Python - Replace part of regex?

description: Python - Replace part of regex


rawDescription: Nested grouping Regular Expression in Python


code:
from sqlalchemy import exists

session.query(B).filter(exists().where(B.a_id==A.id, A.a_property_special > 3.0))

rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


code:
start_time - end_time
abs(start_time - end_time)

rawDescription: Converting date into hours

description: Converting date into hours


code:
def secondpartition(s):
    parts = s.split('.', 2)
    if len(parts) <= 2:
        return s
    return parts[-1]

rawDescription: How do I remove from the beginning to the 2nd specific character of a string?

description: Remove from the beginning to the 2nd specific character of a string


code: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)

rawDescription: Generating Mouse-Keyboard combination events in python


code: print(*('*'*n), sep='-'*m) #this can fail if you use `'**'` instead of `'*'`

rawDescription: Printing "*" characters separated by dashes with the print function's "sep" paramter


code:
a = Singleton(0)
for i in range(32):
    a = Concatenation(a, Mapper({0: 1, 1: 2, 2: 0}.get, a))
print(a[3000000000 - 1])

rawDescription: Generating 3 billion-th element of a sequence in python


code:
# do your plotting first, for example
x = np.arange(5, 25)
y = x * x
plt.plot(x, y)
# and then the ticks
plt.xticks([8, 15, 22], ['foo', 'bar', 'baz'])
# And finally show the plot
plt.show()

rawDescription: Scikit learn confusion matrix

description: Scikit learn confusion matrix


code:
mytest = dict()
for each_line in data:
    number, name = line.split(None,1)
    mytest[number] = name

rawDescription: parsing text file without splitting up multi-word names

description: Parsing text file without splitting up multi-word names


rawDescription: Python file keyword argument?

description: Python file keyword argument


code: t = parser.parse("18:36").time()

rawDescription: Python: How can I convert string to datetime without knowing the format?


rawDescription: Numpy bincount() with floats

description: Numpy bincount() with floats


code:
from pybrain.tools.shortcuts import buildNetwork
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.datasets import SupervisedDataSet,UnsupervisedDataSet
from pybrain.structure import LinearLayer
ds = SupervisedDataSet(21, 21)
ds.addSample(map(int,'1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6'.split()),map(int,'1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6'.split()))
ds.addSample(map(int,'1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6'.split()),map(int,'1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7'.split()))
net = buildNetwork(21, 20, 21, outclass=LinearLayer,bias=True, recurrent=True)
trainer = BackpropTrainer(net, ds)
trainer.trainEpochs(100)
ts = UnsupervisedDataSet(21,)
ts.addSample(map(int,'1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7'.split()))
[ int(round(i)) for i in net.activateOnDataset(ts)[0]]

rawDescription: Request for example: Recurrent neural network for predicting next value in a sequence


code:
def translate(tpl):
    result = []
    t0 = [' '.join([nltk.tag.tuple2str(item) for item in sent]) for sent in tpl]
    for t in t0:
        t = re.sub(r'/NUM', '/N', t)
        t = [nltk.tag.str2tuple(item) for item in t.split()]
        result.append(t)
    return result

rawDescription: operating on embedded tuples/strings, python

description: Operating on embedded tuples/strings, python


rawDescription: How do you evaluate a certain part of an array in Python?

description: Evaluate a certain part of an array in Python


code: ar[numpy.where(ar == 'c')]

rawDescription: python matrix search

description: Python matrix search


code:
company = {"AXP": "American Express", "BIDU": "Baidu"}
stock_index = {"GOOG": "Google"}

rawDescription: Python str.contains from two or more dictionaries


code:
release = pypi.release_data('numpy', '1.8.1')
release['download_url']
release['platform']
release['downloads']

rawDescription: Searching PyPI by topic

description: Searching PyPI by topic


code:
import time
import unittest

value = None

def setup():
    global value
    value = 1

class TestExampleTwo(unittest.TestCase):
    def test_one(self):
        time.sleep(3)
        self.assertEqual(1, value)

class TestExampleThree(unittest.TestCase):
    def test_one(self):
        time.sleep(4)
        self.assertEqual(1, value)

rawDescription: How to benchmark unit tests in Python without adding any code

description: Benchmark unit tests in Python without adding any code


code:
import math
import sys
if sys.version_info[0] < 3:
  from Tkinter import Tk, Button, Frame, Canvas, Scrollbar
  import Tkconstants
else:
  from tkinter import Tk, Button, Frame, Canvas, Scrollbar
  import tkinter.constants as Tkconstants

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pprint, inspect

frame = None
canvas = None
ax = None

def printBboxes(label=""):
  global canvas, mplCanvas, interior, interior_id, cwid, figure
  print("  "+label,
    "canvas.bbox:", canvas.bbox(Tkconstants.ALL),
    "mplCanvas.bbox:", mplCanvas.bbox(Tkconstants.ALL),
    "subplotpars:", figure.subplotpars.__dict__ )

def addScrollingFigure(figure, frame):
  global canvas, mplCanvas, interior, interior_id, cwid
  # set up a canvas with scrollbars
  canvas = Canvas(frame)
  canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW)

  xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)
  yScrollbar = Scrollbar(frame)

  xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW)
  yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS)

  canvas.config(xscrollcommand=xScrollbar.set)
  xScrollbar.config(command=canvas.xview)
  canvas.config(yscrollcommand=yScrollbar.set)
  yScrollbar.config(command=canvas.yview)

  # plug in the figure
  figAgg = FigureCanvasTkAgg(figure, canvas)
  mplCanvas = figAgg.get_tk_widget()

  # and connect figure with scrolling region
  cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW)
  printBboxes("Init")
  changeSize(figure, 1)

def changeSize(figure, factor):
  global canvas, mplCanvas, interior, interior_id, frame, cwid
  oldSize = figure.get_size_inches()
  print("old size is", oldSize)
  figure.set_size_inches([factor * s for s in oldSize])
  wi,hi = [i*figure.dpi for i in figure.get_size_inches()]
  print("new size is", figure.get_size_inches())
  print("new size pixels: ", wi,hi)
  mplCanvas.config(width=wi, height=hi) ; printBboxes("A")
  canvas.itemconfigure(cwid, width=wi, height=hi) ; printBboxes("B")
  canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
  tz.set_fontsize(tz.get_fontsize()*factor)
  for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
               ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(item.get_fontsize()*factor)
  ax.xaxis.labelpad = ax.xaxis.labelpad*factor
  ax.yaxis.labelpad = ax.yaxis.labelpad*factor
  #figure.tight_layout() # matplotlib > 1.1.1
  figure.subplots_adjust(left=0.2, bottom=0.15, top=0.86)
  figure.canvas.draw() ; printBboxes("C")
  print()

if __name__ == "__main__":
  global root, figure
  root = Tk()
  root.rowconfigure(1, weight=1)
  root.columnconfigure(1, weight=1)

  frame = Frame(root)
  frame.grid(column=1, row=1, sticky=Tkconstants.NSEW)
  frame.rowconfigure(1, weight=1)
  frame.columnconfigure(1, weight=1)

  figure = plt.figure(dpi=150, figsize=(4, 4))
  ax = figure.add_subplot(111)
  ax.plot(range(10), [math.sin(x) for x in range(10)])
  #tz = figure.text(0.5,0.975,'The master title',horizontalalignment='center', verticalalignment='top')
  tz = figure.suptitle('The master title')

  ax.set_title('Tk embedding')
  ax.set_xlabel('X axis label')
  ax.set_ylabel('Y label')
  print(tz.get_fontsize()) # 12.0
  print(ax.title.get_fontsize(), ax.xaxis.label.get_fontsize(), ax.yaxis.label.get_fontsize()) # 14.4 12.0 12.0

  addScrollingFigure(figure, frame)

  buttonFrame = Frame(root)
  buttonFrame.grid(row=1, column=2, sticky=Tkconstants.NS)
  biggerButton = Button(buttonFrame, text="larger",
                        command=lambda : changeSize(figure, 1.2))
  biggerButton.grid(column=1, row=1)
  smallerButton = Button(buttonFrame, text="smaller",
                         command=lambda : changeSize(figure, 0.833))
  smallerButton.grid(column=1, row=2)
  qButton = Button(buttonFrame, text="quit",
                         command=lambda :  sys.exit(0))
  qButton.grid(column=1, row=3)

  root.mainloop()

rawDescription: How to get a Matplotlib figure to scroll + resize properly in a Tkinter GUI

description: Get a Matplotlib figure to scroll + resize properly in a Tkinter GUI


rawDescription: How make Javascript new Date().toUTCString() into Python


code: final

rawDescription: How to append dictionary to a list in loop

description: Append dictionary to a list in loop


code: sorted_by_second = sorted(data, key=lambda tup: tup[1])

rawDescription: How to sort (list/tuple) of lists/tuples?

description: Sort (list/tuple) of lists/tuples


code: StatusTextVar = "Success"

rawDescription: Python 2.7: updating Tkinter Label widget content


code:
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
]

rawDescription: Page not found (404) Error in Django

description: Page not found (404) Error in Django


code:
for cdict in cdicts:
    cdict['categories'] = cdict['categories'].split()

cdicts

rawDescription: How to use a list item to address a dictionary key and append the respective value

description: Use a list item to address a dictionary key and append the respective value


code: os.read(f.fileno(), 50)

rawDescription: Read file with timeout in Python

description: Read file with timeout in Python


code: p3 = PointOnUnitCircle(pi/4)

rawDescription: Use inherited class method within __init__


code:
r.index = r.index.droplevel(0)
r

rawDescription: how to perform calculations across specific rows and columns of a crosstabulation in pandas?

description: Perform calculations across specific rows and columns of a crosstabulation in pandas


rawDescription: Group Pandas DataFrame by row name

description: Group Pandas DataFrame by row name


code:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='mode')

rawDescription: python argparse library does not read arguments

description: Python argparse library does not read arguments


code:
U = xMin - xMax
V = yMin - yMax

rawDescription: Quiver vector from high value toward low value


code:
bills = {}
while True:
    choice = input("Do you want to calculate for another person?")
    if choice.lower().startswith("y"):
        break
    person_name = input("Enter the name of the person: ")
    if not person_name:
        continue  # ask about continuing again
    bill = Bill(float(input("Check: ")), float(input("Tax: ")),
                float(input("Tip: ")))
    bill.calculate()
    print("{}'s bill:".format(person_name))
    print(*bill.advice)
    bills[person_name] = bill

rawDescription: How would I make a loop that creates instances in python 3?


rawDescription: fast way to transpose and concat csv files in python?

description: Fast way to transpose and concat csv files in python


code:
# assuming you allow your integer field to be null
class FooModel(models.Model):
    time = models.IntegerField(null=True)

qs = FooModel.objects.all()
for model in qs:
    # handle case when time is null - model.time will be None
    t = model.time or 90
    model.time = timedelta(seconds=t)

rawDescription: Django Query Result Is NoneType?

description: Django Query Result Is NoneType


rawDescription: Maximum number of elements in the path of a matrix


code:
import collections
collections.namedtuple('Conf', 'data', verbose=True)

rawDescription: Why inheriting from namedtuple results in infinite recursion in this case?


code: a[:,np.newaxis] * np.sum(m, axis=0)

rawDescription: Dot product between a matrix and a 1d-array in numpy


code:
c = np.random.rand(2,2,3,4)
c
c.ndim
c.shape

rawDescription: In Python NumPy what is a dimension and axis?


rawDescription: Differences between functools.partial and a similar lambda?


code: events['AvailabilityDelta'] = events.Login + events.Logout

rawDescription: How do I get a Pandas TimeSeries for user sessions (using Pandas or Numpy)

description: Get a Pandas TimeSeries for user sessions (using Pandas or Numpy)


code:
def check_initialize():
    if not db().select(db.auth_user.ALL).first():
        db.auth_user.insert(
            username = 'administrator',
            password = db.auth_user.password.validate('admin1234')[0],
            email = 'null@null.com',
            first_name = 'System',
            last_name = 'Administrator',
            is_admin = True,
        )

# do initialization check
cache.ram('db_initialized', lambda: check_initialize(), time_expire=None)

rawDescription: How can I create new auth_user and auth_group on Web2py running on Google App Engine (GAE)?

description: Create new auth_user and auth_group on Web2py running on Google App Engine (GAE)


rawDescription: PyPlot: Trying to generate shared legend in a subplot, but legends don't appear properly when embedded in a loop. (PDF backend)


code: getattr(t, 'foo')()

rawDescription: How do I iterate over all imported functions

description: Iterate over all imported functions


code:
def apply_recursive(ob, func):
    if not isinstance(ob, list):
        return func(ob)
    return [apply_recursive(elem, func) for elem in ob]

apply_recursive([['a','b'],[['c'],[['d']]],['e']], str.upper)

rawDescription: How to create a new nested list from a function and an existing nested list in python?

description: Create a new nested list from a function and an existing nested list in python


code:
A.objects.extra(
    select={
        'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id',
    },
    where=['b_count < 2']
)

rawDescription: Django models - how to filter number of ForeignKey objects


code:
sums = df.Smoke.groupby(df.Sex).sum()
axis('equal');
pie(sums, labels=sums.index);
show()

rawDescription: How do I plot a pie chart using Pandas with this data

description: Plot a pie chart using Pandas with this data


rawDescription: Get value using lxml

description: Get value using lxml


code:
from collections import defaultdict
histogram = defaultdict(int) # this means, "if we haven't seen a number before, set its default value to the result of int(), which is 0
for i in list_:
    histogram[i] += 1

rawDescription: Seeing if values in a list are of equal value ~Python


code:
first = lambda n : n.split()[0]
first_names = [first(name) for name in names]

rawDescription: Best way to split strings

description: Split strings


code:
timestamp_uniqify('1')
'1'
timestamp_uniqify('1')
'1A'
timestamp_uniqify('1')
'1B'
timestamp_uniqify('1')
'1C'
timestamp_uniqify('2')
'2'
timestamp_uniqify('3')
'3'
timestamp_uniqify('3')
'3A'
timestamp_uniqify('3')
'3B'

rawDescription: How would you translate this from Perl to Python?


rawDescription: Using console commands in python

description: Using console commands in python


code:
from collections import Counter

words = input_string.split()
wordCount = Counter(words)

rawDescription: How to find the count of a word in a string?

description: Find the count of a word in a string


code:
@show_guts
def foo(a,b):
    biz = str(a)
    baz = str(b)
    return biz + baz

result = foo("banana","phone")

rawDescription: Printing a function's local variable names and values


code:
def mergesort(seq):
    if len(seq)<2:
        return seq
    else:
        m = len(seq)//2
        return merge(mergesort(seq[:m]), mergesort(seq[m:]))
def merge(low, high):
    res = []
    i, j = 0, 0
    while i<len(low) and j<len(high):
        if low[i] <= high[j]:
            res.append(low[i])
            i = i+1
        else:
            res.append(high[j])
            j = j+1
    res.extend(low[i:])
    res.extend(high[j:])
    return res
mergesort([10,12,55,22,100])
mergesort(list(range(100,50,-10)))

rawDescription: simplest mergesort implementation in Python, having type troubles

description: Simplest mergesort implementation in Python, having type troubles


code: [tuple([current_token]) + tuple(sent[id] for id in idx) for idx in combinations(range(len(sent)), 2)]

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
import csv
import random

with open('filename.txt') as fin:
    lines = fin.readlines()
    random.shuffle(lines)

    rnd_str = []
    for i, line in enumerate(lines):
        if i >= 0 and i < 6800:
            rnd_str.append(line)

    r = rnd_str

    dict1 = {}
    for row in r:
        a, b, v = row.split()
        dict1.setdefault((a,b),[]).append(v)

with open ("filename2.txt") as f:
    dict2 = {}
    r = csv.reader(f,delimiter="\t")

    dict2 = {}
    for row in r:
        a, b, v = row.split()
        dict2.setdefault((a,b),[]).append(v)

    count = 0
    for key1 in dict1:
        for key2 in dict2:
            if (key1[0] == key2[0]) and ((float(key1[1]) - (float(key2[1]))) < 0):
                count += 1

print(count)

rawDescription: Combining two python scripts to run as one program


code:
e = elements()
lib.func(ctypes.byref(e))

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code:
# Some if this is from http://nullege.com/codes/show/src@e@i@einstein-HEAD@Python25Einstein@Lib@subprocess.py/380/win32api.GetStdHandle
# and
# http://nullege.com/codes/show/src@v@i@VistA-HEAD@Python@Pexpect@winpexpect.py/901/win32console.GetStdHandle.PeekConsoleInput

from ctypes import *
import time
import threading

from win32api import STD_INPUT_HANDLE, STD_OUTPUT_HANDLE

from win32console import GetStdHandle, KEY_EVENT, ENABLE_WINDOW_INPUT, ENABLE_MOUSE_INPUT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT

import keyPress

class CaptureLines():
    def __init__(self):
        self.stopLock = threading.Lock()

        self.isCapturingInputLines = False

        self.inputLinesHookCallback = CFUNCTYPE(c_int)(self.inputLinesHook)
        self.pyosInputHookPointer = c_void_p.in_dll(pythonapi, "PyOS_InputHook")
        self.originalPyOsInputHookPointerValue = self.pyosInputHookPointer.value

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

    def inputLinesHook(self):

        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
        inputChars = self.readHandle.ReadConsole(10000000)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT)

        if inputChars == "\r\n":
            keyPress.KeyPress("\n")
            return 0

        inputChars = inputChars[:-2]

        inputChars += "\n"

        for c in inputChars:
            keyPress.KeyPress(c)

        self.inputCallback(inputChars)

        return 0

    def startCapture(self, inputCallback):
        self.stopLock.acquire()

        try:
            if self.isCapturingInputLines:
                raise Exception("Already capturing keystrokes")

            self.isCapturingInputLines = True
            self.inputCallback = inputCallback

            self.pyosInputHookPointer.value = cast(self.inputLinesHookCallback, c_void_p).value
        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

    def stopCapture(self):
        self.stopLock.acquire()

        try:
            if not self.isCapturingInputLines:
                raise Exception("Keystrokes already aren't being captured")

            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.isCapturingInputLines = False
            self.pyosInputHookPointer.value = self.originalPyOsInputHookPointerValue

        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

rawDescription: Key echo in Python in separate thread doesn't display first key stroke


code:
from gevent.monkey import patch_all
patch_all()
from gevent.pywsgi import WSGIServer

def stream_to_internal_storage(data):
    pass

def simple_app(environ, start_response):
    bytes_to_read = 1024

    while True:
        readbuffer = environ["wsgi.input"].read(bytes_to_read)
        if not len(readbuffer) > 0:
            break
        stream_to_internal_storage(readbuffer)

    start_response("200 OK", [("Content-type", "text/html")])
    return ["hello world"]

def run():
    config = {'host': '127.0.0.1', 'port': 45000}

    server = WSGIServer((config['host'], config['port']), application=simple_app)
    server.serve_forever()

if __name__ == '__main__':
    run()

rawDescription: Python server for streaming request body content


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

from kivy.lang import Builder

kv = '''
<MyButton>:
    size_hint: None, 1
    size: self.texture_size
'''
Builder.load_string(kv)

class MyButton(Button):
    pass

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.add_widget(MyButton(text="Fixed size button"))
        self.add_widget(Button(text="Normal button"))
        self.add_widget(MyButton(text="Fixed size button"))

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: How do I set minimum allowable width/height for widget/layout in Kivy?

description: Set minimum allowable width/height for widget/layout in Kivy