code:
# remove empty lines
lines = [l for l in lines if len(l.strip()) > 0]
header = lines[0]
line = lines[1].split(' ')
column1 = line[0]
column2 = line[1]
...

rawDescription: File and space in Python

description: File and space in Python


code:
super_x = []
for i, df_chunk in enumerate(df_list):
    [x, y] = preprocess_data(df_chunk)
    super_x.append(x)
super_x = pd.concat(super_x, axis=0)

rawDescription: Why does concatenation of DataFrames get exponentially slower?


rawDescription: django model for list of objects' relations to each other?

description: Django model for list of objects' relations to each other


rawDescription: inserting a new entry into adjacency list

description: Inserting a new entry into adjacency list


code:
import os
def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

rawDescription: Copying the contents of a variable to the clipboard


code: print_both(open_file_variable, 'pass arguments as if it is', 'print!', 1, '!')

rawDescription: Python output on both console and file

description: Python output on both console and file


code: [d.pop(k, None) for k in l]

rawDescription: deleting items from a dictionary with a given list

description: Deleting items from a dictionary with a given list


code: response = raw_input('Enter your number --> ')

rawDescription: I'm not sure of a way to go about this task using Python code


rawDescription: Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists


code: C = np.einsum('ij,ij->i',A,B)

rawDescription: how to calculate the dot product of two arrays of vectors in python?

description: Calculate the dot product of two arrays of vectors in python


code: (s + mystring for s in mylist)

rawDescription: Appending the same string to a list of strings in Python


code:
class Participant(models.Model):
    user = models.ForeignKey('auth.User')
    creation_date = models.DateTimeField()
    phone_no = models.CharField(max_length=20)

    def __unicode__(self):
        return self.user.email

class Winner(Participant):
    win_date = models.DateTimeField()

rawDescription: python django continous checking for validation of user and date

description: Python django continous checking for validation of user and date


code:
width_idx = {w: i for i, w in enumerate(widths)}
height_idx = {h: i for i, h in enumerate(heights)}

rawDescription: Python 2D table lookup by labels

description: Python 2D table lookup by labels


code:
c = MyClass()
instances(MyClass)
del c
_

rawDescription: Python: different behavior using gc module in interactive mode


rawDescription: How to load all cPickle dumps from a log file?

description: Load all cPickle dumps from a log file


code: df = pd.DataFrame.from_csv(io.StringIO(t), index_col=None)

rawDescription: Pandas creates DataFrame with first header column in it's own row


code: data = [[item.strip() for item in line.rstrip('\r\n').split('\t')] for line in open('input.txt')]

rawDescription: Python - file contents to nested list

description: Python - file contents to nested list


rawDescription: Pyparsing CSV string with random quotes

description: Pyparsing CSV string with random quotes


code:
import csv

#Read both files
with open('process.csv', 'rb') as a:
    reader = csv.reader(a,delimiter = ",")
    process_csv = list(reader)

with open('files.csv', 'rb') as b:
    reader = csv.reader(b,delimiter = ",")
    data_csv = list(reader)

#Write into combine.csv
if len(process_csv) == len(data_csv):
    with open('combine.csv', 'ab') as f:
        writer = csv.writer(f,delimiter = ",")
        for i in range(0,len(process_csv)):
            temp_list = []
            temp_list.extend(process_csv[i])
            temp_list.append(data_csv[i][1])
            writer.writerow(temp_list)

rawDescription: Python: Append column to CSV from a different csv file


code:
split_data = (data[i:i+step] for i in range(0,len(data),step))
#note i use an iterator comprehension this time since i dont want to loop over the stuff twice

for grouping in split_data:
    analyze(grouping)

rawDescription: Python csv group rows by n row numbers

description: Python csv group rows by n row numbers


rawDescription: Convert float to comma-separated string

description: Convert float to comma-separated string


code:
def parse(self, response):
    sel = Selector(response)
    sites = sel.xpath('//*[@id="content"]/div[2]/div/div/div[1]')
    passed_date=response.meta.get('date')
    items=[]
    for site in sites:
        item = DmozItem()
        # No need to replace u'. It is an internal representation for unicode
        # strings. It won't affect your data
        links = site.xpath('.//a/@href').extract()
        self.all_articles.append(item)
        # For all the links, yield a Request and send the
        # item object
        for link in links:
            yield Request(url=link, callback=self.get_text_of_the_article, meta={'item': item})

def get_text_of_the_article(self,response):
    sel=Selector(response)
    # Get the item object sent from parse method
    item = response.request.meta['item']
    # You can save the link url here
    item['link'] = response.url
    item['text'] = sel.xpath('//*[@id="articleText"]/p[1]').extract()
    return item

rawDescription: Extract data from the second level link, scrapy


code: A[(slice(None),) + coords]

rawDescription: Index a numpy array using a tuple (or list) when len < ndim?


code:
has_rock_genres = Q(genre__genre='Rock') | Q(genre__parent__genre='Rock')
has_pop_genres = Q(genre__genre='Pop') | Q(genre__parent__genre='Pop')

Track.objects.filter(has_rock_genres & has_pop_genres).distinct()

rawDescription: Django Many-to-many query fulfilling a specific condition


code:
new = df[['ID','address','prev_address']].groupby(['address','prev_address', df.used_at.dt.year]).count().reset_index()

new['visit'] = new['prev_address'] + ' -> ' + new['address']

rawDescription: How to determine the priority actions for a every unique user using pandas

description: Determine the priority actions for a every unique user using pandas


code:
[
    [
        os.path.join(path, 'list%d'%l1_index, l2_value)
        for l2_value in l2[l1_index]
    ]
    for l1_index in l1
]

rawDescription: Creating nested lists with a list comprehension


code:
allletters = set(list('abcdefghijklmnopqrstuvwxyz'))
usedletters = set() # update this as you go
while( len(usedletters) != len(allletters) ):
    guessedletter = raw_input("pick a letter")
    availletters = allletters.difference(usedletters)
    usedletters.update(guessedletter)

rawDescription: letter/word guessing game in python

description: Letter/word guessing game in python


rawDescription: In Appcelerator Titanium, how can I get Django's CSRF token?


code:
def summers(num_iters):
    pool = multiprocessing.Pool(processes=8)

    outputArr = np.zeros((num_iters,1,512*512)) #you wouldn't have to initialize these
    sumArr = np.zeros((1,512*512))              #but I do to make sure I have the memory

    outputArr = np.array(pool.map(computation, range(num_iters)))
    sumArr = outputArr.sum(0)

    pool.close() #not sure if this is still needed since map waits for all iterations

    return sumArr

rawDescription: How to parallelize a sum calculation in python numpy?

description: Parallelize a sum calculation in python numpy


code:
import cgi, urllib, urlparse

class Url(object):
    def __init__(self, url):
        """Construct from a string."""
        self.scheme, self.netloc, self.path, self.params, self.query, self.fragment = urlparse.urlparse(url)
        self.args = dict(cgi.parse_qsl(self.query))

    def __str__(self):
        """Turn back into a URL."""
        self.query = urllib.urlencode(self.args)
        return urlparse.urlunparse((self.scheme, self.netloc, self.path, self.params, self.query, self.fragment))

rawDescription: Is there a better way to write this URL Manipulation in Python?


code:
img = Image.open('./edgewalker-cat.png')
pix = img.load()
pix
pix[0,0]

rawDescription: Converting list to numpy array issues

description: Converting list to numpy array issues


code:
items = [sorted(subitems)[-1]
         for _, subitems
         in itertools.groupby(keys, keyfunc)]

rawDescription: Selecting items matching a specific condition from a list


code: c.execute("SELECT * FROM tbl_subscriber LIMIT %i,%i;", (actualLimit,steps))

rawDescription: Best way to iterate through all rows in a DB-table

description: Iterate through all rows in a DB-table


code:
from pylab import hist, show, xticks

x = [1.1]*29 + [2]*7 + [3.2]*3 + [5]
hist(x)
xticks(range(1, 6))
show()

rawDescription: How to change ticks on a histogram? (matplotlib)

description: Change ticks on a histogram? (matplotlib)


code:
from django import template

from django_tables2.templatetags.django_tables2 import querystring

register = template.Library()

@register.inclusion_tag('django_tables2/header.html', takes_context=True)
def render_header(context):
    for column in context['table'].columns:
        column.sort_existing = False
        if 'sort' in context['request'].GET:
            if column.name in context['request'].GET['sort']:
                column.sort_existing = True

    return context

rawDescription: django-table2 multi-column sorting UI

description: Django-table2 multi-column sorting UI


code:
class LoadFromFile (argparse.Action):
    def __call__ (self, parser, namespace, values, option_string = None):
        with values as f:
            parser.parse_args(f.read().split(), namespace)

rawDescription: how to get argparse to read arguments from a file with an option rather than prefix

description: Get argparse to read arguments from a file with an option rather than prefix


code:
# main.py
import pygame
from pygame.locals import *

import content

def init():
    pygame.display.init()

def stuff():
    content.morestuff()

if __name__ == '__main__':
    init()
    stuff()

rawDescription: Way around Python imports within imports?


code: from __future__ import division

rawDescription: Accessing a large number of unsorted array elements in Python


code:
class SpreadSheet(object):
    '''awesome docstring'''
    def __init__(self, fileobj):
        self.table = []
        self.headers = []

        filereader = reader(fileobj, delimiter=',')
        for row in filereader:
            self.table.append(row)
    ...

rawDescription: Writing a csv temporary file using tempfile


rawDescription: Python UDP server on ubuntu not working

description: Python UDP server on ubuntu not working


code: [o.my_attr for o in my_list]

rawDescription: How to extract from a list of objects a list of specific attribute?

description: Extract from a list of objects a list of specific attribute


code:
def f1(c):
    sleep(20)
    return (c % 2) == 0

def f2(c):
    sleep(25)
    return (c % 4) == 0

rawDescription: how should I order my statement in a short circuit and?

description: How should I order my statement in a short circuit and


code:
good
awesome

rawDescription: How to find total number of positive and negative words from a text?

description: Find total number of positive and negative words from a text


code: 40001#World Music#Mike Oldfield#Tubular Bells#   53###

rawDescription: Trim or remove single white space char from delimited text


rawDescription: How to determine specific color and size of chosen nodes in Networkx graph plot

description: Determine specific color and size of chosen nodes in Networkx graph plot


code:
def find_best_two_months(orders):
  first  = lambda x: x[0]
  second = lambda x: x[1]

  orders_by_year_and_month = [
    ("%04d-%02d" % (date.year, date.month), amount)
    for date, amount in orders]

  sorted_orders = sorted(orders_by_year_and_month, key=first)

  totals_by_month = [
    (ym, sum(map(second, groupped_orders)))
    for ym, groupped_orders in groupby(sorted_orders, key=first)]

  totals_two_months = [
    ( "%s - %s" % (m1[0], m2[0]), m1[1]+m2[1] )
    for m1, m2 in zip(totals_by_month, totals_by_month[1:]) ]

  return max(totals_two_months, key=second)

rawDescription: How to create a list of totals for durations?

description: Create a list of totals for durations


rawDescription: Is there a way to generate a list of indices using numpy


code: filecount = len([name for name in os.listdir('.') if os.path.isfile(name)])

rawDescription: Counting files and incrementing variable Python


code:
try:
    [x for x in raw_input("Enter numbers: ").split(' ') if x]
except NameError:
    [x for x in input("Enter numbers: ").split(' ') if x]

