code: "b" in Foo.__dict__.values()

rawDescription: Checking if a variable belongs to a class in python


code: expected_row = get_expected_rows(**row)

rawDescription: Python unpacking list value in kwargs

description: Python unpacking list value in kwargs


rawDescription: Using sqlalchemy to create an index on a json key (expression index)


code:
import Crypto.Random
from Crypto.Cipher import AES
import hashlib

rawDescription: Encrypt / decrypt data in python with salt


code:
if name is not None and ent is not None and col is not None:
    value.setdefault(name, []).append({ent: col})

rawDescription: Adding multiple dictionaries to a key in python dictionary


code:
import win32com.client
xlPasteFormats                 = -4122
xlPasteSpecialOperationNone    = -4142
excelInstance = win32com.client.gencache.EnsureDispatch ("Excel.Application")
workbook = excelInstance.Workbooks.Item(1)
worksheet = workbook.Worksheets(1)
worksheet2 = workbook.Worksheets(3)
cells1 = worksheet.UsedRange
cells2 = worksheet2.UsedRange
cells1.Copy()
cells2.PasteSpecial(xlPasteFormats, xlPasteSpecialOperationNone)

rawDescription: How Do I Use Excel's Format Painter Across a Whole Workbook


code:
first_number = int(raw_input("Enter your first number: "))
second_number = int(raw_input("Enter your second number: "))

rawDescription: My 'lowest common multiple' program hangs, and doesn't output an answer


rawDescription: Python float decimal places

description: Python float decimal places


code: xy = np.vstack([[xmin, 0], xy, [xmax, 0], [xmin, 0]])

rawDescription: python area chart with gradient color between the line and y=0

description: Python area chart with gradient color between the line and y=0


code:
def giveMeSomeRows(group):
    return random.uniform(low=group.low, high=group.high, size=N)

results = x.groupby(['farm', 'fruit']).apply(giveMeSomeRows)

rawDescription: How do I convert a row from a pandas DataFrame from a Series back to a DataFrame?

description: Convert a row from a pandas DataFrame from a Series back to a DataFrame


code:
def myindex(lst, target):
    for index, item in enumerate(lst):
        if item == target:
            return [index]
        if isinstance(item, (list, tuple)):
            path = myindex(item, target)
            if path:
                return [index] + path
    return []

rawDescription: Find index of nested item in python

description: Find index of nested item in python


rawDescription: Create a list that follows a certain creation pattern


rawDescription: how to enter in to a folder through python code on linux

description: Enter in to a folder through python code on linux


code:
for time in itertime(start_time, end_time, step=5 * 60):
     ...

rawDescription: Python datetime

description: Python datetime


code:
user = User.all().filter('name =', 'John').filter('password =', '1234').get()
if user:
    user.name = 'Marcus'
    user.put()

rawDescription: Google App Engine Datastore delete entity by properties


code:
import __builtin__
__builtin__.rubbish= 3
rubbish

rawDescription: Python Superglobal?

description: Python Superglobal


code:
self.lamps = [self.lamp_1, self.lamp_2, self.lamp_3, self.lamp_4]
for lamp in self.lamps:
    self.canvas.itemconfig(lamp, fill=self.color_blink)

rawDescription: substring variable name python

description: Substring variable name python


rawDescription: how to preserve pandas dataframe identity when extracting a single row

description: Preserve pandas dataframe identity when extracting a single row


code: (self.list[L][0] == operand.list[R][0]) and (op != div or operand.list[R][1] != 0)

rawDescription: How to do this conditional statement?

description: Do this conditional statement


code: "It was when [... ] the cosmos...Forevermore..."

rawDescription: Proper parsing of a html-page with escaped ascii-strings


code: global_dict["foo"] = 2

rawDescription: Using a global dictionary with threads in Python


code:
net_SO = NeuralNet(
    layers=[(layers.InputLayer, {"name": 'input', 'shape': (None, 1, 28, 28)}),
            (layers.Conv2DLayer, {"name": 'conv1', 'filter_size': (3,3,), 'num_filters': 5}),
            (layers.DropoutLayer, {'name': 'dropout1', 'p': 0.2}),
            (layers.DenseLayer, {"name": 'hidden1', 'num_units': 50}),
            (layers.DropoutLayer, {'name': 'dropout2', 'p': 0.2}),
            (layers.DenseLayer, {"name": 'output', 'nonlinearity': nonlinearities.softmax, 'num_units': 10})],
    # optimization method:
    update=nesterov_momentum,
    update_learning_rate=10**(-2),
    update_momentum=0.9,

    regression=False,
    max_epochs=200,
    verbose=1,

    on_epoch_finished=[PlotLosses(figsize=(8,6))], #this is the important line
    )

net_SO.fit(X, y) #X and y from the MNIST dataset

rawDescription: Live plot losses while training neural net in Theano/lasagne


code:
from flask.ext.admin.contrib.sqla import ModelView

admin.add_view(ModelView(MyModel, db.session, 'Menu Text'))

rawDescription: Flask-Admin : Customize table name for the admin interface


code:
def parse_4digit_number(s):
    i = int(s)
    if 0 <= i <= 9999:
        return i
    else:
        raise ValueError("{0} is out of range".format(i))

rawDescription: Regex to match a range number of digits from a string representin an integer number?


code:
targets = ["Contact", "Purpose", "Email"]
results = {}

rawDescription: Extract data from a site using python

description: Extract data from a site using python


code:
from itertools import cycle

input1 = input("Enter word: ")
input2 = "goodbye"
for x, y in zip(cycle(input1), input2):
    total = ord(x) + ord(y)
    print(total)

rawDescription: Adding 2 ascii converted characters using nested loops in Python 3.2


code:
def initUI(self):

    self.widgetPanel=wx.Panel(self, -1)
    self.widgetPanel.SetBackgroundColour('white')

    # Buttons for play the simulation
    playButton = wx.Button(self.widgetPanel, -1, "Play", pos=(10,10), size=(30,30))

    self.Bind(wx.EVT_BUTTON, self.play, playButton)
    playButton.SetDefault()
    self.sT = wx.StaticText(self,-1,"",size=(20,20))
    self.timer = wx.Timer()
    self.timer.Bind(wx.EVT_TIMER,self.run_st)
def play(self, event):
    self.timer.Start(1000)

def run_st(self,timerEvent):
    global i
    i = (i+1)%4
    self.sT.SetLabel("1")
    self.sT.SetPosition(pos_st[i])

rawDescription: wxPython moving widgets

description: WxPython moving widgets


code:
df.loc[df['solvent'] == 'NONANE', 'num'] = 9
df.loc[df['solvent'] == 'OCTANE', 'num'] = 8

rawDescription: Setting column equal to value depending on another column pandas


code:
myCoord = [1,2]
someCoords1 = [[2,3], [4,5], [1,2], [6,7]]
someCoords2 = [[2,3], [4,5], [8,9], [6,7]]
myCoord in someCoords1 or myCoord in someCoords2

rawDescription: identify x,y coordinate pair in a python x,y array

description: Identify x,y coordinate pair in a python x,y array


code:
md5 = hashlib.md5('2005-05-26-10458.68').hexdigest()     # get MD5 as hex string
float.fromhex('0.' + md5[:16])                           # first half as float
float.fromhex('0.' + md5[16:])                           # second half as float

rawDescription: Converting a number string into MD5 with python


code:
payload = [
    ('fname', 'homer'), ('lname', 'simpson'),
    ('favefood', 'raw donuts'), ('favefood', 'free donuts'),
]
rtt = requests.post("http://httpbin.org/post", data=payload)

rawDescription: handling duplicate keys in HTTP post in order to specify multiple values

description: Handling duplicate keys in HTTP post in order to specify multiple values


rawDescription: concatenating two multidimensional arrays in numpy

description: Concatenating two multidimensional arrays in numpy


code:
class UserProfile(models.Model):
    user = models.ForeignKey(User, primary_key=True)
    quote = models.CharField('Favorite quote', max_length =  200)

rawDescription: How can I extend a user profile in django?

description: Extend a user profile in django


code:
res.to_frame(name='ABC')  # ''.join(cols)
res.to_frame(name='ABC').to_csv('new.csv')

rawDescription: Python - Combining Columns in a CSV file


code:
class SharedValue(object):
    def __init__(self, val):
        self.value = val

class Lock():
    def __init___(self, locked = True):
        self.attributes = {'locked': SharedValue(locked)}

    def toggleLock():
        self.attributes['locked'].value = not self.attributes['locked'].value

class Door():
    def __init__(self, locked = False):
        if not isinstance(locked, SharedValue):
            locked = SharedValue(locked)
        self.attributes = {'locked': locked}

rawDescription: How do I set a value of a dictionary to a reference to a value of another dictionary?

description: Set a value of a dictionary to a reference to a value of another dictionary


code:
class FileLineWrapper(object):
    def __init__(self, f):
        self.f = f
        self.line = 0
    def close(self):
        return self.f.close()
    def readline(self):
        self.line += 1
        return self.f.readline()

rawDescription: Is there an easy way to tell which line number a file pointer is on?


code:
from django.db import transaction

class Group(models.model):
    # your fields
    img_count = models.IntegerField()

    @transaction.atomic
    def next_sku(self):
        self.img_count += 1
        self.save()
        return self.img_count

class Photo(models.Model):
    # your fields
    category_auto_key = models.IntegerField(editable=False)

    def category_image(self):
        return self.group.abbv+"-"+str(self.category_auto_key)

    def save(self, *args, **kwargs):
        if not self.category_auto_key:
            self.category_auto_key = self.group.next_sku()
        super(Photo, self).save(*args, **kwargs)

rawDescription: Auto Incrementing natural keys with django / postgres


code:
from __future__ import division

import os
os.chdir(os.path.expanduser('~/tmp'))

import numpy as np
import scipy.optimize as optimize
import matplotlib.pyplot as plt

def func(x,a,b,c):
   return a*np.exp(-b*x)-c

xData = np.load('xData.npy')*10**5
yData = np.load('yData.npy')*10**5

print(xData.min(), xData.max())
print(yData.min(), yData.max())

trialX = np.linspace(xData[0], xData[-1], 1000)

# Fit a polynomial
fitted = np.polyfit(xData, yData, 10)[::-1]
y = np.zeros(len(trialX))
for i in range(len(fitted)):
   y += fitted[i]*trialX**i

# Fit an exponential
popt, pcov = optimize.curve_fit(func, xData, yData)
print(popt)
yEXP = func(trialX, *popt)

plt.figure()
plt.plot(xData, yData, label='Data', marker='o')
plt.plot(trialX, yEXP, 'r-',ls='--', label="Exp Fit")
plt.plot(trialX, y, label = '10 Deg Poly')
plt.legend()
plt.show()

rawDescription: Why does scipy.optimize.curve_fit not fit to the data?


rawDescription: pandas python - round() not behaving correctly

description: Pandas python - round() not behaving correctly


code: val_if_true if condition else val_if_false

rawDescription: single line if statement - Python

description: Single line if statement - Python


code: b = bytes('abcd', 'ascii')

rawDescription: How to XOR literal with a string

description: XOR literal with a string


code: number = int(number.lstrip())

rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


Metric: true

Severity: warn

Event: false

Group: UndefinedGroup