rawDescription: Input List - Double/Triple Digits

description: Input List - Double/Triple Digits


code:
if char < m:
    return isitIn(char, aStr[:len(aStr) // 2])
elif char > m:
    return isitIn(char, aStr[len(aStr) // 2:])

rawDescription: Using a recursive bisection algorithm to check if character is in string


code:
def bgr(a):
    """ for when B' < G' < R'
    """
    t = transform(a)
    red, green, blue = a.transpose([2,0,1])
    # same as: red, green, blue = a[..., 0], a[..., 1], a[..., 2]
    r_max, g_max, b_max = t.transpose([2,0,1])
    assert np.all((b_max <= g_max) & (g_max <= r_max)), "doesn't match rank"
    condition = r_max >= g_max + b_max
    new_red = np.where(condition, red + g_max + b_max, red + r_max)
    new_green = np.where(condition, green - g_max, green - r_max + b_max)
    new_blue = blue - b_max
    return np.dstack([new_red, new_green, new_blue])

rawDescription: Iterating a function over the RGB values of individual pixels


code:
import pandas as pd
ts = pd.Series(times, index=dates)
ts.plot(rot=30, style='x-')

rawDescription: matplotlib time vs date

description: Matplotlib time vs date


code:
def showxy(event):
    xm, ym = event.x, event.y
    x3 = xm*ym
    return x3

rawDescription: How to return an int value from a function python

description: Return an int value from a function python


code:
import re
s = '::: message'
match = p.search(s)
match.span()
s[slice(*match.span())]

rawDescription: Why do Python regex spans extend one place past the actual match?


rawDescription: How to evaluate two items of the same list and return their sum if equal?

description: Evaluate two items of the same list and return their sum if equal


rawDescription: What is the most Pythonic way to test for match with first item of tuple in sequence of 2-tuples?


code: array([ True, False, False,  True,  True, False], dtype=bool)

rawDescription: NumPy: Comparing Elements in Two Arrays

description: NumPy: Comparing Elements in Two Arrays


code: twentyandovermen_breast = strokesort('twentyandover', 'men')

rawDescription: create variable names based on function arguments? Python

description: Create variable names based on function arguments? Python


code:
with open("Output.txt", "w") as text_file:
    text_file.write("Write blablabla into a file")

rawDescription: redirecting python output to a log file

description: Redirecting python output to a log file


code: import tkinter.messagebox

rawDescription: Why do we sometimes need to import module1.module2 but sometimes not?


rawDescription: Convert Select Columns in Pandas Dataframe to Numpy Array


code: CITY_TYPES = (str, float, float, int)

rawDescription: Regular Expressions in data parsing Python


code: user = {u'user': {u'lang': u'en', u'utc_offset': -18000, u'statuses_count': 58304, u'default_profile_image': False, u'friends_count': 373, u'profile_background_image_url_https': u'https://pbs.twimg.com/profile_background_images/457457546580602880/VxHBaVbH.jpeg', u'profile_use_background_image': False, u'profile_sidebar_fill_color': u'EFEFEF', u'profile_link_color': u'009999', u'profile_image_url': u'http://pbs.twimg.com/profile_images/531605236696104960/cG-Lu2y6_normal.jpeg', u'time_zone': u'Quito', u'is_translator': False, u'screen_name': u'lovebscott', u'url': u'http://t.co/3nt6d6jM9p', u'verified': True, u'geo_enabled': True, u'profile_background_color': u'131516', u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/14521926/1403029806', u'id': 14521926, u'profile_background_image_url': u'http://pbs.twimg.com/profile_background_images/457457546580602880/VxHBaVbH.jpeg', u'description': u'#KingofFabulous - #TheMultimediaMaven - Mogul - TV / Internet Personality - @EBONYMag Advice Columnist - @glam_com Contributing Editor', u'is_translation_enabled': False, u'profile_background_tile': True, u'favourites_count': 14, u'name': u'B. Scott', u'notifications': None, u'follow_request_sent': None, u'profile_text_color': u'333333', u'created_at': u'Fri Apr 25 03:29:42 +0000 2008', u'profile_location': None, u'contributors_enabled': False, u'location': u'Los Angeles, CA', u'entities': {u'url': {u'urls': [{u'indices': [0, 22], u'url': u'http://t.co/3nt6d6jM9p', u'expanded_url': u'http://lovebscott.com', u'display_url': u'lovebscott.com'}]}, u'description': {u'urls': []}}, u'followers_count': 161968, u'profile_sidebar_border_color': u'FFFFFF', u'id_str': u'14521926', u'default_profile': False, u'following': None, u'protected': False, u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/531605236696104960/cG-Lu2y6_normal.jpeg', u'listed_count': 1905}}

rawDescription: Python: Twitter API tweets/search: Flatten nested dictionary to columns


rawDescription: How to extract a number from a string in Python?

description: Extract a number from a string in Python


rawDescription: Writing from one file to another python

description: Writing from one file to another python


code:
zyme
abbrühen

rawDescription: Discover identically adjacent strings with regex and python


code: d2 = dict((k,v) for k,v in d.iteritems() if k in s)

rawDescription: Remove entries of a dictionary that are not in a set


code:
class X: pass

a = X()
b = X()
a == b

rawDescription: Comparing two identical objects in Python (2.7) returns False


code:
import numpy as np
logx = np.log(x)
logy = np.log(y)
coeffs = np.polyfit(logx,logy,deg=3)
poly = np.poly1d(coeffs)

rawDescription: Fit a curve using matplotlib on loglog scale


code:
def fancy_dict(*args):
    'Pass in a list of tuples, which will be key/value pairs'
    ret = {}
    for k,v in args:
        for i in k:
            ret[i] = v
    return ret

rawDescription: Is there a way to have a dictionary key be a range?


code:
class TabBar(QtGui.QTabBar):
    def __init__(self, parent=None):
        super(TabBar, self).__init__(parent)

        self.setStyleSheet('font-size: 18pt; font-family: Courier;')

rawDescription: PyQt4: Change text size and font on QTabBar


code:
class Person(models.Model):
    name = models.CharField()
    male = CustomBooleanField() # use the custom field

rawDescription: Django model.BooleanField as 0/1

description: Django model.BooleanField as 0/1


code:
import random

namelist = []
namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

rawDescription: Python: can't assign to literal

description: Python: can't assign to literal


code:
x = sm.add_constant(ts12.index)
x
ts12_ols_fit = sm.OLS(ts12.values, ts12.index).fit()
ts12_ols_fit.params
ts12_ols_fit = sm.OLS(ts12.values, x).fit()
ts12_ols_fit.params
ts12_ols_fit.fittedvalues

rawDescription: Fitting downward trends (negative slope) with statsmodels linear regression


rawDescription: Trying to set function as parameter

description: Trying to set function as parameter


code:
# Create the sample file:
with open("sample.data", "wb") as f:
    f.write(sample)

rawDescription: Taking a hex file and extracting data

description: Taking a hex file and extracting data


code:
def f(x, periods=periods):
    for k, v in periods.items():
        if x.hour >= v[0].hour and x.hour < v[1].hour:
            return k
    return 'unknown_period'

rawDescription: Bin timestamp into custom periods

description: Bin timestamp into custom periods


code:
empty_paginator = models.Object.query.filter_by(id=None).paginate()
empty_paginator.items
empty_paginator.has_next

rawDescription: empty paginate object sqlalchemy

description: Empty paginate object sqlalchemy


code:
import datetime as dt
import dateutil.parser as dparser

date_str='on Jun 03, 02010 at 10:22PM'
date=dparser.parse(date_str)
print(date)
# 2010-06-03 22:22:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Thu, 03 Jun 2010 22:22:00

rawDescription: Convert 12hr date/time string to 24hr datetime


code:
d = genDDict(2)
d[2][1]

rawDescription: nesting defaultdicts in an arbitrary depth

description: Nesting defaultdicts in an arbitrary depth


code: image = (image * 255).round().astype(np.uint8)

rawDescription: python make RGB image from 3 float32 numpy arrays

description: Python make RGB image from 3 float32 numpy arrays


code:
def kernel_loops(img, kernel_min, kernel_max):
    img_h, img_w = img.shape
    win_h, win_w = kernel_min.shape
    heatmap = np.zeros(img.shape, dtype='uint16')
    target = heatmap[win_h//2:-win_h//2+1, win_w//2:-win_w//2+1]

    for i in range(win_h):
        for j in range(win_w):
            # Negative index fails when slicing to the end
            source = img[i:i+img_h-win_h+1, j:j+img_w-win_w+1]
            target += (kernel_min[i,j] <= source) & (source <= kernel_max[i,j])

    return heatmap

rawDescription: Numpy custom moving window count cells in range


code:
import ntpath
ntpath.splitdrive('C:\windows\somefile.exe')
ntpath.normcase('C:\program Files/somefile.exe')

rawDescription: Copy files based on path from file

description: Copy files based on path from file


code:
for w in words:
    if not w.isalpha():
          continue

rawDescription: How do I find only whole words using re.search?

description: Find only whole words using re.search


code:
if (
       cond1 == 'val1' and cond2 == 'val2' and
       cond3 == 'val3' and cond4 == 'val4'
   ):
    do_something
if    (cond1 == 'val1' and cond2 == 'val2' and
       cond3 == 'val3' and cond4 == 'val4'):
    do_something

rawDescription: Python style: multiple-line conditions in IFs


code:
def getPdb(self,event):
    dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
    mypath = ''
    if dlg.ShowModal() == wx.ID_OK:
        path = dlg.GetPath()
        mypath=os.path.basename(path)
    dlg.Destroy()

    if mypath:
        self.hey.Clear()
        self.hey.AppendText(mypath)
    return

rawDescription: loading a file, posting that to a textbox

description: Loading a file, posting that to a textbox


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

x = [1,2,3,4]
y = [3,5,7,10] # 10, not 9, so the fit isn't perfect

fit = np.polyfit(x,y,1)
fit_fn = np.poly1d(fit)
# fit_fn is now a function which takes in x and returns an estimate for y

plt.plot(x,y, 'yo', x, fit_fn(x), '--k')
plt.xlim(0, 5)
plt.ylim(0, 12)

rawDescription: Linear regression with matplotlib / numpy


code:
def func(**params):
    self.callMethod(aname, rargs, oargs, **params)

rawDescription: What does this lambda function do? (lambda with a function call inside)


code:
d = {}
d["a"] = "This string is presumably too long to be auto-interned."
d["b"] = "This string is presumably too long to be auto-interned."
d["a"] is d["b"]
di = InternDict()
di["a"] = "This string is presumably too long to be auto-interned."
di["b"] = "This string is presumably too long to be auto-interned."
di["a"] is di["b"]

rawDescription: size efficient dictionary(associative array) implementation

description: Size efficient dictionary(associative array) implementation


rawDescription: python mean of list of lists

description: Python mean of list of lists


code: r=[''.join([str(elt) for elt in p]) for p in itertools.product(*(set(elt) for elt in (v,w,x,y,z)))]

rawDescription: Is there an algorithm to find unique combinations of 2 lists? 5 lists?


code:
first_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei']}
second_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei'], 'three': ['trois', 'drie', 'drei']}
first_mutable.items() <= second_mutable.items()
first_mutable['one'].append('ichi')
first_mutable.items() <= second_mutable.items()

rawDescription: Test if dict contained in dict

description: Test if dict contained in dict


code:
import struct, datetime

def parse_thread_index(index):

    s = index.decode('base64')

    guid = struct.unpack('>IHHQ', s[6:22])
    guid = '{%08X-%04X-%04X-%04X-%12X}' % (guid[0], guid[1], guid[2], (guid[3] >> 48) & 0xFFFF, guid[3] & 0xFFFFFFFFFFFF)

    f = struct.unpack('>Q', s[:6] + '\0\0')[0]
    ts = [datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=f//10)]

    for n in range(22, len(s), 5):
        f = struct.unpack('>I', s[n:n+4])[0]
        ts.append(ts[-1] + datetime.timedelta(microseconds=(f<<18)//10))

    return guid, ts

rawDescription: Parsing Thread-Index Mail Header with Python


code:
self.t0 = Label(frame, fg="blue", textvariable=self.temp0,font=(20))
self.t0.grid(row=2, column=0)

rawDescription: How to alter attributes in Tkinter

description: Alter attributes in Tkinter


code: df.pivot_table(values='value', index=['year', 'month'], columns='item')

rawDescription: pandas: how to run a pivot with a multi-index?

description: Pandas: how to run a pivot with a multi-index


rawDescription: How to tweak the NLTK sentence tokenizer

description: Tweak the NLTK sentence tokenizer


code: count = sum(1 for m in findall(target, key))

rawDescription: Assigning value in a while comparison expression


code: print ( drugs[drugs_needed[1]][0] )

rawDescription: python: getting element in a list

description: Python: getting element in a list


code:
source
import logging, sys, threading, time

STOP_VALUE = 'stop'

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)-4s %(threadName)s %(levelname)s %(message)s",
    datefmt="%H:%M:%S",
    stream=sys.stderr,
)

class Database(list):
    PATH = '/tmp/db.dat'
    def __init__(self):
        super(Database,self).__init__()
        self._update_lock = threading.Lock()

    def update(self):
        with self._update_lock:
            self[:] = [ line.strip() for line in open(self.PATH) ]

db = Database()

def spawn(events, key):
    events[key] = threading.Event()
    th = threading.Thread(
        target=search_worker,
        kwargs=dict(stop_ev=events[key]),
        name='thread-{}'.format(key),
    )
    th.daemon = True
    th.start()

def search_worker(stop_ev):
    """
    scan database until "stop" found, or our event is set
    """
    logging.info('start')
    while True:
        logging.debug('scan')
        db.update()
        if STOP_VALUE in db:
            logging.info('stopvalue: done')
            return
        if stop_ev.wait(timeout=10):
            logging.info('event: done')
            return

def manager():
    """
    scan database
    - word: spawn thread if none already
    - word_stop: tell thread to die by setting its stop event
    """
    logging.info('start')
    events = dict()
    while True:
        db.update()
        for key in db:
            if key == STOP_VALUE:
                continue
            if key in events:
                continue
            if key.endswith('_stop'):
                key = key.split('_')[0]
                if key not in events:
                    logging.error('stop: missing key=%s!', key)
                else:
                    # signal thread to stop
                    logging.info('stop: key=%s', key)
                    events[key].set()
                    del events[key]
            else:
                spawn(events, key)
                logging.info('spawn: key=%s', key)
        time.sleep(2)

if __name__=='__main__':

    with open(Database.PATH, 'w') as dbf:
        dbf.write(
        'whiskey\nsyrup\n'
        )

    db.update()
    logging.info('start: db=%s -- %s', db.PATH, db)

    manager_t = threading.Thread(
        target=manager,
        name='manager',
    )
    manager_t.start()
    manager_t.join()

rawDescription: Waking up a specific thread from sleep from another thread in python


code:
db.execute("SELECT ... WHERE lexicon.word IN (?,?,?)",
           ['Hello', 'world', 'meow'])

rawDescription: Using a Variable Number of WHERE Clauses to Match an Arbitrary Number of Keywords pysqlite


code:
def to_string(self):
    return """<{tag}{attributes}>{content}</{tag}>""".format(
        tag=self.tag,
        attributes=' '.join('%s="%s"' % (attr, val) for
                            attr, val in self.attributes),
        content=''.join(
            (n if isinstance(n, basestring) else n.to_string()) for
            n in self.contents))

rawDescription: Python: HTML generation performance improvement


code:
import myfile
app = myfile.MyApp()
app.step()
app.something = something_else
app.step()

rawDescription: IPython iterate main loop manually?

description: IPython iterate main loop manually


code: sorted_objects = sorted(objdict, key=lambda k: k['thing1'], reverse=True)

rawDescription: Sorting a list with dictionaries, django


code:
from mock import Mock
mock = Mock()

rawDescription: Automocking for Python?

description: Automocking for Python


code:
# focus element in the query string
# http://example.com/route?id=123
@app.route('/route')
def route():
    id = request.args.get('id')
    # id will be the given id or None if not available
    return render_template('my-form.html', id = id)

rawDescription: render html page /#:id using flask

description: Render html page /#:id using flask


code:
Base = declarative_base()

class Something(Base):
    pass

def initialize(engine):
    Something.__table__ = Table('something', Base.metadata, autoload_with=engine)

rawDescription: How to dynamically create classes inside a module-level initialize() method in Python

description: Dynamically create classes inside a module-level initialize() method in Python


code:
a = b
b = a + b

rawDescription: Fibonacci sequence python

description: Fibonacci sequence python


code:
def func(df,file):
    df.loc[:,'filename'] = file

[func(df_,file) for df_,file in zip(list_df,file_names)]

rawDescription: Python - List comprehension expression for assigning values from list to list of DataFrames


code:
import lxml.html as LH

text = '''\

        TEXT A
        TEXT B
        TEXT C

'''

root = LH.fromstring(text)
e = root.xpath('.//a[text()="TEXT A"]')
print(e)

rawDescription: How to use lxml to find an element by text?

description: Use lxml to find an element by text


code:
from itertools import zip_longest
textchars = bytearray([0,7,8,9,10,12,13,27]) + bytearray(range(0x20, 0x100))
textdict = dict(zip_longest(textchars,[''],fillvalue=''))
is_binary_string = lambda data: bool(data.translate(textdict))

rawDescription: migrate str.translate from Python 2 to Python 3

description: Migrate str.translate from Python 2 to Python 3


rawDescription: splitting and concatenating a string

description: Splitting and concatenating a string


code:
def wrapping_function(k):
    return add_x_to_input(some_value_for_x, k)

map(wrapping_function, myList)

rawDescription: Map function and input function parameters


code: df['month'] = pd.to_datetime(df['month'], format='%m/%y')

rawDescription: PANDAS coarse dates (month/year)

description: PANDAS coarse dates (month/year)


code:
def atoi(s):
    rtr=0
    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return rtr

rawDescription: Convert String to Int without int()

description: Convert String to Int without int()


rawDescription: Iterating and selecting a specific array from a multidimensional array in Python


code:
import pymongo
import bson.binary

from pymonngo import MongoClient
from bson.binary import Binary

client = MongoClient()
db = client.test

db.btest.insert({ "bindata": Binary("Hello",0) })

db.btest.find_one()

rawDescription: Converting an html page to binary format in python


rawDescription: Create all possible subsequence with unique elements


code:
def main():
    print('Select from  the list below which operation you want the calculator to do.')
    print("A.Add")
    print("S.Subtract")
    print("M.Multiply")
    print("D.Divide")
    while True:
        choice = raw_input("Enter choice(a/s/m/d)")
        if choice not in {"a", "s", "m", "d","q"}:
            print (" the letter you entered is not in our lists!")
            continue
        num1 = int(input("Enter an integer as your first number: "))
        num2 = int(input("Enter an integer as second number: "))
        if choice == 'a':
            print("{} + {} = {}".format(num1, num2, add(num1, num2)))
        elif choice == 's':
            print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
        inp = input("Enter 1 to play again or 2 to exit")
        if inp == "1":
            main()
        else:
            print("thanks for playing")
            break

rawDescription: how to add restart command in python?

description: Add restart command in python


code:
orig = [10, 20, 30]
arr = orig              # Second reference to the same list.
arr = []                # Points arr to a new list, leaving orig unchanged
orig

rawDescription: Difference between arr[:]=[] and arr[]=[] in python3.x?


code: histogram = collections.Counter(d['age'] for d in user_records.itervalues())

rawDescription: python: creating histogram out of dictionary

description: Python: creating histogram out of dictionary


code: text = ''.join(word_list)

rawDescription: Read each word and rest of line in Python?


code: d.strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Date formate conversion in Python

description: Date formate conversion in Python


code: output = dict((el1[0], el2) for el1, el2 in zip(list1, list2))

rawDescription: merging list of tuples and list and create dictionary

description: Merging list of tuples and list and create dictionary


code:
counts, centers = np.histogram(cols, bins=40)
page_divider = centers[np.argmax(counts)]

rawDescription: Searching for a line in a jpg file Python


code: print(count)  # Python3

rawDescription: Error in displaying unicode and frequency


code:
#define _ACTIVE_TAG 1
#define _ISLAND_SLEEPING 2
#define _WANTS_DEACTIVATION 3
#define _DISABLE_DEACTIVATION 4
#define _DISABLE_SIMULATION 5

rawDescription: How can a #defined C value be exposed to Python in a Cython module?


code: 'blah blah ' ' blah blah ' ' blah blah '

rawDescription: Creating Variables Based Off A String

description: Creating Variables Based Off A String


code: gender_ambiguous_data_2014 = df[(df.name.isin(gender_ambiguous_names)) & (df.year == 2014)]

rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code:
import os, sys
PATH = r'\your\path\to\matplotlib'
sys.path.append(PATH)
import setupext # setupext.py contains the dependency definitions

os.chdir(PATH)

rawDescription: How to know the enabled features of a matplotlib installation?

description: Know the enabled features of a matplotlib installation


code:
def handleRequest():
    results = Buffer.onUserRequest()
    # Format a response, using the results
    if not results:
        return 'No data available'  # or any other useful error message
    return response(results[0][0], results[0][1])

rawDescription: Python thread-safe access without blocking or uncontrolled queue growth?


code:
iFile = open("/tmp/foo.txt", "w")
"Successfully created the file: {0}.txt".format(iFile)
"Successfully created the file: {0}.txt".format(iFile.name)

rawDescription: Python - How to modify text output using %s?


code:
import numpy as np

def forloop(x):
    data_200_300 = []
    data_300_400 = []
    for i in x:
        if 200 < i < 300:
            data_200_300.append(i)
        elif 300 < i < 400:
            data_300_400.append(i)
    return [data_200_300, data_300_400]

def lambdaversion(data, bin_start, bin_end, bin_step):
    filtered_data = []
    for i in range(bin_start,bin_end,bin_step):
        filtered_data.append( filter(lambda x: i < x < i+bin_step, data) )
    return filtered_data

def indexingversion(data, bin_start, bin_end, bin_step):
    x = np.array(data)
    bin_edges = np.arange(bin_start, bin_end + bin_step, bin_step)
    bin_number = bin_edges.size - 1
    cond = np.zeros((x.size, bin_number), dtype=bool)
    for i in range(bin_number):
        cond[:, i] = np.logical_and(bin_edges[i] < x,
                                    x < bin_edges[i+1])
    return [list(x[cond[:, i]]) for i in range(bin_number)]

#@profile
def run_all():
    n = 100000
    x = np.random.random_integers(200, 400, n) + np.random.ranf(n)
    bin_start = 200
    bin_end = 400
    bin_step = 100
    a = forloop(x)
    b = lambdaversion(x, bin_start, bin_end, bin_step)
    c = indexingversion(x, bin_start, bin_end, bin_step)
    print('All the same? - ' + str(a == b == c))

if __name__ == '__main__':
    run_all()

rawDescription: How can i group data based on range of values

description: Group data based on range of values


code:
from facebook import GraphAPI

APP_ID = '<your_app_id>'
APP_SECRET = '<your_app_secret>'

graph = GraphAPI(version=2.5)
graph.access_token = graph.get_app_access_token(APP_ID, APP_SECRET)

# sequence of page ids you want to retrieve emails for
pages = ('page1_id', 'page2_id', 'page3_id')

objects = graph.get_objects(pages, fields='name,emails')

for page in objects.values():
    print('{}: {}'.format(page['name'], ', '.join(page['emails'])))

rawDescription: Using Selenium to scrape email addresses by checking for characters


code:
cur.execute("""SELECT *
               FROM people_counter
               WHERE time_stamp BETWEEN
                   date '2015-06-01' and
                   date '2015-06-30';""")

rawDescription: Psycopg2, selection based on date/time

description: Psycopg2, selection based on date/time


code:
import itertools

class House(object):

    def __init__(self, row, col):
        self._row = row
        self._col = col

GRIDHEIGHT = 10
GRIDWIDTH = 10

houses = {(col, row): House(row, col) for col, row in
          itertools.product(range(GRIDWIDTH), range(GRIDHEIGHT))}

rawDescription: Iterating through instances of a class by instance attribute


code:
import pandas
pandas.set_option('expand_frame_repr', False)

rawDescription: equivalent of R's View for Python's pandas

description: Equivalent of R's View for Python's pandas


code:
result = alist[0].copy()
for key in repeated:
    result[key] = [d[key] for d in alist]

rawDescription: concatenate dictionaries over a key

description: Concatenate dictionaries over a key


code:
def decorated_func():
    pass
decorated_func = decorator_expr(decorated_func)

rawDescription: Decorated function along with original, without having to re-write the function


code: logger = logging.getLogger(__name__) # __name__ == module's name, not '__main__'

rawDescription: Suspend the formating of the logger, then go back to it


rawDescription: How to convert sparse matrix to dense form using python

description: Convert sparse matrix to dense form using python


code:
def main():
    nums = create_list(1000)
    counts = count_list(nums)
    for i in range(1,7):
        print(i, counts[i])

rawDescription: I need to get my main function working

description: I need to get my main function working


code:
df.loc[df['ImageName'] <= 70, 'Test'] = 1
df.loc[(df['ImageName'] > 70) & (df['ImageName'] <= 90), 'Test'] = 2

rawDescription: new python pandas dataframe column based on value of variable, using function

description: New python pandas dataframe column based on value of variable, using function


code:
def get_time(x):
    (start, _, _) = x
    return start

times = rdd.map(get_time)

rawDescription: Using Apache-Spark to analyze time series


code: list(gen(3, 2))

rawDescription: How to generate these vectors quickly in Python?

description: Generate these vectors quickly in Python


rawDescription: reading Unicode string as json object in python

description: Reading Unicode string as json object in python


code:
xvals=riadok[3::2]
yvals=riadok[4::2]
xmax=max(xvals)
ymax=max(yvals)

rawDescription: Python: find maximum x-value and maximum y-value in text file


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

# Generate some data
N = 10
x = np.arange(N)
y = np.array([i*(10**-38) for i in x])

fig, ax = plt.subplots()

# Plot the data
ax.plot(x,y)

# Get the text object
text = ax.yaxis.get_offset_text()

# Set the size.
text.set_size(30) # Overkill!

plt.show()

rawDescription: Python Pylab, how to alter the size of the label specifying the magnitude of the axes


rawDescription: Creating a normal with limits with variable standard deviation


code:
def undo_last_csv_import(request):
    some_record = Record.objects.by_user(request.user).from_the_last_import()[0]
    latest_saved_version_of_some_record = Version.objects.get_for_date(
        some_record,
        datetime.now(), # The latest saved Version at the moment.
        )
    # Revert all versions that belong to the same revision
    # as the version we got above.
    latest_saved_version_of_some_record.revision.revert()

rawDescription: How to implement an "undo" feature using Python/Django

description: Implement an "undo" feature using Python/Django


code:
print(rawdict.data)
# {2}

rawDescription: How to build an undo storage with limit?

description: Build an undo storage with limit


rawDescription: Plotting pandas timedelta

description: Plotting pandas timedelta


code:
import pandas as pd
df = pd.read_csv("brainandbody.csv", skipinitialspace=True)
df
df.mean()

rawDescription: Python - "cannot perform reduce with flexible type" when trying to use numpy.mean


code:
reps=[]
for i in range(len(msg)-1):
    if msg[i] == msg[i + 1] or msg[i] == msg[i - 1]:
        reps.append(msg[i])

reps

rawDescription: Longest repeating substring using for-loops and if-statements


code: return rreverse(s[1:]) + s[0]

rawDescription: Need help understanding a recursive solution to reverse a List


code:
s1 = 'Hello'
s2 = 'Hi'
s1 + s2

rawDescription: Subprocess Variables

description: Subprocess Variables


code:
def combs(elt2color, combination_size=4, max_colors=3):

    def inner(needed, index):
        if needed == 0:
            yield result
            return
        if n - index < needed:
            # not enough elements remain to reach
            # combination_size
            return
        # first all results that don't contain elts[index]
        for _ in inner(needed, index + 1):
            yield result
        # and then all results that do contain elts[index]
        needed -= 1
        elt = elts[index]
        color = elt2color[elt]
        color_added = color not in colors_seen
        colors_seen.add(color)
        if len(colors_seen) <= max_colors:
            result[needed] = elt
            for _ in inner(needed, index + 1):
                yield result
        if color_added:
            colors_seen.remove(color)

    elts = tuple(elt2color)
    n = len(elts)
    colors_seen = set()
    result = [None] * combination_size
    for _ in inner(combination_size, 0):
        yield tuple(result)

rawDescription: Efficient combinations of N colored elements with restriction in the number of colors


code:
from django.contrib import admin
from my_app import models

admin.site.register(models.Router)

rawDescription: Uploading files using Django Admin

description: Uploading files using Django Admin


code: np.sum(y == 1)

rawDescription: random subsampling of the majority class

description: Random subsampling of the majority class


code:
from scipy.linalg import circulant
r = np.array([1,2,3,4])

rawDescription: Create a "wrapped" ndarray from a given array


code:
import wx
import wx.lib.scrolledpanel as scrolled
class MyPanel(scrolled.ScrolledPanel):

    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent, -1)
        self.SetAutoLayout(1)
        self.SetupScrolling()

rawDescription: How to scroll Panel with GridBagSizer in wxPython

description: Scroll Panel with GridBagSizer in wxPython


code:
dct = {k: sorted(l, reverse=True)[:10 if k in ('a','c') else 20]
    for k, l in dct.items()}

rawDescription: Slicing a dictionary of list

description: Slicing a dictionary of list


code:
yo.say_hi()
a = yo()
a.say_hi()

rawDescription: Where is the best place to put support functions in a class?


code:
# Input prompt.  '\#' will be transformed to the prompt number
c.PromptManager.in_template = br'{color.Green}\# {color.LightBlue}~\u{color.Green}:\w{color.LightBlue} {git_branch_and_st} \$\n>>> '

# Continuation prompt.
c.PromptManager.in2_template = br'... '

rawDescription: How do I define custom function to be called from IPython's prompts?

description: Define custom function to be called from IPython's prompts


code: points = list(set(points))

rawDescription: Deleting elements from numpy or list in python


code:
class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.description = "This shape has not been described yet"
        self.author = "Nobody has claimed to make this shape yet"

    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def describe(self, text):
        self.description = text

    def authorName(self, text):
        self.author = text

    def scaleSize(self, scale):
        self.x = self.x * scale
        self.y = self.y * scale

rawDescription: Tcl Object Oriented extension for porting into Python code


code:
import nltk

nltk.download()

rawDescription: How to delete a particular sentence from a file using line number in Python

description: Delete a particular sentence from a file using line number in Python


rawDescription: Writing Calculated Info to the front of a text file in Python


code:
total = 0
for line in rows:
    numSlashes = line.count('/')
    if numSlashes > 0:
        total += numSlashes + 1

rawDescription: Python: How to count items in a specific column


rawDescription: how to extend a python dictionary while there are list inside

description: Extend a python dictionary while there are list inside


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

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

plt.figure()
levels = np.arange(-1.0,1.5,0.25)
CS = plt.contour(X, Y, Z, levels=levels)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('levels = {}'.format(levels.tolist()))
plt.show()

rawDescription: Adding extra contour lines using matplotlib 2D contour plotting


code:
colors = [(1,1,1)] + [(random(),random(),random()) for i in xrange(255)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)

rawDescription: How to display objects in different random colors on a white background in matplotlib python?

description: Display objects in different random colors on a white background in matplotlib python


code:
class MyClass(object):
    @staticmethod
    def function1(num1, num2):
        return num1 + num2

class index:
    @staticmethod
    def GET():
        num1, num2 = get_numbers_somehow()
        MyClass.function1(num1, num2)

rawDescription: Why do I need to pass an object to this class to make it work?


code:
s
pd.get_dummies(s, prefix=s.name, prefix_sep='')

rawDescription: protein sequence coding

description: Protein sequence coding


code:
m.__dummy__ = Mock()
m.__dummy__

rawDescription: Unable to mock __subclasses__ in python

description: Unable to mock __subclasses__ in python


code:
EmptyArray = []
d = {}
newlist = []

for gFeat in GeneratorLayer.getFeatures():

    Owner = gFeat.attributes()[gProvider.fieldNameIndex('CompanyNam')].toString()

    A = ([str(i) for i in Owner]) #convert from PyQt4.QtCore.QString to normal string
    B = ''.join(A)

    EmptyArray.append(B)

    m = 1

    for n in EmptyArray:  # no need to enumerate as numbers should increment only on uniques

        if n not in d:  # this is a unique
            d[n] = [m]  # put number in dictionary, with key as val.
            m += 1  # so increment

        elif n == '':  # if it's blank (and if it is already in the dict)
            d[n].append(m)  # append new number, as blanks always increment
            m += 1  # increment

    for name in EmptyArray:  # looping less as only want to get names

        if name == '':  # if it's a blank, we want to pop out the first item in the list.
            a2 = str('{},NULL'.format(d[name].pop(0)))

        else:  # otherwise we just index the first item.
            a2 = str('{},{}'.format(d[name][0], name))

rawDescription: Re-write loop to assign a number to every row in a column


code:
class MyList(QtGui.QListWidget):
    def mouseReleaseEvent(self, e):
        super(MyList, self).mouseReleaseEvent(e)
        print('released', e)

rawDescription: PyQt4: emit signal when mouse is released anywhere on the screen


code: user = request.auth[0]

rawDescription: Is there a way to get the username of the currently authenticated user in python Bottle using basic_auth?


code:
class StateWidget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        style1 = "background-color: yellow"
        style2 = "background-color: black"

        # animation doesn't work for strings but provides an appropriate delay
        animation = QtCore.QPropertyAnimation(self, 'styleSheet')
        animation.setDuration(150)

        state1 = QtCore.QState()
        state2 = QtCore.QState()
        state1.assignProperty(self, 'styleSheet', style1)
        state2.assignProperty(self, 'styleSheet', style2)
        #              change a state after an animation has played
        #                               v
        state1.addTransition(state1.propertiesAssigned, state2)
        state2.addTransition(state2.propertiesAssigned, state1)

        self.machine = QtCore.QStateMachine()
        self.machine.addDefaultAnimation(animation)
        self.machine.addState(state1)
        self.machine.addState(state2)
        self.machine.setInitialState(state1)
        self.machine.start()

rawDescription: Blinking Widget with PyQt

description: Blinking Widget with PyQt


code:
class SomeClass(object):
    def somemethod(self):
        return '''\
This text
does not need to be indented
at all.
In this text, newlines are preserved.
'''
        # but do continue the next line at the right indentation.

rawDescription: String Concatenation: Putting large chuck of text in Python code


rawDescription: Python not all in operation

description: Python not all in operation


rawDescription: A system independent way using python to get the root directory/drive on which python is installed


rawDescription: Plotting bar charts by each two rows

description: Plotting bar charts by each two rows


rawDescription: Python - split list in to sublists based on another list


code: df.groupby( [df.index.year, df.index.month, df.index.day, df.index.hour] ).count()

rawDescription: counting records on per hour, per day and create multindex DataFrame as output

description: Counting records on per hour, per day and create multindex DataFrame as output


code:
from itertools import chain as ch

files = list(ch.from_iterable(os.listdir(x) for x in ['dir1', 'dir', 'dir3'] if os.path.isdir(x)))

rawDescription: One-liner to get flat list of files from a list of possible directories?


rawDescription: Parse HTML Table with Python BeautifulSoup


code:
s = ':foo [bar]'
''.join(c for c in s if c.isalnum() or c.isspace())
''.join(c for c in s if c.isalnum() or c.isspace()).split()

rawDescription: Split string without non-characters

description: Split string without non-characters


rawDescription: Running a python script on my hosting

description: Running a python script on my hosting


rawDescription: Adding a constant integer to a value in a python dictionary


code:
def perturbate(x, h):
    """
    Given an initial point x = [x0, x1, ..., xn]
    Returns a list of points containing the original point and,
    for every coordinate, "perturbations" of that point created
    by adding and subtracting 'h' to the coordinate.
    """
    # start with the original point plus
    # 2 copies of it for every coordinate
    points = [x[:] for i in range(len(x)*2 + 1)]

    for coordinate_index in range(len(x)):
        points[coordinate_index*2 + 1][coordinate_index] -= h
        points[coordinate_index*2 + 2][coordinate_index] += h
    return points

rawDescription: Update certain elements in a list

description: Update certain elements in a list


rawDescription: python regular expression re.search(r"([a-z]+[A-Z]+[0-9]+)", password)

description: Python regular expression re.search(r"([a-z]+[A-Z]+[0-9]+)", password)


code:
A
setones_between_triggers(A,2,-2)

rawDescription: numpy array set ones between two values, fast

description: Numpy array set ones between two values, fast


rawDescription: How to change Pandas dataframe index value?

description: Change Pandas dataframe index value


code:
import csv
from operator import itemgetter

cols = [1,2] # list all the columns you want here
with open('testfile') as f:
    ig = itemgetter(*cols)
    result = [ig(row) for row in csv.reader(f, delimiter=';')]

result

rawDescription: Python : Alias in comprehensive list

description: Python : Alias in comprehensive list


code:
s="""group1_big
group1_big
group1_bigs
group1_bugs
group2_bug"""
d={}
for i in s.split('\n') :
  d.setdefault(i[:7],[]).append(i)

from collections import Counter
count={len(j):Counter([t[8] for t in j]).most_common() for i,j in d.items()}
final_count=[next((t[0] for t in j if t[1]>=0.75*i),j) for i,j in count.items()]
words=[next((t for t in v if t[8] in final_count),None) for v in d.values()]
words

rawDescription: Compare Characters Within a String

description: Compare Characters Within a String


code:
from lxml.etree import fromstring
tree = fromstring('<x:html xmlns:x="http://www.w3.org/1999/xhtml"/>')

rawDescription: XPath Child Traversal Methods and Performance


rawDescription: Automated alignment of "tabular" Python code


code:
def f(d):
    paths = []
    for key, value in d.items():
        if value is None:
            paths.append([key, value])
        else:
            internal_lists = f(value)
            for l in internal_lists:
                paths.append([key] + l)
    return paths

rawDescription: dict of dicts python

description: Dict of dicts python


code: {{ order.pa_tranlength * order.pa_width * order.pa_costprice|to_decimal }}

rawDescription: Jinja2 convert float to decimal mid calculation


rawDescription: What does the Star operator mean in Python?


code:
from bp import auto_bp
app.register_blueprint(auto_bp, url_prefix='/list')

rawDescription: Binding Flask AutoIndex to a different URL other than http://localhost?


code:
#Second .py module
import thread
import create_ftp_server

this_ftp = create_ftp_server.ftp_server()

thread.start_new_thread(this_ftp.run,())
thread.start_new_thread(this_ftp.add_user,('user','password',".",'elradfmwM'))

rawDescription: PyFtpdLib How to add a user while still running server


code:
a, b, c = 3, 1, 8

x = min(a, b, c)  # Smallest of the three
z = max(a, b, c)  # Largest of the three
y = (a + b + c) - (x + z)  # Since you have two of the three, you can solve for
                           # the third

print(a, b, c)
print(x, y, z)

rawDescription: How to manually sort a list of numbers in Python?

description: Manually sort a list of numbers in Python


rawDescription: Empty EmbeddedDocument field?

description: Empty EmbeddedDocument field


code: [Counter(x) for x in a]

rawDescription: How to count occurrences of specific element for arrays in a list?

description: Count occurrences of specific element for arrays in a list


code:
from itertools import groupby

def lookAround(pos1, pos2):
    i, j = pos1[0], pos1[1]
    # look around 2 above/below, grouping into runs of colors, returns list of lists
    list1 = groupby([pos2[(i_, j)] for i_ in range(max(0,i-2), min(9,i+2))])
    # look around 2 left right, grouping into runs of colors, returns list of lists
    list2 = groupby([pos2[(i, j_)] for j_ in range(max(0,j-2), min(9,j+2))])
    # return true if there's a run of 3 or more colours in either direction
    return any(lambda l: len(l)>=3, list1 + list2)

rawDescription: Haskell Algorithm/Candy Crush possible Moves


code:
def get_angle_text(angle_plot):
    angle = angle_plot.get_label()[:-1] # Excluding the degree symbol
    angle = "%0.2f"%float(angle)+u"\u00b0" # Display angle upto 2 decimal places

    # Get the vertices of the angle arc
    vertices = angle_plot.get_verts()

    # Get the midpoint of the arc extremes
    x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
    y_width = (vertices[0][5] + vertices[-1][6]) / 2.0

    #print x_width, y_width

    separation_radius = max(x_width/2.0, y_width/2.0)

    return [ x_width + separation_radius, y_width + separation_radius, angle]

rawDescription: Best way to plot an angle between two lines in Matplotlib

description: Plot an angle between two lines in Matplotlib


code:
turn1l = []
for i in range(5):
    ...

rawDescription: Raise SystemExit not working

description: Raise SystemExit not working


code: ET.tostring(root, pretty_print=True)

rawDescription: How to pass ET.dump() xml string from a Django view to a template -- python django ElementTree

description: Pass ET.dump() xml string from a Django view to a template -- python django ElementTree


code: return sorted(ob.items(), key=lambda x: x[1])[:default]

rawDescription: Sorting function works differently when imported rather then called in script


rawDescription: using dict vs class __dict__ method to format strings

description: Using dict vs class __dict__ method to format strings


code:
for components in itertools.product(*ranges):
    ips.append('{}.{}.{}.{}'.format(*components)) # OR
    ips.append('.'.join(map(str, components)))

rawDescription: Python parse ip regex

description: Python parse ip regex


code:
import pandas as pd
import numpy as np

np.random.seed(123456)
num_periods=5
monthindex=pd.date_range('1/1/2014', periods=num_periods, freq='MS')
dd = pd.DataFrame(data={'date':monthindex,
                        'c1': np.random.uniform(10, 20, size=num_periods),
                        'c2': np.random.uniform(30, 40, size=num_periods)},
                  index=monthindex,
)
print(dd)

rawDescription: Specifying dataframe index as date at time of creation


code:
grb = df.groupby(['ID0', 'Time'])
df2 = grb['Data0', 'Data1'].transform(lambda obj: obj.values[::-1])
df.join(df2, rsuffix='.2')

rawDescription: Widening Pandas Data Frame, Similar to Pivot or Stack/Unstack


code:
names = ['spam', 'eggs']
for name in names:
    ro.r("source('" + codeLoc + "/filename" + name + ".R')")

rawDescription: assigning then attaching a filepath name in python using rpy2

description: Assigning then attaching a filepath name in python using rpy2


rawDescription: How does python do list slices and modification on the LHS?


code:
X, Y = np.meshgrid(X, Y)
ax.plot_surface(X, Y, Z.T)

rawDescription: Python & Matplotlib: How to create a meshgrid to plot surf?


code:
def sgn_pbc(x, y, Lbox):
    d = abs(x-y)
    w = sgn(Lbox/2., d)
    return  w * (y < x) - (x < y)

rawDescription: efficient sign function in python for case of periodic boundary conditions

description: Efficient sign function in python for case of periodic boundary conditions


code: map(lambda x,y:x(y), functions, values)

rawDescription: Zip and apply a list of functions over a list of values in Python


rawDescription: Pythonic way to rewrite the following C++ string processing code


code:
def BinominalCoefficient(n,k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res //= (i + 1)
    return res
def CatalanNumbers(n):
   c = BinominalCoefficient(2*n, n)
   return (c//(n+1))
print (CatalanNumbers(511))

rawDescription: Python calculating Catalan Numbers

description: Python calculating Catalan Numbers


rawDescription: Regular expression in python 2.7 to identify any non numeric symbol in a column in dataframe


code:
for key in sorted(index):
    print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key]))))

rawDescription: Python sort in a dictionary and a set

description: Python sort in a dictionary and a set


code:
import xml.etree.ElementTree as ET
tree = ET.parse("input.xml")
root = tree.getroot()
elems = tree.findall('.//{http://abc}ActnCode')
print('elems', elems)
for elem in elems:
    elem.text = 'CAN'
tree.write("output.xml")

rawDescription: replace xml values with python

description: Replace xml values with python


code: pd.concat([df1, df2], axis=1)

rawDescription: Merge many tsv files by common key using Python pandas


code:
for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
    print(*row)

rawDescription: How can I print a dictionary in table format?

description: Print a dictionary in table format


code:
C = np.random.rand(2,3,3)
D = C.copy()
C[:, :, 1:] = np.diff(C, axis = -1)
C = np.cumsum(C, axis = -1)
np.allclose(C,D)

rawDescription: In place difference between elements of a Numpy array


code:
masked = map(lambda x: any(_ in x for _ in w.apply(str.lower)), \
             df['Tweet'].apply(str.lower))

rawDescription: pandas find strings in common among Series

description: Pandas find strings in common among Series


code: dig = reversed(int(d) for d in str(num))

rawDescription: Divide number into digits and save them in list (array) using python


code:
[
  {employeeId:1,Salary:10000},
  {employeeId:2,Salary:15000}
]

rawDescription: SQL Alchemy: How to bulk update values from a list of dicts


rawDescription: Can I extend list in Python with prepend elements instead append?

description: Extend list in Python with prepend elements instead append


code:
from itertools import chain, permutations, product

def new_edge_sets(deleted_edges):

    def edges_to_pieces(l):
        new_list = []
        n = len(l)
        for i in xrange(-1,n-1):
            new_list.append((l[i%n][1], l[(i+1)%n][0]))
        return new_list

    def permute(it):
        return product(*(permutations(i) for i in it))

    def permute2(it):
        return chain.from_iterable(permute(p) for p in permutations(it))

    def pieces_to_edges(p):
        new_list = []
        n = len(p)
        for i in xrange(n):
            new_list.append((p[i%n][1], p[(i+1)%n][0]))
        return new_list

    def permute3(s):
        return (pieces_to_edges(s[:1] + list(p)) for p in permute2(s[1:]))

    return permute3(edges_to_pieces(deleted_edges))

rawDescription: How to enumerate possible reconstructions of a Hamiltonian cycle without DFS/BFS?

description: Enumerate possible reconstructions of a Hamiltonian cycle without DFS/BFS


code: df.groupby(["groupA", "groupB"]).sum()

rawDescription: Count the number of matched element in pandas


rawDescription: How to print a binary number

description: Print a binary number


code:
while roomNumber not in ("L1", "L2", "L3", "L4", "L5"):
    ...

rawDescription: Multiple while matches in python

description: Multiple while matches in python


code:
df2 = gb.agg({
    'ActivityDateTime': ['first', 'last'],
    'Value1': 'mean',
    'Value2': 'mean'})

rawDescription: Aggregation on Pandas data frame for selected rows


code:
tmpset = set(L2)
tmpset.update(L3)
L4 = [ n for n in L1 if n not in tmpset ]

rawDescription: Python - removing items from lists

description: Python - removing items from lists


code:
from numpy.core.umath_tests import inner1d
inner1d(A,B)

rawDescription: Numpy equivalent of dot(A,B,3)

description: Numpy equivalent of dot(A,B,3)


code: results = list(iterator)

rawDescription: What are the advantages of "yield item" vs return iter(items)?


code:
# get 2 best results:
results = BlogPost.query.whoosh_search('cool', limit=2)

rawDescription: Search Index for user articles

description: Search Index for user articles


code: ostr.write(line + '\n')

rawDescription: Append Text (Single Letter) to the end of each line in a text file


code:
arr = np.random.randint(0, 255, (3,3))
brightest = arr.max()
threshold = brightest // 2
arr
brightest
threshold

rawDescription: What's the fastest way to threshold a numpy array?


code:
from tkinter import *

def box(a):
    z['text'] = a

def start(root):
    box('hi')
    root.after(100, start, root)

root = Tk()
z = Label(root, text='')
z.place(width=50, height=20)
start(root)
root.mainloop()

rawDescription: Looking for a way to stop memory leak in this basic program


code:
import cairo
from gi.repository import Gtk
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

class MyApp(object):
    """Double buffer in PyGObject with cairo"""

    def __init__(self):
        # Build GUI
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'test.glade')
        self.builder.add_from_file(self.glade_file)

        # Get objects
        go = self.builder.get_object
        self.window = go('window')

        # Create buffer
        self.double_buffer = None

        # Connect signals
        self.builder.connect_signals(self)

        # Everything is ready
        self.window.show()

    def draw_something(self):
        """Draw something into the buffer"""
        db = self.double_buffer
        if db is not None:
            # Create cairo context with double buffer as is DESTINATION
            cc = cairo.Context(db)

            # Scale to device coordenates
            cc.scale(db.get_width(), db.get_height())

            # Draw a white background
            cc.set_source_rgb(1, 1, 1)

            # Draw something, in this case a matrix
            rows = 10
            columns = 10
            cell_size = 1.0 / rows
            line_width = 1.0
            line_width, notused = cc.device_to_user(line_width, 0.0)

            for i in range(rows):
                for j in range(columns):
                    cc.rectangle(j * cell_size, i * cell_size, cell_size, cell_size)
                    cc.set_line_width(line_width)
                    cc.set_source_rgb(0, 0, 0)
                    cc.stroke()

            # Flush drawing actions
            db.flush()

        else:
            print('Invalid double buffer')

    def main_quit(self, widget):
        """Quit Gtk"""
        Gtk.main_quit()

    def on_draw(self, widget, cr):
        """Throw double buffer into widget drawable"""

        if self.double_buffer is not None:
            cr.set_source_surface(self.double_buffer, 0.0, 0.0)
            cr.paint()
        else:
            print('Invalid double buffer')

        return False

    def on_configure(self, widget, event, data=None):
        """Configure the double buffer based on size of the widget"""

        # Destroy previous buffer
        if self.double_buffer is not None:
            self.double_buffer.finish()
            self.double_buffer = None

        # Create a new buffer
        self.double_buffer = cairo.ImageSurface(\
                cairo.FORMAT_ARGB32,
                widget.get_allocated_width(),
                widget.get_allocated_height()
            )

        # Initialize the buffer
        self.draw_something()

        return False

if __name__ == '__main__':
    gui = MyApp()
    Gtk.main()

rawDescription: Drawing in PyGobject (python3)

description: Drawing in PyGobject (python3)


code:
g = sns.clustermap(networks.corr(),

                  # Turn off the clustering
                  row_cluster=False, col_cluster=False,

                  # Add colored class labels
                  row_colors=network_colors, col_colors=network_colors,

                  # Make the plot look better when many rows/cols
                  linewidths=0, xticklabels=False, yticklabels=False)

rawDescription: How to express classes on the axis of a heatmap in Seaborn

description: Express classes on the axis of a heatmap in Seaborn


code: [list(i.group(1,2)) for i in re.finditer('(\d{2})(020511|00)', theStr)]

rawDescription: Python String Double Splitting?

description: Python String Double Splitting


code:
a
overlap
indices

rawDescription: numpy: find symmetric values in 2d arrays

description: Numpy: find symmetric values in 2d arrays


code:
circles = []
countY = 750
circles.append((pygame.color.Color('black'), (150, countY), 25, 0))
circles.append((pygame.color.Color('black'), (250, countY), 25, 0))
circles.append((pygame.color.Color('white'), (450, countY), 25, 0))
circles.append((pygame.color.Color('white'), (550, countY), 25, 0))

while game:
    window.fill(grey)
    for event in pygame.event.get():
        # pygame.event.get() don't call pygame.event.get() twice

        if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
            diceRoll = random.randint(1, 4)
            circles.append((pygame.color.Color('black'), (150, countY - 72 * diceRoll), 25, 0))

    for (color, pos, rad, w) in circles:
        pygame.draw.circle(window, color, pos, rad, w)
    pygame.display.flip()

rawDescription: Why is python skipping these lines of code?


rawDescription: Limits of quad integration in scipy with np.inf


code:
text = "Ryan 123"
nums = map(ord, text)
nums

rawDescription: How to convert numbers into characters?

description: Convert numbers into characters


code: sum(i[1]==j[1] for i,j in izip(lstup1,lstup2))

rawDescription: Faster way to count number of matching 2nd elements between two list of tuples? - Python


code: strong, rest_of_the_content = myTargetElementObject.text.split(". ", 1)

rawDescription: Selecting parent element text only using Selenium


code: (pointDistFunc(p1, p2) for p1 in lst)

rawDescription: Python Effecient Wrappers

description: Python Effecient Wrappers


code:
table = [[r[0], float(r[1]), float(r[2]),
         float(r[3]), float(r[4]), r[5], float(r[6])] for r in table]

rawDescription: Arithmetic Operations with Nested Lists in Python


code: df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

rawDescription: Pandas: How to create a data frame of random integers?


code:
from types import FunctionType
from functools import wraps

def copy_func(func,global_namespace):
    "copies a function object with the new specified global scope"
    c = FunctionType(func.__code__,global_namespace,func.__name__,func.__defaults__,func.__closure__)
    try:
        c.__kwdefaults__ = func.__kwdefaults__
    except AttributeError:pass #this is only for python 3
    c = wraps(func)(c) #copy all metadata although there doesn't seem to be any for roboclaw
    return c

rawDescription: Encapsulate the scope of an imported module


code:
import os

# The notifier function
def notify(title, subtitle, message):
    t = '-title {!r}'.format(title)
    s = '-subtitle {!r}'.format(subtitle)
    m = '-message {!r}'.format(message)
    os.system('terminal-notifier {}'.format(' '.join([m, t, s])))

# Calling the function
notify(title    = 'A Real Notification',
       subtitle = 'with python',
       message  = 'Hello, this is me, notifying you!')

rawDescription: Python post osx notification

description: Python post osx notification


rawDescription: Get the column names of a python numpy ndarray


code:
from threading import Event

class Sleep(object):
    def __init__(self, seconds, immediate=True):
        self.seconds = seconds
        self.event = Event()
        if immediate:
            self.sleep()

    def sleep(self, seconds=None):
        if seconds is None:
            seconds = self.seconds
        self.event.clear()
        self.event.wait(timeout=seconds)

    def wake(self):
        self.event.set()

rawDescription: abortable sleep() in Python

description: Abortable sleep() in Python


rawDescription: Getting value of a class in selenium and python


rawDescription: Controlling a relay with a momentary button in Python


code:
import numpy as np
import pandas as pd

class OnlineVariance(object):
    """
    Welford's algorithm computes the sample variance incrementally.
    """
    def __init__(self, iterable=None, ddof=1):
        self.ddof, self.n, self.mean, self.M2 = ddof, 0, 0.0, 0.0
        if iterable is not None:
            for datum in iterable:
                self.include(datum)

    def include(self, datum):
        self.n += 1
        self.delta = datum - self.mean
        self.mean += self.delta / self.n
        self.M2 += self.delta * (datum - self.mean)
        self.variance = self.M2 / (self.n-self.ddof)

    @property
    def std(self):
        return np.sqrt(self.variance)

d = {'Open': {0: 159.18000000000001, 1: 157.99000000000001, 2: 157.66, 3:
 157.53999999999999, 4: 155.03999999999999, 5: 155.47999999999999, 6:
 155.44999999999999, 7: 155.93000000000001, 8: 155.0, 9: 157.72999999999999},
 'Close': {0: 157.97999999999999, 1: 157.66, 2: 157.53999999999999, 3:
 155.03999999999999, 4: 155.47999999999999, 5: 155.44999999999999, 6: 155.87, 7:
 155.0, 8: 157.72999999999999, 9: 157.31}}

df = pd.DataFrame.from_dict(d)

df['Close_Stdev'] = pd.rolling_std(df[['Close']],window=5)

ov = OnlineVariance()
for n in range(5):
    ov.include(df['Close'].shift(n))

df['std'] = ov.std
print(df)
assert np.isclose(df['Close_Stdev'], df['std'], equal_nan=True).all()

rawDescription: How do I use pandas' rolling_std to consider two columns in its observation?

description: Use pandas' rolling_std to consider two columns in its observation


rawDescription: Checking from Python which easy_install version is available?


code:
try:
   model.objects.get(pk=1)
except model.DoesNotExist:
   model.objects.create(pk=1)

description: MultipleObjectsReturned with get_or_create


code:
from datetime import date, timedelta
today = date.today()
# Use today.isoweekday() if you want the week
# to start on Sunday instead of Monday
first_day_of_week = date.today() - timedelta(today.weekday())
end_date = first_day_of_week + timedelta(days=6)
this_week_qs = Sample.objects.filter(date__range=[startdate, enddate])

rawDescription: Sorting queryset with date

description: Sorting queryset with date


code:
df = df.sort(["FullDate", "Score"]) # THIS IS THE WRONG ORDER
df.groupby(["Year", "Subject", "Student"]).tail(1)

rawDescription: Python pandas: Identify Records Based on Multiple Criteria on Multiple Fields


rawDescription: Iteratively copy specific rows from CSV file to new file


code:
class Foo(object):
    calls=0

rawDescription: Static member of a function in Python ?

description: Static member of a function in Python


code:
from ..Level1 import t_Generic
from t_Generic import A as GenericA
from t_Generic import B as GenericB
from t_Generic import C as GenericC

rawDescription: pythonic way to customize classes

description: Pythonic way to customize classes


rawDescription: Python If Statement Never Evaluates to True


code: array[np.abs(array) < eps] = 0

rawDescription: Python Numpy - Treat really small numbers as zero


code:
for sublist in list:
    y = sublist
    fig = plt.figure()
    plt.plot(x,y)
    plt.title(names[g])
    g = g + 1
    plt.savefig(genes[g-1])
    plt.close(fig)

rawDescription: Matplotlib: want different plot for each line


code: a[w] = np.roll(a[w], 1, axis=1)

rawDescription: Reverse certain rows in N by 2 array

description: Reverse certain rows in N by 2 array


code: np.hstack([dydx, dydx[-1]])

rawDescription: simple but weird vstack/concatenate problems (python)

description: Simple but weird vstack/concatenate problems (python)


code:
class Property(object):
    def __init__(self, type_, default_value):
        self._type = type_
        self._default_value = default_value

    def generate_property(self, name):
        self._internal_name = '_' + name
        def getter(object_):
            return getattr(object_, self._internal_name)
        def setter(object_, value):
            if not isinstance(value, self._type):
                raise TypeError("Expect type {0}, got {1}.".format(self._type, type(value)))
            else:
                setattr(object_, self._internal_name, value)
        return property(getter, setter)

class AutoPropertyMeta(type):
    def __new__(meta, name, bases, attributes):
        defaults = {}
        for name, value in attributes.iteritems():
            if isinstance(value, Property):
                attributes[name] = value.generate_property(name)
                defaults[name] = value._default_value
        # create __init__ to inject into the class
        # our __init__ sets up our secret attributes
        if '__init__' in attributes:
            realInit = attributes['__init__']
            # we do a deepcopy in case default is mutable
            # but beware, this might not always work
            def injectedInit(self, *args, **kwargs):
                for name, value in defaults.iteritems():
                    setattr(self, '_' + name, copy.deepcopy(value))
                # call the "real" __init__ that we hid with our injected one
                realInit(self, *args, **kwargs)
        else:
             def injectedInit(self, *args, **kwargs):
                for name, value in defaults.iteritems():
                    setattr(self, '_' + name, copy.deepcopy(value))
        # inject it
        attributes['__init__'] = injectedInit
        return super(AutoPropertyMeta, meta).__new__(meta, name, bases, attributes)

rawDescription: Python: How to create instance attribute by metaclass?


code: d[max(d)]

rawDescription: getting value of the maximum key in dictionary (python)

description: Getting value of the maximum key in dictionary (python)


code: print ( [ (v, k) for k, v in merged.items () ] )

rawDescription: List of values for duplicate keys in dictionary Python


code:
base=a.max()+1
c=a+base*b

rawDescription: remove duplicate elements from two numpy arrays

description: Remove duplicate elements from two numpy arrays


code:
import argparse

parser=argparse.ArgumentParser(
    description='''My Description. And what a lovely description it is. ''',
    epilog="""All's well that ends well.""")
parser.add_argument('--foo', type=int, default=42, help='FOO!')
parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
args=parser.parse_args()

rawDescription: Writing a help for python script

description: Writing a help for python script


rawDescription: How to remove a column in a numpy array?

description: Remove a column in a numpy array


code:
['I have 9 sheep in my garage',
'Video games are super cool.',
'Some peanuts can sing, though they taste a whole lot better than they sound!']

rawDescription: Split Sentence on Punctuation or Camel-Case


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

time_ms = np.arange(0,9,0.1)
freq = -500 + 1000.*np.random.rand(time_ms.shape[0])

majorYlocator = ticker.MultipleLocator(100)
majorXlocator = ticker.MultipleLocator(1)
minorXlocator = ticker.MultipleLocator(0.2)

ax = plt.subplot(212)

ax.set_ylim((-500,500))
ax.yaxis.set_major_locator(majorYlocator)
ax.set_xlim((0,8))
ax.xaxis.set_major_locator(majorXlocator)
ax.xaxis.set_minor_locator(minorXlocator)

ax.plot(time_ms, freq)
ax.plot(time_ms, y2, color='r', lw=1)
ax.plot(time_ms, y3, color='r', lw=1)
ax.fill_between(time_ms, y2, 500, color='red', alpha=0.3)
ax.fill_between(time_ms, y3, -500, color='red', alpha=0.3)

ax.grid(b=True, which='major', color='k', linestyle='-')
ax.grid(which='minor', color='k', linestyle=':', alpha=0.5)

ax.set_title("Response Plot")
ax.set_xlabel('Time (ms)')
ax.set_ylabel('Voltage (V)')

plt.show()

rawDescription: Plot only x-axis minor gridlines in x-y graph in Python


rawDescription: Complex numbers usage in python

description: Complex numbers usage in python


code:
from urlparse import urlparse
o = urlparse('http://www.example.com/query%28%29.cgi?somevar=thing&someothervar=otherthing')
o

rawDescription: Looking to write out to separate files; Python:


rawDescription: Fastest way to read every n-th row with numpy's genfromtxt


code:
soup = BeautifulSoup(html_content,"lxml")

rez = [d.text for d in soup.select("#__xclaimwords_wrapper")]

rawDescription: Parsing forum posts with python3 and beautiful soup


code:
import json
json_str = '{"foo": "bar"}'
d = json.loads(json_str) # d = {'foo': 'bar'}

rawDescription: JSON and AJAX with Python

description: JSON and AJAX with Python


code:
# Incidentally, they say that this method returns a list with the current letter's positions.
# This isn't true - it is returning a generator.
# To return a list, the outermost parenthesis need to be replaced with square brackets,
#    or by simply adding list before the parenthesis
# i.e. [...] or list(...)
def zip_letters(xl, yl, dxl, dyl, rl, word):
    """Returns a list with the current letter's positions (x, y and rotation).
    E.g.: for letter 'L' with positions x = 10, y = 20 and rotation = 30:
    >>> [[10, 20, 30], 'L']
    Store the last value of each position and pop the first one in order to
    avoid setting an x,y or rotation value that have already been used.
    """
    # Notice the parenthesis below - this is a generator that gets exhausted after one iteration
    return (
        ([pl.pop(0) if pl else None for pl in (xl, yl, dxl, dyl, rl)], char)
        for char in word)

rawDescription: Unpacking in a for loop twice

description: Unpacking in a for loop twice


code:
from django.shortcuts import render_to_response

def my_view(request):
    mylist = ['item 1', 'item 2', 'item 3']

    return render_to_response('template.html', {'mylist':mylist})

rawDescription: how to render to response?

description: Render to response


code:
gzopen64
gz_open

rawDescription: Python C extension link with a custom shared library


code:
from bs4 import BeautifulSoup
from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor

data = """
Lake Travis Zipline Adventures
"""

soup = BeautifulSoup(data)

# get onclick value
onclick = soup.find("div", class_="title", onclick=True)["onclick"]

# parse onclick js code
parser = Parser()
tree = parser.parse(onclick)
for node in nodevisitor.visit(tree):
    if isinstance(node, ast.FunctionCall):
        print(node.args[-1].value)

rawDescription: Need help Regex for python

description: Need help Regex for python


code:
# only select url nodes that have image child
url_tags =  tree.xpath("//url[image]")
data = [(e.xpath("./image/title//text()")[0], e.xpath("./loc/text()")[0]) for e in  url_tags]

rawDescription: Using LXML to print out individual strings from file


code:
excluded = set(int(x) for x in exclude_me)

while True:
    candidate = random.randint(0, 999)
    if candidate not in excluded:
        result_int = candidate
        break

result = '{:03d}'.format(result_int)

rawDescription: Generating a random string of fixed length where certain values are prohibited


code:
import itertools
list(itertools.chain.from_iterable(
    [key] + list(flat(value)) for key, value in d.items()
))
# => ['AA', 'No Av', 'Ave', 3.35, 'Max', 0.9, 'Min', -6.8, 'analist disp:',
#     -5.0, u' AA: Jan 11, 2016\t\t\t']

rawDescription: How to flatten a "complex" dictionary into a list

description: Flatten a "complex" dictionary into a list


code:
this.s
import codecs
codecs.decode(this.s, 'rot13')

rawDescription: Attributes of Python module `this`

description: Attributes of Python module `this`


rawDescription: xpath selectors not returning a match

description: Xpath selectors not returning a match


code:
{ "_id" : 3, "greaterCount" : 2, "lesserCount" : 1, "zeroCount" : 0 }
{ "_id" : 2, "greaterCount" : 1, "lesserCount" : 0, "zeroCount" : 2 }
{ "_id" : 1, "greaterCount" : 1, "lesserCount" : 1, "zeroCount" : 0 }

rawDescription: Pymongo and Aggregation framework query

description: Pymongo and Aggregation framework query


rawDescription: Dot product of every element with every other element of an array


code: QtCore.QTimer.singleShot(1000, lambda: self.Box.append("Text2")) #1000 milliseconds = 1 second

rawDescription: Python, PySide sleep without stalling the whole program?


code:
def func(**kwargs):
    kwargs1, kwargs2 = partition_mapping(kwargs, ("arg1", "arg2", "arg3"))

rawDescription: Python: pass more than one keyword argument?


code:
customer_id = c_int()
dbbind(dbconn, 1, INTBIND, 0, byref(customer_id))

rawDescription: How to translate the cast of a memory address in C into python ctypes call?

description: Translate the cast of a memory address in C into python ctypes call


rawDescription: Adding multiple values to an existing dictionary as SETS


rawDescription: How can i get keys in a dictionaty in Python when a value is given?

description: Get keys in a dictionaty in Python when a value is given


code:
def createAdder(x):
    return lambda y: y + x
adders = [createAdder(i) for i in range(4)]

rawDescription: What do (lambda) function closures capture in Python?


code:
for line_num, (is_last, row) in enumerate(isLast(reader)):
    if not is_last: assert len(row) == len(header)

rawDescription: Have csv.reader tell when it is on the last line


code:
chardict = {}
for i,v in enumerate(characteristics):
    chardict[v] = i

rawDescription: Efficient way of marking which elements of a smaller list are in a larger list (Python)


code:
import random
y = random.randrange(2**64) # some 64-bit int
y
yt = y * 0.6
yt
yt - int(yt)

rawDescription: implementing custom hashing method

description: Implementing custom hashing method


code:
s = "something"
driver.execute_script("document.getElementsByName('redirect')[0].setAttribute('type', 'text');")
driver.find_element_by_name("redirect").send_keys(s)

rawDescription: Python SELENIUM issue

description: Python SELENIUM issue


code:
def my_any(iterable):
    for i in iterable:
        if i:
            return True
    return False

rawDescription: Checking for lists of empty values

description: Checking for lists of empty values


rawDescription: Python Sqlalchemy: Filter by datediff of months


code:
s = 'a|b|more b|yet more b|c|d|e|f'
a, *b, c, d, e, f = s.split('|')
b = '|'.join(b)

a,b,c,d,e,f

rawDescription: Chopping A Line From A Text Document Into Different Strings


code:
def connect_and_get_data(query, data):
    ...
    cursor.execute(query, data)
    ...

def get_data_about_first_amazing_topic(useful_string):
    query = "SELECT ... FROM ... WHERE ... AND some_field=%s"
    connect_and_get_data(query, ("one","two","three"))
    ...

rawDescription: Executing different queries using mysql-python


code:
if re.search(re.escape("Crude protein (min.)"),"Crude protein,protein,Protein,Protein    (crude),Crude protein (min.)") : print("ok")
...
ok

rawDescription: re.search : a lack of understanding through 2 exemples

description: Re.search : a lack of understanding through 2 exemples


code:
from copy import deepcopy
from collections import defaultdict

nodes = defaultdict(list)
for node in object_list:
    nodes[node.pred].append(node)

for ind, st_nodes in enumerate(starting_nodes):
    starting_nodes[ind].extend(deepcopy(nodes.get(st_nodes[0].id,[])))

rawDescription: How to compare two unequal lists and append matching elements value back to the first List

description: Compare two unequal lists and append matching elements value back to the first List


code:
class ExampleForm(forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.fields['mym2mfield'].queryset = Example.objects.filter(example_feeds__user=request.user)

rawDescription: forms.ModelForm Restrict to User Who Created the Model

description: Forms.ModelForm Restrict to User Who Created the Model


code:
nrows = 5
ncols = 5
mark = "X"
space = "_"
the_matrix = []

rawDescription: Drawing an X in a 2D array - Python

description: Drawing an X in a 2D array - Python


code:
setup = 'from __main__ import np, input_a, input_b'
print(timeit.timeit('input_b[input_b > input_a] = input_a', setup=setup))
# 2.2448947575996456
print(timeit.timeit('np.where(input_b < input_a, input_b, input_a)', setup=setup))
# 5.35540746395358

rawDescription: Getting the minimum from elements of a Numpy array and a float


code: data = np.matrix(data)

rawDescription: what is the efficient way to work with matrix in numpy

description: What is the efficient way to work with matrix in numpy


code:
import matplotlib.pyplot as plt
values = [[i.values[0,1], i.values[-1,1]] for i,j in zip(parts1, parts2)]
for value in values:
    plt.plot([0,1], value)

rawDescription: Pandas plotting lines from different columns ignoring values


code:
def mutate_dic(dic, country_name, field, new_data):
    dic[country_name][field] = new_data

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code: tkFont.Font(..., size=-20)

rawDescription: How to derive the font size from a height constraint?

description: Derive the font size from a height constraint


code:
def simple_list(request):
    queryset = Simple.objects.all()
    table = SimpleTable(queryset)
    return render_to_response("simple_list.html", {"table": table},
                              context_instance=RequestContext(request))

rawDescription: how to render a Queryset into a table template-django

description: Render a Queryset into a table template-django


code:
def test_1():
  obj = MyClass()
  # Mock something
  obj.run_loop()
  # Do your assertions

rawDescription: Mocking a variable in python

description: Mocking a variable in python


code:
from django.forms import ModelForm, HiddenInput
class GuideForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(GuideForm, self).__init__(*args, **kwargs)
        self.fields['date_modified'].widget = HiddenInput()

    class Meta:
        fields = ('name', 'sno', 'date_modified', )
        model = models.Guide

rawDescription: How to make django crispy form to hide a particular field?

description: Make django crispy form to hide a particular field


code:
proc = subprocess.Popen(['python',
    os.path.join(path, 'python_repeat_deckgen_remote.py'),
    '-m',
    module])

rawDescription: Issues with subprocess.Popen() replacing os.system()


code:
try: import winreg
except: import _winreg as winreg
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") as key:
    print(winreg.QueryValueEx(key, "EditionID")[0])

rawDescription: How to determine Windows Edition in Python with using Squish QT?

description: Determine Windows Edition in Python with using Squish QT


code: min(c for (a,b,c),(d,e,f) in your_list)

rawDescription: Return min/max of multidimensional in Python?


code:
for line in afile:
    if 'MyExpression' in line:
        # ...the number extraction, e.g with a regular expression, then:
        for nextline in afile:
            if 'MyExpression' in nextline or 'MyExpression2' in nextline:
                # the other number extraction, then
                break  # done with the inner loop

rawDescription: For loop when iterating over lines in a file?


code:
try:
    import threading
except ImportError:
    import dummy_threading as threading

rawDescription: Refresh decorator

description: Refresh decorator


code:
module = __import__(module_name)
clazz = None
for attribute_name in dir(module):
    attribute = getattr(module, attribute_name)
    if attribute_name.endswith('Bot') and callable(attribute):
        clazz = attribute
        break

rawDescription: How to extract classes out of Python modules?

description: Extract classes out of Python modules


code:
def draw_circle(t):
    t.forward(100)
    t.left(91)

rawDescription: How To create a shortcut for a command in python 3.3


code:
import itertools

def mult(fs):
    res = 1
    for f in fs:
        res *= f
    return res

def _generate_all_factorizations(factors):
    if len(factors) <= 1:
        yield factors
        return

    for factors_in_mult in xrange(1, len(factors)+1):
        for which_is in itertools.combinations(range(len(factors)), factors_in_mult):
            this_mult = mult(factors[i] for i in which_is)
            rest = [factors[i] for i in xrange(len(factors)) if i not in which_is]

            for remaining in _generate_all_factorizations(rest):
                yield [this_mult] + remaining

rawDescription: Algorithm to find ALL factorizations of an integer


code:
df1["nr_shares"] = df1.apply(lambda row: row["nr_shares"] * (-1 if row["transaction"] == "Sell" else 1), axis=1)
df1

rawDescription: Fill a Pandas dataframe using information from another Pandas dataframe


code:
from collections import defaultdict
data = defaultdict(list)
for line in inmap:
    k, v = (x.strip() for x in line.split('\t'))
    data[k].append(v)

rawDescription: Defining a list of values for a dictionary key using an external file


code:
from itertools import starmap
list(starmap('{}.{}.{}.{}:{}'.format,zip(*[iter(data)]*5)))

rawDescription: Concat every 4 strings from a list?

description: Concat every 4 strings from a list


code:
Stick = A(10, 20)
Stick.x
Stick.y
Stick.pos
Stick.pos = [5,10]
Stick.x
Stick.y
Stick.pos
Stick.pos[0] = 70
Stick.x
Stick.pos

rawDescription: properties that are lists, assigning to index

description: Properties that are lists, assigning to index


code:
for index, elem in enumerate(LONG_LIST):
 print >>outfile,"""

{0}
{1}
{2}

""".format(elem[0], elem[1], elem[2])

rawDescription: How to use String format to create HTML report

description: Use String format to create HTML report


rawDescription: How to remove specific strings from a list

description: Remove specific strings from a list


code:
class MyForm(django.forms.Form):
    tags = django.forms.CharField(required=True)

    def clean_tags(self):
        """Split the tags string on whitespace and return a list"""
        return self.cleaned_data['tags'].strip().split()

rawDescription: Django array value in a form

description: Django array value in a form


code:
mat_A = np.asarray(mat_A)
mat_B = np.asarray(mat_B)
mat_C = mat_A + mat_B
print(mat_C)

rawDescription: How can I add two elements of same indices of two 2D arrays in python?

description: Add two elements of same indices of two 2D arrays in python


code:
s.groupby(level=0).apply(lambda x: sum(x.iloc[1:]))
s.groupby(level=0).apply(lambda x: sum(x.iloc[1:])).sum()

rawDescription: Filter by rank of one index level in Pandas?


code:
def dX_dt(X, t):
    vals = dict(x=X[0], y=X[1], t=t)
    return [eq.evalf(subs=vals) for eq in systemOfEquations]

rawDescription: SymPy/SciPy: solving a system of ordinary differential equations with different variables


rawDescription: Using regex for mutliple lines

description: Using regex for mutliple lines


code:
content ="'Yoda' :"
content = re.sub("\w\s*'\s*[^:]$", "", content)
print (content)

rawDescription: python regex not ending with some characters

description: Python regex not ending with some characters


code:
cherrypy.config.update(
    {'server.socket_host': '0.0.0.0'} )
cherrypy.quickstart()

rawDescription: Python (CherryPy) web app deployed locally, but not visible over intranet


code:
midx = (np.max(events['x'])+np.min(events['x']))//2
midy = (np.max(events['y'])+np.min(events['y']))//2

rawDescription: Efficiently get midpoint of image in Python with astropy


rawDescription: Python, how to compare substrings?

description: Python, how to compare substrings


code:
...
testValues = [ genName() for i in range(20) ]
testValues = sorted(testValues)
xx = widgets.DropdownWidget(values=testValues)
...

rawDescription: Sorting the values within a dropdown widget in ipython notebook


code: result = [(b, aud[tuple(b[:3])]) for b in B if tuple(b[:3]) in aud]

rawDescription: python union of 2 nested lists with index

description: Python union of 2 nested lists with index


code:
# Build a key->None dict for all `mm`
d = dict.fromkeys(mm)
# Update `None` values with last index using a gen-exp instead of dict-comp
d.update((v,k) for k,v in enumerate(ll) if v in d)
# {499: None, 501: 3, 502: 5}

rawDescription: Find last occurrence of any item of one list in another list in python


code: dir(f)

rawDescription: Is a Python function stored as an object?


code:
@app.task()
def add(x, y):
    time.sleep(10)
    return x + y

@app.task()
def parent():
    print('start')
    group(add.s(i, i) for i in xrange(100))()
    print('stop')

rawDescription: What is the life cycle of celery's parent tasks?


code:
def words(f):
    for line in f:
        for word in line.split():
            yield word

rawDescription: Anyway to input next string from a file in python


code:
#!/usr/bin/env python3
import wave

with wave.open('ecg.wav') as wavfile, open('ecg.mit16', 'wb') as output_file:
    assert wavfile.getnchannels() == 1 # mono
    assert wavfile.getsampwidth() == 2 # 16bit
    while True:
        data = wavfile.readframes(4096)
        if not data:
            break
        output_file.write(data)

rawDescription: Floating point to 16 bit Twos Complement Binary, Python


code:
stats = item['stats']
print(stats['championsKilled'])

rawDescription: How to read data from Json in Python

description: Read data from Json in Python


code:
#!/usr/bin/env python

# Here is the original globals() dict
print(globals())
# {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None}

var={'x':'Howdy'}
globals().update(var)

# Now the globals() dict contains both var and 'x'
print(globals())
# {'var': {'x': 'Howdy'}, 'x': 'Howdy', '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None}

# Lo and behold, you've defined x without saying x='Howdy' !
print(x)
Howdy

rawDescription: Python: Difference between 'global' & globals().update(var)


code:
proc = subprocess.Popen([cmd1, cmd2], stdout=subprocess.PIPE, cwd=path)
for ln in proc.stdout:
    process(ln)

rawDescription: Need to make Subprocess communication better


code:
a = rdpcap('/tmp/tmp.pcap')
for A in a:
    print('%.6f' % A.time)

rawDescription: Higher timestamp precision with scapy

description: Higher timestamp precision with scapy


rawDescription: How do I append to the correct deeply-nested list?

description: Append to the correct deeply-nested list