Message: Hello World

HEADER.connection: Keep-Alive

rawDescription: Two JSON douments linked by a key

description: Two JSON douments linked by a key


code:
def main(global_config, **settings):
    try:
        settings['sqlalchemy.connect_args'] = eval(settings['sqlalchemy.connect_args'])
    except KeyError:
        settings['sqlalchemy.connect_args'] = {}
    engine = engine_from_config(settings, 'sqlalchemy.')
    # rest of code..

rawDescription: How to pass secure_auth to MySQL login via SQLalchemy

description: Pass secure_auth to MySQL login via SQLalchemy


code:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'v7j%&)-4$(p&tn1izbm0&#owgxu@w#%!*xn&f^^)+o98jxprbe'
INSTALLED_APPS = ['modeltest']
ROOT_URLCONF = 'BarebonesTest.urls'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

rawDescription: What minimal files i need to use django ORM


code:
class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

class Fox(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

def print_age(IdOrObj):
    # This will fail if passed a Fox
    myObj = Person.objects.get(pk=IdOrObj) if isinstance(IdOrObj, int) else IdOrObj
    print('%s is %s years old' % (myObj.name, myObj.age))

rawDescription: Is it good practice to allow multiple types of argument in python


code:
import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

find('*.txt', '/path/to/dir')

rawDescription: Find a file in python

description: Find a file in python


code: [float(n.split()[3]) for n in lines if n[:4]=="ATOM"]  #or n.startswith("ATOM") instead of n[:4]=="ATOM"

rawDescription: How to generate an array/list from an output using .split() in Python 2.6

description: Generate an array/list from an output using .split() in Python 2.6


code:
os.path.splitext(os.path.basename('a.b.c'))[0] + '.new'
os.path.basename('a.b.c').split('.')[0] + ".new"

rawDescription: Python-Which command is better for changing the file extension?


code:
import re
re.search(r'Phone:\s*(\d+\.\d+)', 'Phone: 3396222') is None
re.search(r'Phone:\s*(\d+\.\d+)', 'Phone: 339.6222').group(1)

rawDescription: why this regular expression returns empty

description: Why this regular expression returns empty


code: self.canvas["object_colour"] = (1., )*4  # colour tuple here

rawDescription: Passing variables to GLSL in Kivy

description: Passing variables to GLSL in Kivy


code:
print(repr(astr))
# u'e\u0301'
print(repr(combined_astr))
# u'\xe9'

rawDescription: Precompose Unicode Character Sequences in Python


rawDescription: How to gracefully stop python unittest?

description: Gracefully stop python unittest


code:
from collections import defaultdict
def Counter(x):
    d = defaultdict(int)
    for v in x: d[v]+=1
    return d

rawDescription: Python list sort by size of group

description: Python list sort by size of group


rawDescription: Python: creating customer sort method & loop stops before list sorted


code: dir, file = os.path.split('foo/bar/baz.txt')

rawDescription: Python Fileconveyor Naming Issues

description: Python Fileconveyor Naming Issues


code: print( re.findall( "link: '([^']+)'", myDoc ) )

rawDescription: Regular expression for string between two strings?


code:
import requests
import bs4     # the 'beautifulsoup4' module
import pickle

# find an 'all the countries' listing
url = "http://www.nationsonline.org/oneworld/countries_of_the_world.htm"
r   = requests.get(url)
bs  = bs4.BeautifulSoup(r.text)

# grab all table rows
rows = [
    [cell.text.strip() for cell in row.findAll('td')]
    for row in bs.findAll('tr')
]
# filter for just the rows containing country-name data
rows = [row[1:] for row in rows if len(row) == 4]

# create a look-up table
country = {}
for en,fr,lo in rows:
    country[en] = en
    country[fr] = en
    country[lo] = en

# and store it for later use
with open('country.dat', 'wb') as outf:
    pickle.dump(country, outf)

rawDescription: Compare CSV files and print results using Python


code:
t = 'WHQ'
set(t)
set([t])

rawDescription: Is that a tag list or something else?

description: Is that a tag list or something else


code:
from decimal import *
d = Decimal(58106601358565889).sqrt()
print(d == int(d))

rawDescription: Distinguishing large integers from near integers in python


code:
if settings.ADMIN_ENABLED:
    urlpatterns += patterns('',
        (r'^admin/(.*)', include(admin.site.urls)),
        # ..maybe other stuff you want to be dev-only, etc...
        )

rawDescription: How can I disable Django's admin in a deployed project, but keep it for local development?

description: Disable Django's admin in a deployed project, but keep it for local development


code:
def recursive_rnd_sum_by_n_with_min(_sum=356, _num=3, _min=31):
    def f(_sel=[]):
        left = _num - len(_sel)
        so_far = sum(_sel)
        if left == 1:
            return _sel + [_sum - so_far]
        return f(_sel + [random.randint(_min, _sum - so_far - left * _min)])
    return f()

rawDescription: randomly select 3 numbers whose sum is 356 and each of these 3 is more than 30

description: Randomly select 3 numbers whose sum is 356 and each of these 3 is more than 30


code: words_par.startswith("P1" or "P2" or "P3") & words_par.endswith("P1" or "P2" or "P3")

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.model = QtGui.QStandardItemModel()
        self.view = QtGui.QTreeView()
        self.view.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.view.setModel(self.model)
        self.setCentralWidget(self.view)
        parent = self.model.invisibleRootItem()
        for item in 'One Two Three Four'.split():
            parent.appendRow([
                QtGui.QStandardItem(item),
                QtGui.QStandardItem(),
                QtGui.QStandardItem(),
                ])
        self.view.setColumnWidth(0, 800)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: How do you set the column width on a QTreeView?

description: Set the column width on a QTreeView


rawDescription: Count Number of Rows Between Two Dates BY ID in a Pandas GroupBy Dataframe


code:
import lxml.html

url = 'http://kmbsapps.konicaminolta.us/wheretobuy/main_search.jspx?productCategory=Office+Systems&sl_zip='

with open('1.txt') as f:
    for line in f:
        cod = line.strip()
        tree = lxml.html.parse(url+cod)
        name = tree.xpath('//tr/td/span[@class="largecol"]/text()')
        address = tree.xpath('//tr/td/span[@class="smallcol"]/text()')
        name = [n for n in name if n.strip()]
        for n, a in zip(name, address):
            print(n, a)

rawDescription: please help me in lxml

description: Please help me in lxml


code:
@app.route('/archive')
def display_archive():
    p = db.session.query(Post.pub_date).all()
    d = defaultdict(list)
    for i in p:
        d[i.pub_date.year].append(i.pub_date.month)

    # add the monthly counts by counting the instances of month number.
    adict = {}
    for k, v  in d.items():
        adict[k] = Counter(v)

    bdict = {}
    # add the monthly and yearly totals counts
    posttotal = 0
    for key, value in adict.iteritems():
        yearsum = 0
        for m, c in value.items():
            yearsum += c
            posttotal += c
            bdict[key] = yearsum

    d = defaultdict(list)
    for k, v in adict.items() + bdict.items():
        d[k].append(v)

    return render_template('archive.html', d=d)

rawDescription: Creating An Archive List For A Blog

description: Creating An Archive List For A Blog


code:
for subdict in dictionary.values():
    for key, val in subdict.items():
        if key.startswith('option-'):
            del subdict[key]
            subdict[' '.join(key.split('-', 1))] = val

rawDescription: Change name of keys in New_dictionary where New_dictionary as value of Main_dictionary


code: "SELECT * FROM my_table WHERE id=%s" % str(id)

rawDescription: Python sqlite3 string formatting

description: Python sqlite3 string formatting


code: board = [[(0,0)]*lines for _ in range(columns)]

rawDescription: Change values of a list of list (of tuples) in a for statement


code:
def fetchlines(line=None):
    if line is not None:
        # As long as we are called with a line
        # store the line in the array we added to this function
        fetchlines.lines.append(line)
    else:
        # When we are called without a line
        # we are retrieving the lines
        # Truncate the array after copying it
        # so we can re-use this function
        lines = fetchlines.lines[:]
        fetchlines.lines = []
        return lines

fetchlines.lines = []

@app.route("/")
def hello():
    ftp = FTP("someaddress")
    ftp.login()
    ftp.dir(fetchlines)
    lines = fetchlines()
    return "<br>".join(lines)

rawDescription: flask+ftplib basic application

description: Flask+ftplib basic application


code: test1=Test1(windows, data, axes)

rawDescription: How to replace previous plots in a matplotlib figure with new plots or grid of plots?

description: Replace previous plots in a matplotlib figure with new plots or grid of plots


rawDescription: Counting change of value in irregular time series data


rawDescription: Understanding performance difference

description: Understanding performance difference


code:
from functools import wraps

def another_lower_level_decorator(func):
    @wraps( func )
    def wrapped(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapped

def some_abstract_decorator(func):
    @wraps(func)
    @another_lower_level_decorator
    def wrapper(*args, **kwargs):
        # ... details omitted
        return func(*args, **kwargs)
    return wrapper

@some_abstract_decorator
def test():
    """ This is a docstring that should be on the decorated function """
    pass

help(test)

rawDescription: Python - correct order of the application of decorators


code:
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
             "Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben",
             "Audrey","Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]

count = 0
for student1 in math_students:     #change this to student1
    for student2 in cs_students:   #change this to student2
        if student1 ==student2:    #check if student1 is equal to student 2
            count +=1
            print("Student:", student2, "is enrolled in both classes") #print student2
print(count, "Students are enrolled in Computer Science and Maths")

rawDescription: Nested loops to determine students in two classes (both)


code:
with open(fname, 'rb') as fh:
    first = next(fh).decode()

    fh.seek(-1024, 2)
    last = fh.readlines()[-1].decode()

rawDescription: What is the most efficient way to get first and last line of a text file?


code:
null
null
null

rawDescription: Python Multiple variables has one Value

description: Python Multiple variables has one Value


code:
if condition:
    import matplotlib as mlib
else:
    import modifiedmatplotlib as mlib

rawDescription: Conditional import in a module

description: Conditional import in a module


rawDescription: FileNotFoundError when creating a file using a variable in Python 3.5.1


code: proc = subprocess.Popen(['cat', 'myfile'], stdout = subprocess.PIPE)

rawDescription: How do you execute a terminal command and then repeatedly check and store the response in Python?

description: Execute a terminal command and then repeatedly check and store the response in Python


code:
with open("foo.txt", "r") as fo:
    with open("out.txt", "w") as foo:
        foo.write(fo.read())

rawDescription: Reading/Writing to a file in Python

description: Reading/Writing to a file in Python


code:
xyz2.py
import argparse

parser = argparse.ArgumentParser(description="XYZ2 args", add_help=False)
parser.add_argument("-xyz2-lizard", action='store_true')
parser.add_argument("-xyz2-spock", action='store_true')

rawDescription: How to specify multiple instances of same type of parent parser in argparse

description: Specify multiple instances of same type of parent parser in argparse


code:
from collections import Counter
def book_index(alice):
    worddict = Counter()
    for ln in alice:
        worddict.update(ln.split())
    return worddict

rawDescription: How to turn a dictionary "inside-out"

description: Turn a dictionary "inside-out"


rawDescription: Scipy: Do sparse matrices support advanced indexing?


code:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

rawDescription: How can i get a log system similar with appengine(GAE) in django?

description: Get a log system similar with appengine(GAE) in django


code:
def setUp(self):
    """
    Initializes the test client and logs it in.
    """
    password = 'secret'
    self.user = create_user(password=password)
    self.logged_in = self.client.login(username=self.user.username, password=password)

rawDescription: Django test client does not log in

description: Django test client does not log in


code:
import sys
import pandas as pd

# Simulation of return values from the calls
calls = [
    [
        {u'dateTime': u'2011-03-28', u'value': u'2298'},
        {u'dateTime': u'2011-03-29', u'value': u'2322'},
        {u'dateTime': u'2011-03-30', u'value': u'2309'},
    ],
    [
        {u'dateTime': u'2011-03-28', u'value': u'28'},
        {u'dateTime': u'2011-03-29', u'value': u'22'},
        {u'dateTime': u'2011-03-30', u'value': u'09'},
    ]
]

# Create an initial empty data frame
df = pd.DataFrame()
# Make the consecutive calls
for i, call in enumerate(calls):
    # Create the new DataFrame from the data you got
    df_new = pd.DataFrame(call).set_index('dateTime')
    # Rebane the column to avoid collision
    df_new.rename(columns={'value': 'value_%s' % i}, inplace=True)
    # Merge it with the current data frame
    df = pd.concat([df, df_new], axis=1)
# Save data to file (I'm using here the sys.stdout, just
# to print it to console.
df.to_csv(sys.stdout, header=None)

rawDescription: How do I build a CSV with data returned from multiple API calls in Python?

description: Build a CSV with data returned from multiple API calls in Python


rawDescription: merge two tuples with same key

description: Merge two tuples with same key


code: s = set(u"rabbit", u"lamb", u"calf")

rawDescription: Fastest possible dictionary-like matching


code:
def method_of(instance):
    def method_adder(function):
        setattr(instance, function.__name__, function.__get__(instance))
        return function
    return method_adder

@method_of(a)
def new_func(self, arg1, arg2):
    stuff()

rawDescription: Assigning method to object at runtime in Python


rawDescription: Java: Equivalent of Python's range(int, int)?


rawDescription: python quickest way to merge dictionaries based on key match

description: Python quickest way to merge dictionaries based on key match


code: output = array.size - np.searchsorted(np.sort(array), array, side='right')

rawDescription: Efficient way to count the greater than operation for each value itself


rawDescription: Given a list of Tuples, return a new list of the first values of the tuples


rawDescription: Replace parts of string that occur within a list


code: month = [[day[0] for day in week] for week in month]

rawDescription: Cannot change content of list within list. Can anybody explain why?


code: f.bar = 43

rawDescription: How to protect class attributes in Python?

description: Protect class attributes in Python


rawDescription: Shortest distance between one point and a group of others?


code:
from itertools import product, islice

def dashed_combos(inputstring):
    words = inputstring.split()
    for combo in islice(product(' -', repeat=len(words) - 1), 1, None):
        yield ''.join(w for pair in zip(words, combo + ('',)) for w in pair)

rawDescription: Python replace spaces in string iteratively


code:
sample = 'Sunshine makes me happy, on a cloudy day'
sample[::2].upper()
sample[1::2].lower()

rawDescription: Having trouble with whitespace and strings in a function


code:
class groupby(object):
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def next(self):
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey))
    def _grouper(self, tgtkey):  # This is the "group" iterator
        while self.currkey == tgtkey:  # self.currkey != tgtkey if you advance groupby and then try to use this object.
            yield self.currvalue
            self.currvalue = next(self.it)
            self.currkey = self.keyfunc(self.currvalue)

rawDescription: Python groupby behaves strangely

description: Python groupby behaves strangely


code:
from operator import itemgetter

multiple_index = map(itemgetter(0, 3, 4), L)

rawDescription: Python list comprehension with multiple variables


code:
['cheesecake', 'pudding']
['pudding', 'bread']

rawDescription: How to select only integers in a list of strings/integers?

description: Select only integers in a list of strings/integers


code:
text = "don\u2019t think"
textencode = text.split(" ")
textencode

rawDescription: Encode ASCII text

description: Encode ASCII text


code:
import numpy as np
n, m = 3, 5
x = np.arange(n*m).reshape(n,m)
y = np.arange(m)[None,...]
x.shape
y.shape
(x-y).shape
x
y
x-y

rawDescription: Euclidean distances between several images and one base image


code:
import math
# draw the circle
for angle in range(0, 360, 5):
    x = r * math.sin(math.radians(angle)) + a
    y = r * math.cos(math.radians(angle)) + b
    map_[int(round(y))][int(round(x))] = '#'

rawDescription: How can I draw a circle in a data array/map in python

description: Draw a circle in a data array/map in python


code:
slicer = tuple(slice(0, i, 1) for i in index)
result = A[slicer]

rawDescription: Getting a slice of a numpy ndarray (for arbitary dimensions)


code:
# coding: utf-8

with open('status.txt') as f:
    tco = f.read()

import re
re.compile("(?P<key>\w+)=(?P<value>\w+)")
expre = re.compile("(?P<key>\w+)=(?P<value>\w+)")
pairs = dict(re.findall(expre, tco))

rawDescription: Loading `status` objects from File?

description: Loading `status` objects from File


code:
for c in cities :
    c.retrieveTemps()
    long, lat = c.long, c.lat
    x, y = map(float(long), float(lat))
    if c.high0 >= 34:
        plt.text(x, y, c.high0, fontsize=7, fontweight='bold')

rawDescription: Using plt.text to only plot data that meets a certain criteria


code:
a, b, *c = 1, 2, 3
c = c[0] if c else 2
a
b
c
a, b, *c = 1, 2
c = c[0] if c else 2
a
b
c

rawDescription: Default value in Python unpacking

description: Default value in Python unpacking


code:
import requests
from bs4 import BeautifulSoup
from collections import Counter
urls = ["http://en.wikipedia.org/wiki/Wolfgang_Amadeus_Mozart","http://en.wikipedia.org/wiki/Golf"]

with open('thisisanew.txt', 'w', encoding='utf-8') as outfile:
    for url in urls:
        website = requests.get(url)
        soup = BeautifulSoup(website.content)
        text = [''.join(s.findAll(text=True))for s in soup.findAll('p')]
        for item in text:
            print(item, file=outfile)

rawDescription: Scrape websites and export only the visible text to a text document Python 3 (Beautiful Soup)


code:
for values in stripped_header:
    volume_axis += [int(values)] * 100

rawDescription: Python - creating patterned lists

description: Python - creating patterned lists


code:
def remainder(a,b):
    return a if a < b else remainder(a-b, b)

rawDescription: how to compute a%b recursively?

description: Compute a%b recursively


rawDescription: How to process sub-lists separately?

description: Process sub-lists separately


code:
DF = DF.set_index(['COL1', 'year']).update(DF2.set_index(['ColX', 'ColY']))
DF.reset_index(inplace=True)

rawDescription: Python pandas conditional replace string based on column values


code: treats = sorted(init_treats)

rawDescription: Loop through multiple different sized python dictionaries


code:
val_size = map(lambda q: q.shape[0], pts)
vals = np.zeros( val_size )

# make an arbitrary function to test:
func = lambda pt: (pt**2).sum()

# collect func's values at grid pts
for i in range(pts[0].shape[0]):
    for j in range(pts[1].shape[0]):
        for k in range(pts[2].shape[0]):
            vals[i,j,k] = func(np.array([pts[0][i], pts[1][j], pts[2][k]]))

rawDescription: Correct usage of scipy.interpolate.RegularGridInterpolator


rawDescription: re.findall not returning a match

description: Re.findall not returning a match


code:
class BaseClass:
    pass
class ClassA(BaseClass):
    pass
class ClassB(BaseClass):
    pass
BaseClass.__subclasses__()
tuple((x,) for x in BaseClass.__subclasses__())

rawDescription: How to retrieve subclasses as tuple of tuple

description: Retrieve subclasses as tuple of tuple


code:
def time_range(start, end, duration):
    dt = start
    while dt < end: #note: `end` is not included in the range
        yield dt
        dt += duration

rawDescription: Difference between two time intervals in series


code:
drop = set(drop)

filtered = [d for d in data if not drop.intersection(d[1].split())]

rawDescription: Filtering a list based on another list

description: Filtering a list based on another list


rawDescription: How to assign a string from a list in python

description: Assign a string from a list in python


code:
if end.casefold() == "end":
    ...

rawDescription: How can I make it so the user can input different answers but display the same result?

description: Make it so the user can input different answers but display the same result


code: valid = re.match('[1-5]$', UserInput)

rawDescription: Input validation with the `re` library

description: Input validation with the `re` library


code:
def skip(app, what, name, obj, skip, options):
    if name == "__init__":
        return False
    return skip

def setup(app):
    app.connect("autodoc-skip-member", skip)

rawDescription: How to use Sphinx's autodoc to document a class's __init__(self) method?

description: Use Sphinx's autodoc to document a class's __init__(self) method


code:
df[0].str.extract("for (\d+)")
df[0].str.extract("for (\d+) yards")

rawDescription: Extract a certain part of a string after a key phrase using pandas?


code:
last3 = []
for h in model.history.all:
   if len(last3) > 2:
       del last3[0]
   last3.append[h]

rawDescription: Second to last item in django-simple-history


code: a.reshape((4, 2))

rawDescription: Numpy: efficient way to generate combinations from given ranges


rawDescription: Generating random numbers with weighted probabilities in python


rawDescription: pandas get rows which are NOT in other dataframe

description: Pandas get rows which are NOT in other dataframe


code:
for drive in drives:
    filepath = find_file(target, drive)
    if filepath is not None:
        break

rawDescription: Search all drives for a file

description: Search all drives for a file


code: file = open(srcfile, 'wb')

rawDescription: Python code to move file over socket

description: Python code to move file over socket


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

def main():
    x = np.array([0, 0, 2, 2])
    y = np.array([0, 2, 0, 2])
    a = np.array([23.4, 23.7, 23.4, 23.7])
    xi, yi = np.mgrid[x.min():x.max():500j, y.min():y.max():500j]

    a_orig = normal_interp(x, y, a, xi, yi)
    a_rescale = rescaled_interp(x, y, a, xi, yi)

    plot(x, y, a, a_orig, 'Not Rescaled')
    plot(x, y, a, a_rescale, 'Rescaled')
    plt.show()

def normal_interp(x, y, a, xi, yi):
    rbf = scipy.interpolate.Rbf(x, y, a)
    ai = rbf(xi, yi)
    return ai

def rescaled_interp(x, y, a, xi, yi):
    a_rescaled = (a - a.min()) / a.ptp()
    ai = normal_interp(x, y, a_rescaled, xi, yi)
    ai = a.ptp() * ai + a.min()
    return ai

def plot(x, y, a, ai, title):
    fig, ax = plt.subplots()

    im = ax.imshow(ai.T, origin='lower',
                   extent=[x.min(), x.max(), y.min(), y.max()])
    ax.scatter(x, y, c=a)

    ax.set(xlabel='X', ylabel='Y', title=title)
    fig.colorbar(im)

main()

rawDescription: Matplotlib 2D graph with interpolation

description: Matplotlib 2D graph with interpolation


code:
x = 1
y = 3
z = None
d = {k:v for k,v in locals().items() if v is not None and not k.startswith('__')}
d

rawDescription: Dictionary from variables that may not be initialized


code:
x.shape
y.shape
y[i].shape

rawDescription: plot single row of 2d numpy array against 1d list

description: Plot single row of 2d numpy array against 1d list


code: O(nlogn + m*logn) < O(m*n)

rawDescription: Which is the fastest way to search a value within a set of many "range" objects in Python


rawDescription: Average time for datetime list

description: Average time for datetime list


code:
def RandomAlter(l, func, char):
    # For each word in our list
    main_list = []
    for w in l:
        # Create a container that is going to hold our new 'word'
        new_word = []
        # Iterate over a range that is equal to the number of chars in the word
        # xrange is a more memory efficient 'range' - same behavior
        for x in xrange(len(w)):
            # If the current position is the character we want to modify
            if x == char:
                # Apply the function to the character and append to our 'word'
                # This is a cool Python feature - you can pass around functions
                # just like any other variable
                new_word.append(func(w[x]))
            else:
                # Just append the normal letter
                new_word.append(w[x])

        # Now we append the 'word' to our main_list. However since the 'word' is
        # a list of letters, we need to 'join' them together to form a string
        main_list.append(''.join(new_word))

    # Now just return the main_list, which will be a list of altered words
    return main_list

rawDescription: HOW TO "Arbitrary" format items in list/dict/etc. EX: change 4th character in every string in list


code: f = replacement_f

rawDescription: How to replace Python function while supporting all passed in parameters

description: Replace Python function while supporting all passed in parameters


rawDescription: How to plot with x-axis at the top of the figure?

description: Plot with x-axis at the top of the figure


code:
reps = 5 # or whatever value you'd like
out = re.sub('[0-9]{{{}}}'.format(reps), '', input)

rawDescription: How do you set a variable number of regex expressions?

description: Set a variable number of regex expressions


code:
splitted = df['Terms'].str.split(',', expand=True)
splitted

rawDescription: How to split string from column to create long format dataframe

description: Split string from column to create long format dataframe


code: data[num] if num in data else data[min(data.keys(), key=lambda k: abs(k-num))]

rawDescription: Python: find closest key in a dictionary from the given input key


code:
def load():
    inFile = open('save.txt', 'rb')
    newList = cPickle.load(inFile)
    inFile.close()
    return newList

rawDescription: name 'newList' is not defined

description: Name 'newList' is not defined


rawDescription: Regular Expression for whole numbers and integers?


code:
def ignore_exception(IgnoreException=Exception,DefaultVal=None):
    """ Decorator for ignoring exception from a function
    e.g.   @ignore_exception(DivideByZero)
    e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
    """
    def dec(function):
        def _dec(*args, **kwargs):
            try:
                return function(*args, **kwargs)
            except IgnoreException:
                return DefaultVal
        return _dec
    return dec

rawDescription: Is there a built-in or more Pythonic way to try to parse a string to an integer


code:
from subprocess import check_call

check_call("cmd1 > >(cmd2) 2> >(cmd3)", shell=True, executable="/bin/bash")

rawDescription: "3-way" Python subprocess pipeline: send stdout and stderr to two different processes?


code:
import Tkinter as tk
import csv
import MasterWindow
from fabfile import connect
import time
from fabric.api import env

LARGE_FONT= ("Verdana", 12)
env.host_string = 'nms@10.0.0.70'
env.password = "nms"

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Graphy-Home", font=LARGE_FONT)
        label.pack(pady=10,padx=10)
        Command = tk.Label(self, text="Enter Command")
        pickCommand = tk.Entry(self)
        pickCommand.pack(pady=10)
        Command.pack()
        button1 = tk.Button(self, text="Submit Command", command=lambda: submit())
        button1.pack()

    def submit(ItrCnt=0,sleepTime=3):
        while (ItrCnt < 10):
            print (pickCommand.get())
            cmd=pickCommand.get()
            ItrCnt=ItrCnt+1
            time.sleep(sleepTime)
            p=connect(cmd)
            print(p.stdout)

rawDescription: Python - fabric module missing all of a sudden


rawDescription: byte reverse AB CD to CD AB with python

description: Byte reverse AB CD to CD AB with python


code:
ax.set_xlim((-50,150))
ax.set_xticks(np.arange(-50, 150, 20))
plt.show()

rawDescription: How to edit x axis with pylab?

description: Edit x axis with pylab


rawDescription: Python cross correlation

description: Python cross correlation


code: result = [f(x) for f, x in zip(funcs, data)]

rawDescription: How to map a tuple of data to a tuple of functions?

description: Map a tuple of data to a tuple of functions


code: (tiles, found) = action.miner_to_ore(world, ore)

rawDescription: If a function (that's outside of the class) needs to use a method from a class, how do I call the method?


code:
class Example:

    # Define this priority
    __array_priority__ = 2

    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return other + self.value

    def __radd__(self, other):
        return other + self.value

import numpy as np
np.arange(5) + Example(np.arange(5))
# returns array([0, 2, 4, 6, 8])

rawDescription: Avoid numpy distributing an operation for overloaded operator


code:
@pytest.fixture(params=['web01-east.domain.com', 'redis01-master-east.domain.com', 'web01.domain.com'])
def patch_socket(request, monkeypatch):
    def gethostname():
        return request.param
    monkeypatch.setattr(socket, 'gethostname', gethostname)

def test__get_pod(patch_socket):
    assert __get_pod() == 'east'

rawDescription: py.test multiple tests per fixture

description: Py.test multiple tests per fixture


code:
width = 0
height = 0
i = 0
sum_x = max_y = 0

rawDescription: Creating a montage of pictures in python


code:
FIRST_CHECK = re.compile("^\d\d - ")
SECOND_CHECK = re.compile("^\d\d ")

rawDescription: Cleaner way to move renamed files when walking over directory


code:
import numpy as np
import pandas as pd
arr = df.values.reshape(1,-1)

rawDescription: Flattening Table From Excel into Csv with Pandas


code:
bigDict.setdefault(label, {}).setdefault(num, 0)
bigDict[label][num] += 1

rawDescription: using nested dictionaries in python

description: Using nested dictionaries in python


rawDescription: Http POST Accents encoding

description: Http POST Accents encoding


code:
from xml.etree import cElementTree as etree

tree = etree.parse("my_xml_file.xml")
namespaces = {"a":"http://schemas.openxmlformats.org/presentationml/2006/main"}
slidenums = tree.findall("a:fld[@type='slidenum']/a:t", namespaces)
for slidenum in slidenums:
    print(slidenum.text)

rawDescription: retrieve data from xml tag Python

description: Retrieve data from xml tag Python


code: [dict(zip(configSet['fields'], result)) for result in configSet['results']]

rawDescription: Python convert a dict object including list to list including dict


code:
def apply_on_all(seq, method, *args, **kwargs):
    for obj in seq:
         getattr(obj, method)(*args, **kwargs)

rawDescription: How to call same method for a list of objects?

description: Call same method for a list of objects


rawDescription: MaxMind IP Lookup Speed with Python API

description: MaxMind IP Lookup Speed with Python API


code:
def chunks(seq, n):
    # http://stackoverflow.com/a/312464/190597 (Ned Batchelder)
    """ Yield successive n-sized chunks from seq."""
    for i in xrange(0, len(seq), n):
        yield seq[i:i + n]

data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
for row in chunks(data, 3):
    print(',  '.join(map(str, row)))

rawDescription: Write to list to rows with specific number of columns


code: cars = {1: car1, 2: car2}

rawDescription: Using a String to Call a Variable in Python 3.3 with Pygame


code: dict.fromkeys(i for i in range(sys.maxunicode+1) if chr(i) not in 'aeiou')

rawDescription: Deleting consonants from a string in Python


code:
ystep =[]
for rec in range(0,x.shape[0],skip):
    ystep.append(y[argrelmax(y[rec:rec+skip])[0]])

rawDescription: Finding discrete logic levels in a waveform


code:
def format_dict(d, indent=0):
    output = []
    for k, v in d.iteritems():
        if isinstance(v, dict):
            output.append(indent*' ' + str(k))
            output.append(indent*' ' + '{')
            output.append(format_dict(v, indent+4))
            output.append(indent*' ' + '}')
        else:
            output.append(indent*' ' + str(k).ljust(16) + str(v) + ';')
    return '\n'.join(output)

rawDescription: Best way to format a nested Python dictionary to be rendered in a jinja2 templates

description: Format a nested Python dictionary to be rendered in a jinja2 templates


rawDescription: Single, double, or triple double quotes for Python’s raw string notation for regex?


code:
import itertools
for i in itertools.cycle(range(10)):
    if condition:
        break
    else:
        print(i)

rawDescription: How to use For loop to cycle through 1 to 10 again and again until the loop is broken in python

description: Use For loop to cycle through 1 to 10 again and again until the loop is broken in python


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

def plot_corr_ellipses(data, ax=None, **kwargs):

    M = np.array(data)
    if not M.ndim == 2:
        raise ValueError('data must be a 2D array')
    if ax is None:
        fig, ax = plt.subplots(1, 1, subplot_kw={'aspect':'equal'})
        ax.set_xlim(-0.5, M.shape[1] - 0.5)
        ax.set_ylim(-0.5, M.shape[0] - 0.5)

    # xy locations of each ellipse center
    xy = np.indices(M.shape)[::-1].reshape(2, -1).T

    # set the relative sizes of the major/minor axes according to the strength of
    # the positive/negative correlation
    w = np.ones_like(M).ravel()
    h = 1 - np.abs(M).ravel()
    a = 45 * np.sign(M).ravel()

    ec = EllipseCollection(widths=w, heights=h, angles=a, units='x', offsets=xy,
                           transOffset=ax.transData, array=M.ravel(), **kwargs)
    ax.add_collection(ec)

    # if data is a DataFrame, use the row/column names as tick labels
    if isinstance(data, pd.DataFrame):
        ax.set_xticks(np.arange(M.shape[1]))
        ax.set_xticklabels(data.columns, rotation=90)
        ax.set_yticks(np.arange(M.shape[0]))
        ax.set_yticklabels(data.index)

    return ec

rawDescription: How can I plot a correlation matrix as a set of ellipses, similar to the R open-air package?

description: Plot a correlation matrix as a set of ellipses, similar to the R open-air package


code:
newsletters = Newsletter.objects.prefetch_related('article_set').all()\
                    .order_by('-year', '-number')

return render_to_response('newsletter/newsletter_list.html',
                          {'newsletter_list': newsletters})

rawDescription: Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)


code:
all_challenges = session.query(Challenge).\
                  filter(Challenge.id.in_(session.query(UserAttempt.challenge_id))).all()

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


code:
# Convert to int array and thus convert each bit of input string to numerals
str2num = np.remainder(A.astype(np.int)//(10**np.arange(3,-1,-1)),10)

de2bi_convarr = 2**np.arange(3,-1,-1)
out = str2num.dot(de2bi_convarr)

rawDescription: fastest way to convert bitstring numpy array to integer base 2

description: Fastest way to convert bitstring numpy array to integer base 2


rawDescription: accessing 2d numpy arrays

description: Accessing 2d numpy arrays


code:
# Start measuring coverage if in testing
if vim.vars.get('measure_coverage'):
    import os
    import atexit
    import coverage
    coverage_path = os.path.expanduser('~/coverage-data/.coverage.{0}'.format(os.getpid()))
    cov = coverage.coverage(data_file=coverage_path)
    cov.start()

    def save_coverage():
        cov.stop()
        cov.save()

    atexit.register(save_coverage)

rawDescription: Is there a way how to test coverage of a vim plugin?


code:
n = np.empty((1,), dtype=object)
n[0] = [None]
s[pd.isnull(s)] = n

rawDescription: How can I set (dtype=object) numpy array values to Python lists, without numpy interpreting the lists as lists of values?

description: Set (dtype=object) numpy array values to Python lists, without numpy interpreting the lists as lists of values


code:
from django.utils.translation import ugettext_lazy as _

# if the translation data exists
_('This string will be translated')

rawDescription: how to change the name of the field displaying in my form

description: Change the name of the field displaying in my form


code:
items_by_year = {
 2004: 10352,
 2005: 15125,
 2006: 8989,
 2007: 1500,
 2008: 10000
}
years = sorted(items_by_year.keys())
to_hist = []
for year in items_by_year:
    to_hist.extend([year]*items_by_year[year])

rawDescription: Chart cumulative percentage by year in matplotlib?


code: sorted(range(10), key=lambda x: (x-5)**2)

rawDescription: Python: Sort nested dictionary by value

description: Python: Sort nested dictionary by value


code:
import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

rawDescription: Can't figure out how to bind the enter key to a function in tkinter


code: time = "%s:%s" % divmod(int(entry), 60)

rawDescription: Unnecessary repetition of declaration

description: Unnecessary repetition of declaration


code: exp = re.compile(r"page%s\.html" % digit_match_greater(last_page_visited))

rawDescription: generate python regex at runtime to match numbers from 'n' to infinite

description: Generate python regex at runtime to match numbers from 'n' to infinite


rawDescription: Grouping Python Panda table with additional heading


code: newlist = [10] + list(mytup)

rawDescription: Where does the list assignment go?

description: Where does the list assignment go


code:
trades.index = timestamps
trades

rawDescription: Python pandas - bucketting and getting sum


code:
s = """Let's say this is first line and let's check line 4
In this second line there are number 10 and 8
Third line doesn't have any numbers
This is fourth line and we'll go on in line 12
This is fifth line and we go on in line 8
In sixth line there is number 6
This seventh line contains number 5, which means 5th line
This is eighth and the last line, it ends here.
These three lines are boring.
They really are
In eleventh line we can see that line 12 is really interesting
This is twelfth line but we go back to line 7."""

lines = s.splitlines()

rawDescription: Numbers in string

description: Numbers in string


rawDescription: How can I get the list sorted out according to the IP address?

description: Get the list sorted out according to the IP address


code:
from django.core.management import call_command
call_command('syncdb', interactive=True)

rawDescription: In django, how do I call the subcommand 'syncdb' from the initialization script?


code:
warn("Use of multiple -w arguments is deprecated and "
     "support may be removed in a future release. You can "
     "get the same behavior by passing directories without "
     "the -w argument on the command line, or by using the "
     "--tests argument in a configuration file.",
     DeprecationWarning)

rawDescription: Python nose configuration file only allow WHERE to be speciifed once


code:
def read_file(fname):
    "Returns contents of file with name `fname`."
    with open(fname) as fp:
         return fp.read()

def write_file(fname, txt):
    "Writes `txt` to a file named `fname`."
    with open(fname, 'w') as fp:
         fp.write(txt)

rawDescription: parse blocks of text from text file using Python

description: Parse blocks of text from text file using Python


code:
from __future__ import division
from collections import Counter
import random
import string

VOWELS = "aeiou"
CONSONANTS = "".join(set(string.lowercase) - set(VOWELS))

def dealHand(n):
    numVowels = n // 3
    lettersets = [VOWELS] * numVowels + [CONSONANTS] * (n - numVowels)
    return Counter(c
        for letterset in lettersets
        for c in random.choice(letterset)
    )

rawDescription: random chars for word game python

description: Random chars for word game python


code:
def listRightIndex(alist, value):
    return len(alist) - alist[-1::-1].index(value) -1

rawDescription: Equivelant to rindex for lists in Python


code:
traveller_node = start_node  # Chosen somehow

while not stopping_condition(traveller_node):
    possible_successors = traveller_node.successors()
    traveller_node = random_choice_from(possible_successors)

rawDescription: Weighted Random Graph Traversal in Python


code: gender = person.gender

rawDescription: Why should I ever use "getattr()"?

description: Why should I ever use "getattr()"


code:
class MenuItemComponentSerializer(serializers.Serializer):
    url = ComponentURLField(source='component')
    name = Field(source='component.name')
    isReplaceable = Field()

rawDescription: How to extend model on serializer level with django-rest-framework

description: Extend model on serializer level with django-rest-framework


rawDescription: Python : How to find in set of rows, one element is less than 1 and other is greater than 1?


code:
import urllib2
from cookielib import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict)
cj = CookieJar(policy)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://somewebsite.com")

[str(i) for i in cj]

rawDescription: Human readable cookie information using cookielib?


rawDescription: When should I use a custom Manager versus a custom QuerySet in Django?


code: matches("bears", ["bea", "be", "ars"])

rawDescription: find best subset from list of strings to match a given string

description: Find best subset from list of strings to match a given string


code:
import sys
import tempfile
import os

class captured_stdout:
    def __init__(self):
        self.prevfd = None
        self.prev = None

    def __enter__(self):
        F = tempfile.NamedTemporaryFile()
        self.prevfd = os.dup(sys.stdout.fileno())
        os.dup2(F.fileno(), sys.stdout.fileno())
        self.prev = sys.stdout
        sys.stdout = os.fdopen(self.prevfd, "w")
        return F

    def __exit__(self, exc_type, exc_value, traceback):
        os.dup2(self.prevfd, self.prev.fileno())
        sys.stdout = self.prev

##
## Example usage
##

## here is a hack to print directly to stdout
import ctypes
libc=ctypes.LibraryLoader(ctypes.CDLL).LoadLibrary("libc.so.6")
def directfdprint(s):
    libc.write(1, s, len(s))

print("I'm printing from python before capture")
directfdprint("I'm printing from libc before captrue\n")

with captured_stdout() as E:
    print("I'm printing from python in capture")
    directfdprint("I'm printing from libc in capture\n")

print("I'm printing from python after capture")
directfdprint("I'm printing from libc after captrue\n")

print("Capture contains: " + repr(file(E.name).read()))

rawDescription: dup, dup2, tmpfile and stdout in python

description: Dup, dup2, tmpfile and stdout in python


code:
level = [
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W                                       W",
"W                                       W",
"W                                       W",
"W              WRRRRRRRW                W",
"               R       R                 ",
"W              R       R                W",
"W              R       R                W",
"W              R       R                W",
"W              WRRRRRRRW                W",
"                                         ",
"W                                       W",
"W                                       W",
"W                                       W",
"W                                       W",
"W                                       W",
"W                                       W",
"W                                       W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]

rawDescription: Create a random door in pygame

description: Create a random door in pygame


code:
def flatten(seq, list = None):
    """flatten(seq, list = None) -> list

    Return a flat version of the iterator `seq` appended to `list`
    """
    if list == None:
        list = []
    try:                          # Can `seq` be iterated over?
        for item in seq:          # If so then iterate over `seq`
            flatten(item, list)      # and make the same check on each item.
    except TypeError:             # If seq isn't iterable
        list.append(seq)             # append it to the new list.
    return list

rawDescription: Extract numbers from a string list - python


code:
import re
p = re.compile(r'[({\[](?!key).*?[)\]}]', re.MULTILINE)
test_str = "\n\n text1 (key) text2\n\n text1 (key) text2 (some other text)\n\n [key] text.. text.. [some other text]\n\n and so on\n"
subst = ""

result = re.sub(p, subst, test_str)

rawDescription: Remove text in parentheses except if text contains keyword


code:
return render(request, 'app/profile.html', context={'names': names}, status=200)
# it's always a good habit to return an HTTP status code

rawDescription: how to parse json array in django

description: Parse json array in django


code: (arr.transpose(1, 0, 2) == arr).all()

rawDescription: testing if a numpy array is symmetric?

description: Testing if a numpy array is symmetric


code:
s = sign(a)
b = b * s

rawDescription: Why doesn't Python have a sign function?

description: Why doesn't Python have a sign function


code:
class RFile(object):
    seen = {}

    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        if other in self.seen:
            text = self.seen[other]
        else:
            text = self.seen[other] = other.read()
            other.close()
        if not isinstance(text, str):
            text = text.decode('ascii')
        return self.name == other.name == text

class TestFileTypeR(TempDirMixin, ParserTestCase):
    """Test the FileType option/argument type for reading files"""

    def setUp(self):
        super(TestFileTypeR, self).setUp()
        for file_name in ['foo', 'bar']:
            file = open(os.path.join(self.temp_dir, file_name), 'w')
            file.write(file_name)
            file.close()
        self.create_readonly_file('readonly')

    argument_signatures = [
        Sig('-x', type=argparse.FileType()),
        Sig('spam', type=argparse.FileType('r')),
    ]
    failures = ['-x', '', 'non-existent-file.txt']
    successes = [
        ('foo', NS(x=None, spam=RFile('foo'))),
        ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
        ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
        ('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
        ('readonly', NS(x=None, spam=RFile('readonly'))),
    ]

rawDescription: How to test opened files in argparse using nose

description: Test opened files in argparse using nose


rawDescription: How to reset some function variables in Python in a loop

description: Reset some function variables in Python in a loop


code:
def Check(self):
   if (condition):
       self.parent().setMyCentral(widget2)

rawDescription: How to set the central widget of existing MainWidnow in Python PyQt4?

description: Set the central widget of existing MainWidnow in Python PyQt4


code: xyz = zip(*calib)

rawDescription: Python 2.7 find min,max on list of lists


code: response = browser.session.post(...)

rawDescription: How to make POST request in robobrowser-python

description: Make POST request in robobrowser-python


code: new = Thing()

rawDescription: Use class variables as instance vars?

description: Use class variables as instance vars


code:
a = np.arange(25).reshape(5, 5)
a

rawDescription: Clarification on indexing numpy array in python


rawDescription: Special case when finding min key for dictionary in Python


code: ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot);    # plot a 3d surface plot

rawDescription: matplotlib - 3D plots - combining scatter plot with surface plot

description: Matplotlib - 3D plots - combining scatter plot with surface plot


code:
a
a.irow(0)[3:].reshape(3,2)
dict(_)

rawDescription: Convert data frame columns to dictionary


code:
def put_blob(storage_url,container_name, blob_name,qry_string,x_ms_blob_type):
 opener = urllib2.build_opener(urllib2.HTTPHandler)
 request = urllib2.Request(storage_url+container_name + '/' + blob_name+'?'+qry_string, data='Hello World!!')
 request.add_header('x-ms-blob-type', x_ms_blob_type)
 request.get_method = lambda: 'PUT'
 opener.open(request)

rawDescription: Fine-Uploader in depth information on the use of Azure Blob Storage through python flask


rawDescription: Finding indices of matches of one array in another array


code:
class Product(models.Model):
    name = models.CharField(max_length=255)
    shops = models.ManyToManyField(Shop, through='ProductShop', related_name='products')
    def lowest_possible_price(self):
        shops = self.shops.all()
        if not shops:
            return "N/A"
        return reduce(lambda x, y: min(x, ProductShop.objects.get(shop__pk=y.id, product__pk=self.id).price),
                shops, ProductShop.objects.get(shop__pk=shops[0].id, product__pk=self.id).price)

rawDescription: Annotate using an extra field from a ManyToMany model in Django


code: r'Normalized Distance in Chamber ($\frac{x}{L}$)'

rawDescription: \frac{}{} won't work for me w/ pylab

description: \frac{}{} won't work for me w/ pylab


code:
with open(in_filename, 'rb') as in_file, open(out_filename, 'wb') as out_file:
    encrypt(in_file, out_file, password)
with open(in_filename, 'rb') as in_file, open(out_filename, 'wb') as out_file:
    decrypt(in_file, out_file, password)

rawDescription: How to AES encrypt/decrypt files using Python/PyCrypto in an OpenSSL-compatible way?


code: zipped = []

rawDescription: python how do I empty or clear a zip()

description: Python how do I empty or clear a zip()


code:
user = User.objects.create_user(username='asdf', email='asdf@example.com', password='xxxx')
user.password

rawDescription: Django test client does not log in

description: Django test client does not log in


code:
from fuzzywuzzy import fuzz

combined_list = ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']
combined_list.append('bakesh')
print('input names:', combined_list)

grs = list() # groups of names with distance > 80
for name in combined_list:
    for g in grs:
        if all(fuzz.ratio(name, w) > 80 for w in g):
            g.append(name)
            break
    else:
        grs.append([name, ])

print('output groups:', grs)
outlist = [el for g in grs for el in g]
print('output list:', outlist)

rawDescription: How to group words whose Levenshtein distance is more than 80 percent in Python

description: Group words whose Levenshtein distance is more than 80 percent in Python


code: list_a, list_b = list(range(2, 6)), list(range(2, 6))

rawDescription: Python Multiplication of Two Lists

description: Python Multiplication of Two Lists


code:
from itertools import groupby

d = {True: 'Correct', False: 'Incorrect'}
with open('text1.txt') as f:
    for k, g in groupby(f, key=str.isspace):
        if not k:
            # Split each line in the current group at whitespaces
            data = [line.split() for line in g]
            # If for each line the second column is equal to third then `all()` will
            # return True.
            predicts_matched = all(line[1] == line[2] for line in data)
            print ('{}: {}'.format(' '.join(x[0] for x in data), d[predicts_matched]))

rawDescription: read through sentences separated by line break and parse

description: Read through sentences separated by line break and parse


code: [float(v) for v in c]

rawDescription: Convert list of numpy.float64 to float in Python quickly


code: userlist.pop(userlist.index(-max([-u for u in userlist])))

rawDescription: How do I remove an element from a list without using .remove

description: Remove an element from a list without using .remove


code:
from datetime import timedelta

def msum(s, lag):
    lag = s.index - timedelta(days=lag)
    inds = np.searchsorted(s.index.astype(np.int64), lag.astype(np.int64))
    cs = s.cumsum()
    return pd.Series(cs.values - cs[inds].values + s[inds].values, index=s.index)

rawDescription: Pandas - Rolling window - uneven interval


code:
import ast
ast.literal_eval(s)[2]

rawDescription: using regex to get a substring from a string

description: Using regex to get a substring from a string


code: a = np.random.normal(size=(20,10,10))

rawDescription: Diagonalisation of an array of 2D arrays


code:
elements = [[10, 20], [30, 40], [50, 60]]
[x for i in range(len(elements)) for x in itertools.product(*elements[:i+1])]

rawDescription: How to generate lists from a specification of element combinations

description: Generate lists from a specification of element combinations


code: php -a

rawDescription: Shortcut to testing PHP code

description: Shortcut to testing PHP code


code:
from sqlalchemy import create_engine, MetaData
engine = create_engine('mssql+pyodbc://<username>:<password>@<host>/<database>')  # replace <username> with user name etc.
meta = MetaData()
meta.reflect(bind=engine)
funds_table = meta.tables['funds']  # tables are stored in meta.tables dict
funds_table  # now stores database schema object

rawDescription: Does the Storm or SQLAlchemy ORM allow creating schema's from an existing database?


code:
f = win32file.CreateFile(path,
                         win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                         win32con.FILE_SHARE_DELETE,
                         None,
                         0,
                         win32con.OPEN_ALWAYS,
                         None)

rawDescription: Does Python IO allow opened file to be deleted/renamed on Windows?


code: [event for event in dicts[key][id]["events"] if event["eventID"] != event_id]

rawDescription: Remove a list item in a nested dictionary


code:
default = object()

def function(a, start = 0, end = default):
    if end is default: end = (len(a) - 1)
    return start, end

rawDescription: Using the length of a parameter array as the default value of another parameter of the same function


code: X = tuple(gen_X())

rawDescription: Conditionals when defining a tuple / list


rawDescription: Python: Finding corresponding indices for an intersection of two lists


code:
def applyPlotStyle():
    plt.xlabel('Size')
    plt.ylabel('Time(s)');
    plt.title('Matrix multiplication')

    plt.xticks(range(100), rotation=30, size='small')
    plt.grid(True)

plt.subplot(211)
applyPlotStyle()
plt.plot(xl, serial_full, 'r--')
plt.plot(xl, acc, 'bs')
plt.plot(xl, cublas, 'g^')

plt.subplot(212)
applyPlotStyle()
plt.yscale('log')
plt.plot(xl, serial_full, 'r--')
plt.plot(xl, acc, 'bs')
plt.plot(xl, cublas, 'g^')

rawDescription: matplotlib subplots with same 'settings'

description: Matplotlib subplots with same 'settings'


code:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random_integers(0, 10**4, 10**5)
correlation = Counter(data).items()
correlation.sort(key=lambda x: x[1])
labels, values = zip(*correlation)
indexes = np.arange(len(correlation))

plt.plot(indexes, values)
plt.fill_between(indexes, values, 0)
plt.show()

rawDescription: Plot a histogram with the x axis values based on the height of the column


rawDescription: Average of a numpy array returns NaN

description: Average of a numpy array returns NaN


code:
value = 'www.test.com'
any(c.isdigit() for c in value)
value = 'www.123.com'
any(c.isdigit() for c in value)
value = 'www.tes$%%^^^t.com'
any(c.isdigit() for c in value)

rawDescription: Python Detect numbers in string by a list of sample


rawDescription: How can I find all indices of a value in a multidimensional array?

description: Find all indices of a value in a multidimensional array


code:
forms.py
# this name may not fit your needs if you have more fields, but you get the idea
class UserEmailForm(forms.Form):
    email = forms.CharField()

rawDescription: How can I prefill value in a custom form field in a ModelForm

description: Prefill value in a custom form field in a ModelForm


code:
for key in dictionary:
    dictionary[key] = tuple(dictionary[key])

rawDescription: Convert dictionary of lists to dictionary of tuples


code:
@app.route('/get_data/', methods=['GET'])
def get_data():
    var1 = request.args.get('var1', 'a')
    var2 = request.args.get('var2', 'b')
    data = mc.some_fn(var1, var2)
    return jsonify({'get_data:': data})

rawDescription: python-flask: pluggable views for dynamic routes

description: Python-flask: pluggable views for dynamic routes


code:
from itertools import izip
x = [dict(date=d, user=u) for d, u in izip(x['date'], x['users'])]

rawDescription: How to structure data to easily build HTML tables in Flask

description: Structure data to easily build HTML tables in Flask


code: s = {key for counter in counters.values() for key in counter}

rawDescription: Python map() dictionary values

description: Python map() dictionary values


code: Y[k,jj,0] += S[ii,jj,0] * c[k-ii,jj,jj] * U[ii,jj,jj]

rawDescription: Struggling With Python For-Loop Speed

description: Struggling With Python For-Loop Speed


code: soup = BeautifulSoup(file, "html5lib")

rawDescription: How do I remove a spurious tag in BeautifulSoup

description: Remove a spurious tag in BeautifulSoup


code: ['segment1', 'segment2', 'segment2']

rawDescription: Segment string into array, regex?

description: Segment string into array, regex


rawDescription: Model an undirected graph in Python

description: Model an undirected graph in Python


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

xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)

# Reshape things so that we have a sequence of:
# [[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],...]
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])

fig, ax = plt.subplots()
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)
coll.set_array(np.random.random(xy.shape[0]))

ax.add_collection(coll)
ax.autoscale_view()

plt.show()

rawDescription: python: how to plot one line in different colors

description: Python: how to plot one line in different colors


code:
class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __eq__(self, other):
        if isinstance(other, Fruit):
            return (self.name, self.color) == (other.name, other.color)
        return self.name == other

fruits = [Fruit('apple', 'red'), Fruit('banana', 'yellow')]
print("An apple is %s" % fruits[fruits.index('apple')].color)

rawDescription: Accessing list of Python objects by object attribute


code:
import sys
import time
import random

for i in range(50):
    f = random.choice([sys.stdout,sys.stderr])
    f.write(str(i)+'\n')
    f.flush()
    time.sleep(0.1)

rawDescription: Subprocess.Popen: cloning stdout and stderr both to terminal and variables


code:
NUMBER_OF_MONTHS = 12
def collapse(A):
    dep = dict()
    for row in A:
        if row[0] not in dep:
            dep[row[0]] = [0.0 for x in xrange(NUMBER_OF_MONTHS)]
        for i in xrange(NUMBER_OF_MONTHS):
            dep[row[0]][i] += row[i+2]
    ret = list()
    for department in dep:
        x = [department]
        x.extend(dep[department])
        ret.append(x)
    return ret

rawDescription: Creating a 2D Array from Another 2D Array (Python)


code:
from collections import namedtuple
from copy import deepcopy

def find_groups(inpixels):
    """
    Group the pixels in the image into three categories: free, closed, and
    border.
        free: A white pixel with a path to outside the image.
        closed: A white pixels with no path to outside the image.
        border: A black pixel.

    Params:
        pixels: A collection of columns of rows of pixels. 0 is black 1 is
                white.

    Return:
        PixelGroups with attributes free, closed and border.
        Each is a list of tuples (y, x).
    """

    # Pad the entire image with white pixels.
    width = len(inpixels[0]) + 2
    height = len(inpixels) + 2
    pixels = deepcopy(inpixels)
    for y in pixels:
        y.insert(0, 1)
        y.append(1)
    pixels.insert(0, [1 for x in range(width)])
    pixels.append([1 for x in range(width)])

    # The free pixels are found through a breadth first traversal.
    queue = [(0,0)]
    visited = [(0,0)]
    while queue:
        y, x = queue.pop(0)

        adjacent = ((y+1, x), (y-1, x), (y, x+1), (y, x-1))
        for n in adjacent:
            if (-1 < n[0] < height and -1 < n[1] < width and
                                        not n in visited and
                                    pixels[n[0]][n[1]] == 1):
                queue.append(n)
                visited.append(n)

    # Remove the padding and make the categories.
    freecoords = [(y-1, x-1) for (y, x) in visited if
                 (0 < y < height-1 and 0 < x < width-1)]
    allcoords = [(y, x) for y in range(height-2) for x in range(width-2)]
    complement = [i for i in allcoords if not i in freecoords]
    bordercoords = [(y, x) for (y, x) in complement if inpixels[y][x] == 0]
    closedcoords = [(y, x) for (y, x) in complement if inpixels[y][x] == 1]

    PixelGroups = namedtuple('PixelGroups', ['free', 'closed', 'border'])
    return PixelGroups(freecoords, closedcoords, bordercoords)

def print_groups(ysize, xsize, pixelgroups):
    ys= []
    for y in range(ysize):
        xs = []
        for x in range(xsize):
            if (y, x) in pixelgroups.free:
                xs.append('.')
            elif (y, x) in pixelgroups.closed:
                xs.append('X')
            elif (y, x) in pixelgroups.border:
                xs.append('#')
        ys.append(xs)
    print('\n'.join([' '.join(k) for k in ys]))

rawDescription: Find closed shapes in image

description: Find closed shapes in image


code: enum_names = {value: name for name, value in vars(MyClass).items() if name.isupper()}

rawDescription: Python: Converting value of constant to name of constant


code:
ax2 = ax1.twinx()
ax2.set_ylim(bottom=-10, top=10)

rawDescription: Unable to control scale of second y-axis on df.plot()


code:
stop_words = set(stop_words)
def tokenizer(text, stem = stemmer.stem, tokenize = nltk.word_tokenize):
   return [stem(tok) for tok in tokenize(text.lower())
           if tok.isalpha() and tok not in stop_words]

rawDescription: Efficient method to exclude items in one list from another list in Python


code:
import re
largeString = "Lorem ipsum ###### some previous text to be erased ###### dolor sit amet"
smallString = "foo bar"
re.sub(r'(?<=###### ).*(?= ######)', smallString, largeString)

rawDescription: How to insert a string between particular characters in Python?

description: Insert a string between particular characters in Python


code: pointsToAdd = int(input("How many Strength points would you like to add: "))

rawDescription: While loop in python not working

description: While loop in python not working


rawDescription: Improve performance of the np.irr function through vectorization


rawDescription: Why does a 'for' loop in python change unreferenced lists?


rawDescription: How can I select n items and skip m from ndarray in python?

description: Select n items and skip m from ndarray in python


rawDescription: How to access wmi in python?

description: Access wmi in python


code: doc["scores"]

rawDescription: How to retrieve sub documents in a Array from mongoDB using python script

description: Retrieve sub documents in a Array from mongoDB using python script


code: pkg_name = XYZ_1000

rawDescription: Is there any way to access variable like $var (similar to shell scripting) in python?


code:
def find_idx(tree, idx):
    """
    Return the node containing the idx'th function parameter, and the index of that
    parameter.  If the tree contains fewer than idx parameters, return (None, None).
    """
    if not isinstance(idx, list):
        # Stash this in a list, so recursive calls share the same value.
        idx = [idx]

    for i, o in enumerate(tree):
        # Skip the function itself.
        if i == 0:
            continue

        if idx[0] == 0:
            return tree, i

        idx[0] -= 1
        if isinstance(o, list):
            container, result_index = find_idx(o, idx)
            if container is not None:
                return container, result_index

    return None, None

rawDescription: How to split two nested lists and combine the parts to create two new nested lists

description: Split two nested lists and combine the parts to create two new nested lists


code: df

rawDescription: Pandas: read_csv indicating 'space-delimited'


code:
params['foo'] = my_raw_input.decode('iso-8859-1')
params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))

rawDescription: Python interface to PayPal - urllib.urlencode non-ASCII characters failing


rawDescription: Processing a remote iCal with Python

description: Processing a remote iCal with Python


code:
BROKER_TRANSPORT_OPTIONS = {
    'priority_steps': list(range(10)),
}

rawDescription: Task priority in celery with redis

description: Task priority in celery with redis


rawDescription: Python to search values in one text file, compare them with values in another text file, then replace values if there is a match


code:
l[:,0]
np.unique(l[:,0], return_inverse = True)

rawDescription: Converting a list of (x,y,z) tuples spaced on a square lattice to an array


code:
class FloatWithUnit(float):
    def __new__(cls, val, unit):
        return float.__new__(cls, val)
    def __init__(self, val, unit):
        self.unit = unit
    def __str__(self):
        return '%g %s' % (self, self.unit)
    def __repr__(self):
        return self.__str__()

rawDescription: creating class object that normally looks like a float

description: Creating class object that normally looks like a float


rawDescription: Split python dictionary to result in all combinations of values


code:
class ValueCache(object):
    def __init__(self, val=None):
        self.val = val

    def update(self, new):
        if self.val == new:
            return False
        else:
            self.val = new
            return True

rawDescription: Dectecting a value change in Python loop


rawDescription: Is there a way to prevent a python 3 script from being called in python 2?


rawDescription: Count number of rows in a many-to-many relationship (SQLAlchemy)


code:
map_surface = pygame.Surface(( len(tilemap[0])*TILE_WIDTH, len(tilemap)*TILE_HEIGHT ))
for y,row in enumerate(tilemap):
    for x,tile_surface in enumerate(row):
        map_surface.blit(tile_surface,(x*TILE_WIDTH,y*TILE_HEIGHT))

rawDescription: How to draw a list of sprites in Pygame

description: Draw a list of sprites in Pygame


rawDescription: Python identify file with largest number as part of filename


code: while reduction_pass(dataset) > 0: pass

rawDescription: How to organize this loop in a more elegant Pythonic way

description: Organize this loop in a more elegant Pythonic way


code:
from tkinter import *

class Return_Value_In_Entry():
    def __init__(self):
        self.Master=Tk()

        self.Entry=Entry(self.Master)
        self.Entry.pack()

        self.Button=Button(self.Master,text="Submit",command=self.Return)
        self.Button.pack()

        self.Master.mainloop()

    def Return(self):
        self.TempVar=self.Entry.get()

        print(self.TempVar)

Return_Value_In_Entry()

rawDescription: Can a tkinter button return a value from an entry on-click?


rawDescription: Python PySide and Progress Bar Threading


code:
import numpy.polynomial.polynomial as poly
poly.polyval(p1, [1,1,1])
poly.polyval(p2, [1,1])

rawDescription: evaluating numpy polynomials at other polynomials

description: Evaluating numpy polynomials at other polynomials


code: d

rawDescription: python - convert date input to date output without time

description: Python - convert date input to date output without time


code:
import subprocess

output = subprocess.check_output(['curl', myLink, '-F', myFile])

rawDescription: Is it possible to make such a request with extra options in Python?


code:
from django.db import models

class TitlePost(models.Model):
    title_name = models.CharField(max_length=100, unique=True)
    title_body = models.TextField(max_length=30000)
    title_why = models.TextField(max_length=250, null=True)
    title_publication_date = models.DateTimeField('date')
    likes = models.IntegerField(default=0)
    dislikes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.title_name

class TopTitlesPostPage(TitlePost):
    hello = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
        return self.hello

class NewTitlesPostPage(TitlePost):
    hello = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
        return self.hello

rawDescription: Django Inheriting from classes

description: Django Inheriting from classes


code:
from calculations import calculate_from_input

calculated_data = calculate_from_input("A.txt")  # Then, you have the data ready to use in your program.

rawDescription: How to run a bat file from Python 3.3.2

description: Run a bat file from Python 3.3.2


code:
...
while self.track:
    start = time.time()
    # Do things here
    sleep_time = start-time.time() + 1
    if sleep_time > 0:
        time.sleep(sleep_time)

rawDescription: Periodic Callback from Thread in Python

description: Periodic Callback from Thread in Python


rawDescription: Most efficient way to change all items in a sublist to a string?


code:
def foo(r):
    for i in r:
        do_something()

for x in xrange(20):
    foo( xrange(x) )

rawDescription: What is a nested for loop?

description: What is a nested for loop


code:
max(days_dictionary, key=days_dictionary.get)
[days_dictionary.get(k, 0) for k in days_week]

rawDescription: Tuple of string and list

description: Tuple of string and list


code: leg.append((dots, line))

rawDescription: Messing labels colors in matplotlib

description: Messing labels colors in matplotlib


code:
@app.route('/oer/api/v1.0/getType/', methods = ['GET'])
def getType():

    # Prepare a dictionary object to hold the result of any processing
    result = []  # create a list instead of dict

    # Get hold of DB connection
    db_connection = getDbConnection()
    db = db_connection['OER']
    # Extract all records passed for the paramater that matches "Type": ie MOOC
    oerType = request.args.get("oerType");
    # test to see that there is something in the string if so try to get a record
    # Not doing this test yet lets get it working with a known record first

    for d in db.oer_records.find({"Type":oerType}):
        result.append(make_public_page(d))  # append to the list of dicts

    return jsonify(items=result)

rawDescription: pulling multiple records from mongo using flask and python

description: Pulling multiple records from mongo using flask and python


code: new_val = old_dest * old_source / 255

rawDescription: Pygame and blitting: white on white = gray?


rawDescription: How can I encode and decode percent-encoded (URL encoded) strings in Python?

description: Encode and decode percent-encoded (URL encoded) strings in Python


code: import pandas

rawDescription: Is there any way to automatic detect required modules and packages in my own python project


code:
from django.utils.log import NullHandler
tracer = logging.getLogger('elasticsearch.trace')
tracer.setLevel(logging.INFO)
tracer.addHandler(NullHandler())

rawDescription: No handlers could be found for logger "elasticsearch.trace"


code: book_form = BookForm() # This will create a new book

rawDescription: django form dropdown list of stored models

description: Django form dropdown list of stored models


code:
p = sub.Popen(['ffprobe', fname], stdout=sub.PIPE, stderr=sub.PIPE)
stdout, stderr = p.communicate()

rawDescription: Subprocess.communicate prints newline to standard output


rawDescription: Python: dividing a list into chunks with varying size


code:
df2.index = np.random.permutation(df2.index)
df1.index
df2.index

rawDescription: When I shuffle a copy of a DataFrame, why the original DataFrame is also shuffled?


code:
with app.test_client() as c:
    r = c.post('/login', data={...})
    self.assertEqual(current_user.email, '...')

description: Flask-Login is_authenticated inconsistency


code:
from collections import Counter

files = dict() # this may be better as a list, tbh

table = str.maketrans('','',string.punctuation)

for file in glob.glob("*.txt"):
    with open(file) as f:
        word_count = Counter()
        for line in f:
            word_count += Counter([word.lower() for word in line.translate(table) if
                                  word not in noise_words_set])
    files[file] = word_count # if list: files.append(word_count)

rawDescription: List of dictionaries - tracking words frequency per file


code:
converter = {units.m: my_mile/Rational('1609.344'),
             units.s: my_hour/Rational('3600')}

rawDescription: SymPy: How to return an expression in terms of other expression(s)?


code: im = QImage(self.canvas.buffer_rgba())

rawDescription: Python - matplotlib - PyQT: Copy image to clipboard


code:
class Portfolio(models.Model):
    assets = models.ManyToManyField("Asset")

rawDescription: Django 1.6 ORM Joins

description: Django 1.6 ORM Joins


code:
def nested_keys(d):
    yield d.keys()
    for value in d.values():
        if isinstance(value, dict):
            for res in nested_keys(value):
                yield res

rawDescription: python get all keys in subdictorionaries

description: Python get all keys in subdictorionaries


rawDescription: find the index of a boolean array whose values are true

description: Find the index of a boolean array whose values are true


code: f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))

rawDescription: Writing nicely formatted text in Python

description: Writing nicely formatted text in Python


code:
a_idx = np.searchsorted(out_id, a[:,0], side='left')
b_idx = np.searchsorted(out_id, b[:,0], side='left')

rawDescription: Updating a NumPy array with another

description: Updating a NumPy array with another


code:
from instant import inline
c_code = """
    [ ... some c code ... ] //see the below page for a more complete example.
"""
c_func = inline(c_code)

rawDescription: Pass many pieces of data from Python to C program


code:
(session.query(Person.name, Assignment.jobId, Assignment.LocID)
    .filter(Assignment.person_id==Person.person_id)
    .filter(sa.sql.functions.now().between(Person.start, Person.end))
    .filter(sa.sql.functions.now().between(Assignment.start, Assignment.end))
)

rawDescription: Can SQL Alchemy and Pyramid handle a date effective scenario


code:
print(sorted(names, key = natural_keys))
# ['IMG0.png', 'img1.png', 'img2.png', 'IMG3.png', 'img10.png', 'img12.png']

rawDescription: python equivalent to php natcasesort

description: Python equivalent to php natcasesort


code:
image_cache = {}
def get_image(key):
  if not key in image_cache:
    image_cache[key] = pygame.image.load(key)
  return image_cache[key]

rawDescription: Pre-loading images pygame

description: Pre-loading images pygame


code:
f = CachedFileObject(cache_dir="/your/tmp/dir")
f.open("/path/to/remote/file")
# ..your f.read()'s here..
f.close()

rawDescription: (locally) cached file object in Python

description: (locally) cached file object in Python


rawDescription: NLTK: can I add terminal to grammar that is already generated


code:
m.assert_has_calls([call.m0(), call.m1()])
m.assert_has_calls([call.m1(), call.m0()])

rawDescription: Python Unit Testing with two mock objects, how to verify call-order?


rawDescription: Python set literals didn't work on numpy unique array


code: l.extend(t + t2)

rawDescription: Add all elements of an iterable to list

description: Add all elements of an iterable to list


code:
ln = 127 # lines start at 0 here
tlc = 0

for commit, lines in repo.blame('HEAD', filepath):
    if tlc <= ln < (tlc + len(lines)):
         print(commit)
    tlc += len(lines)

rawDescription: How to use git blame in GitPython?

description: Use git blame in GitPython


code:
p = dict((node, length) for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
     if length < 5)

rawDescription: Networkx Random Geometric Graph limit nodes within radius r


rawDescription: Round floats down in Python to keep one non-zero decimal only


code:
Solution
df.stack().idxmin()

('b', 'B')

rawDescription: Find location of specific value in dataframe of distances


code:
mylist = [12, 34, "FR", "Something", "SO"]
[i for i in mylist if i in ('FR', 'SO')]

rawDescription: Filtering though a list (Python)

description: Filtering though a list (Python)


rawDescription: Pandas Left Merge / Join not Resulting in what is expected for left join


code:
conds = [
     lambda: condition_1,
     lambda: conds[0]() or condition_2,
     lambda: conds[1]() or condition_3
]

rawDescription: Have extra while loop conditions ... based on a condition?


code:
def _apply_filter(self, fn=lambda ngram, freq: False):
    """Generic filter removes ngrams from the frequency distribution
    if the function returns True when passed an ngram tuple.
    """
    tmp_ngram = FreqDist()
    for ngram, freq in iteritems(self.ngram_fd):
        if not fn(ngram, freq):
            tmp_ngram[ngram] = freq
    self.ngram_fd = tmp_ngram

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
# Sort input array test w.r.t. first column that are IDs
test_sorted = test[test[:,0].argsort()]

# Convert the string IDs to numeric IDs
_,numeric_ID = np.unique(test_sorted[:,0],return_inverse=True)

# Get the indices where shifts (IDs change) occur
_,cut_idx = np.unique(numeric_ID,return_index=True)

# Use the indices to split the input array into sub-arrays with common IDs
out = np.split(test_sorted,cut_idx)[1:]

rawDescription: Fastest way to group by ID for a really big numpy array


code:
url(r'^(.+)-(.+)-(.+)/$', songs.dj_song, name='dj_song'),
url(r'^(.+)-(.+)-(.+)/$', songs.trending_song, name='trending_song'),

rawDescription: Incorrect Django URL pattern match for 2 views with the same URL structure?


code:
foo = Foo()
foo.bar = 'something'  # note case

rawDescription: Add attribute to python class

description: Add attribute to python class


code:
input = open("/path/to/input-file", "r")
output = open("/path/to/output-file", "wb")
output.writelines(decode(input))
output.close()
input.close()

rawDescription: Unescape/unquote binary strings in (extended) url encoding in python


rawDescription: Removing duplicate element from a list and the element itself


rawDescription: Python : Removing a List from List of List?


rawDescription: Python append list in loop

description: Python append list in loop


code:
def add_items(cls):
    cls.foo = "bar"
    return cls

@add_items
class A(object):
    pass

rawDescription: Write attribute to scope above current one


code:
def verts_to_bbox(verts):
    xs = [v[0] for v in verts]
    ys = [v[1] for v in verts]
    zs = [v[2] for v in verts]
    return (min(xs), max(xs), min(ys), max(ys), min(zs), max(zs))

rawDescription: simple python algorithm needed in finding bounding box of meshes from an OBJ file

description: Simple python algorithm needed in finding bounding box of meshes from an OBJ file


code:
new_transform = offset_copy(ax.transData, fig=fig,
                            x = 0.05, y=0.10, units='inches')

rawDescription: Matplotlib: Is it possible to create an new axis with a given y-offset, without creating subplot?


code: thread = threading.Thread(target = server.serve_forever)

rawDescription: SimpleHTTPServer launched as a thread: does not daemonize


code:
def format_float(value, ndigits):
    sign = ''
    if value < 0:
        value = abs(value)
        sign = '-'

    if value >= 1:
        j = min(i-1 for i in range(ndigits+1) if value >= 10 ** (ndigits - i))
        return '{}{:.0{num_digits}f}'.format(sign, value, num_digits=max(0,j))
    s = '{:.17f}'.format(value).rstrip('0')
    _, dec_part = s.split('.')
    if not dec_part:
        # Happens only with 0.0
        return '0'
    if len(dec_part) < ndigits or set(dec_part[:ndigits]) != {'0'}:
        # truncate the decimal representation
        dec_part = dec_part.ljust(ndigits, '0')[:ndigits]
    elif len(dec_part) > ndigits:
        # too small. Just find the first decimal place
        for i, char in enumerate(dec_part):
            if char != '0':
                dec_part = dec_part[:i+1]
                break
    return '{}{}.{}'.format(sign, 0, dec_part)

rawDescription: Decimal formatting based on number of digits in integer and decimal parts


rawDescription: how to pandas parse json that was previously saved

description: Pandas parse json that was previously saved


rawDescription: How do I extract the labels from a MultiIndex?

description: Extract the labels from a MultiIndex


code:
from itertools import groupby

data = """0.0 99.13 0.11
0.5 19.67 0.59
0.5 22.23 1.22
1.0 9.67  0.08""".split('\n')

result = [list(j) for i, j in groupby(data, lambda x: x.split(' ', 1)[0])]

files_num = 0
for e in result:
    files_num = max(files_num, len(e))

for i in range(files_num):
    with open('{}.txt'.format(i), 'w+') as f:
        for line in result:
            min_index = min(i, len(line)-1)
            f.write('{}\n'.format(line[min_index]))

rawDescription: Using duplicates to create different text files


code:
uniques_dict = {}

for record in base:
    key, values = record[1], record[2:]
    for unique in set(values):
        uniques_dict.setdefault(unique, set()).add(key)

rawDescription: Dictionary from associations found in list of lists (performance issue)


code:
def empty(shape):
    if len(shape) == 1:
        return [[] for i in xrange(shape[0])]
    items = shape[0]
    newshape = shape[1:]
    sublist = empty(newshape)
    return [sublist for i in xrange(items)]

rawDescription: Initialize empty list with same shape as array


rawDescription: Numpy Histogram | Use one dimension to match bin, and another for the actual frequency


code:
with open('/tmp/test.csv','w') as f:
    writer=csv.writer(f)
    writer.writerow(['year', 'date']+['draw{i}'.format(i=i) for i in range(1,1001)])
    for yeardate,draws in sorted(draw_sums.items()):
        writer.writerow(list(yeardate)+draws.tolist())

rawDescription: Summing Arrays by Characteristics in Python


rawDescription: Sort a Matrix by row preserving the columns


code:
data = '''\
2 3 4 5 6 3
1 2 2 4 5 5
1 2 2 2 2 4
'''.splitlines()
[int(x) for line in data for x in line.split()]
[[int(i) for i in line.split()] for line in data]

rawDescription: list comprehension replace for loop in 2D matrix

description: List comprehension replace for loop in 2D matrix


rawDescription: How to compare words in two lists according to same order in python?(I have def a function)

description: Compare words in two lists according to same order in python?(I have def a function)


code:
mask = b > a[..., -1:]
index = np.argmax(mask, axis=-1)

rawDescription: Python/Scipy: Find "bounded" min/max of a matrix


code:
def recursive_me(mystring):
    if mystring: # recursive case
        return int(mystring[0]) + recursive_me(mystring[1:])
    else:        # base case
        return 0

rawDescription: Python recursive function that retain variable values


code:
def decorator(setup, teardown):
    def decorate_function(test):
        def wrapper(self):
            setup(self)
            test(self)
            teardown(self)
        return wrapper
    return decorate_function

class run():
    def setup(self):
        print("in setup")
    def teardown(self):
        print("in teardown")
    @decorator(setup, teardown)
    def test(self):
        print("in test")

run().test()

rawDescription: Python decorators calling functions in different classes


code:
import thirdpartymodule_a
import thirdpartymodule_b

def new_init(self):
    self.a = 43

thirdpartymodule_a.SomeClass.__init__ = new_init

thirdpartymodule_b.dosomething()

rawDescription: Monkey patching a class in another module in Python


code:
def before_insert(resource_name, documents):
    for document in documents:
        document['field'] = 'value'

app = Eve()
app.on_insert_myresource += before_insert

app.run()

rawDescription: Python-Eve: Use Pre-Request Event Hooks to modify data before inserting to DB


code:
result = elements[:]  # copy
del result[n]

rawDescription: How to get all the elements in the list without an element at a specific index in python?

description: Get all the elements in the list without an element at a specific index in python


code:
class UserProfile(models.Model):
    countries = models.ManyToManyField(Country)

rawDescription: Country-based Super User Access

description: Country-based Super User Access