code:
class quad:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __call__(x):
        return self.a * x**2 + self.b * x + self.c

q = quad(p, q, r)
q(x)

rawDescription: Should I use a class? (Python)

description: Should I use a class? (Python)


code:
for i in range(3):
    f(i)

rawDescription: python map vs itertools.map: Make the iterator version behave like the former

description: Python map vs itertools.map: Make the iterator version behave like the former


code:
import numpy as np
from scipy import sparse

x = sparse.rand(10000, 10000, format='coo')

rawDescription: Scipy Handling of Large COO matrix

description: Scipy Handling of Large COO matrix


rawDescription: Array within an array?

description: Array within an array


rawDescription: Pandas Dataframe count availability of string in a list


code:
def print_something():
    print("print something")

rawDescription: Mocking print but allow using it in tests


code:
@register.inclusion_tag('checkbox.html')
def my_checkboxes(request, items):
    return {"items": [{'id': i.id, 'checked': request.POST[str(i.id)] == 'on'} for i in items]}

rawDescription: Mark checkboxes in rendered HTML

description: Mark checkboxes in rendered HTML


code:
line = "4 0 2837 9323 ..."
line = [(int(n), dict()) for n in line.split()]

rawDescription: Python - how to store lines of numerical values?


code:
ZoneSubStage.objects.filter(substage__stage=stage_instance).aggregate(Sum('value'))
# This will return {'value__sum': 90}

rawDescription: django models sum of classes fiels

description: Django models sum of classes fiels


code:
conn = psycopg1.connect(database=cr.dbname,  user=dbuser,  password=dbpass)
cur = conn.cursor()

rawDescription: [Openerp]How to make SQL Query with another database user from python code?


code:
# UNTESTED
import requests
import csv

# Connect to the web server.
response = requests.get("https:://domain.com/file_maker.pl?param1=12345")

# Store the data
with open('outfile', 'w') as outfile:
    outfile.write(response.content)

rawDescription: How to download a file (perl cgi backend) using python requests

description: Download a file (perl cgi backend) using python requests


rawDescription: Python 2 and 3 compatible way of hiding a decorator from stacktrace


code:
import numpy as np

# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:,None]
B_mB = B - B.mean()

# Sum of squares across rows
ssA = (A_mA**2).sum(1)
ssB = (B_mB**2).sum()

# Finally get corr coeff
out = np.dot(A_mA,B_mB.T).ravel()/np.sqrt(ssA*ssB)
# OR out = np.einsum('ij,j->i',A_mA,B_mB)/np.sqrt(ssA*ssB)

rawDescription: Correlate a single time series with a large number of time series


code:
def inverse(string, left_string=None):
    from sympy import solve, Symbol, sympify
    string = '-' + string
    e = sympify(string.replace('=','+'))
    if left_string:
        ans = left_string + ' = ' + str(solve(e, sympify(left_string))[0])
    else:
        left = sympify(string.split('=')[0].strip().replace('-',''))
        symbols = e.free_symbols
        symbols.remove( left )
        right = list(symbols)[0]
        ans = str(right) + ' = ' + str(solve(e, right)[0])
    return ans

rawDescription: Algorithm to invert strings of algebraic expressions in Python


rawDescription: How to call a distant shell script from a python file?

description: Call a distant shell script from a python file


code:
lines = []
for line in filehandle:
    lines.append(line)

rawDescription: Open URL and place it to a string

description: Open URL and place it to a string


code: [u'acuerdo', u'aj', u'ajudou', u'al', u'alex', u'algo', u'alpsk\xfdmi', u'alpy', u'andaba', u'andrea', u'ao', u'apresenta', u'as', u'bien', u'bl\xedzko', u'buscando', u'come\xe7o', u'como', u'con', u'conseguido', u'da', u'de', u'decepcionantes', u'deti', u'dificuldades', u'dif\xedcil', u'distancia', u'do', u'doprinese', u'druh', u'd\xe1', u'ela', u'encontrar', u'enfrentar', u'es', u'est\xe1', u'eulex', u'excusa', u'fama', u'foi', u'for\xe7as', u'furiosa', u'golf', u'golfistami', u'golfov\xfdch', u'guasch', u'ha', u'hotelmi', u'hra\u0165', u'ide', u'ihr\xedsk', u'incident', u'intranspon\xedveis', u'in\xedcio', u'in\xfd', u'ispit', u'istragu', u'izbijanju', u'ja\u010danju', u'je', u'jedan', u'jo\u0161', u'kapaciteta', u'kde', u'kombin\xe1cie', u'komplex', u'kon\u010diarmi', u'kosova', u'la', u'lado', u'lequio', u'lete', u'llevar', u'lo', u'longo', u'ly\u017eova\u0165', u'mais', u'man\u017eelky', u'mas', u'me', u'mesmo', u'meu', u'minha', u'misije', u'mo\u017enos\u0165ami', u'muy', u'm\xe1s', u'm\xe3e', u'na', u'nada', u'nad\u0161en\xfdmi', u'nasilja', u'negativas', u'nie', u'nieko\u013ek\xfdch', u'no', u'obaviti', u'obe\u0107ao', u'para', u'parecem', u'parecer', u'pod', u'pone', u'pon\xfakaj\xfa', u'por', u'potrebuj\xfa', u'po\u0161to', u'prava', u'predstavlja', u'pri', u'prova\xe7\xf5es', u'pro\u0161losedmi\u010dnom', u'punham', u'qual', u'qualquer', u'que', u'quem', u'rak\xfaske', u'relaci\xf3n', u'rezortov', u'sa', u'sebe', u'sempre', u'situa\xe7\xf5es', u'sjeveru', u'spojen\xfdch', u'suplantar', u's\xfa', u'taj', u'tak', u'talianske', u'teve', u'tive', u'todas', u'tr\xe1venia', u'una', u've\u013ek\xfd', u'vida', u'visto', u'vladavine', u'vo', u'vo\u013en\xe9ho', u'vysok\xfdmi', u'vy\u017eitia', u'v\xe4\u010d\u0161ine', u'v\u017edy', u'ya', u'zauj\xedmav\xe9', u'zime', u'\u0107e', u'\u010dasu', u'\u010di', u'\u010fal\u0161\xedmi', u'\u0161vaj\u010diarske']

rawDescription: How to vectorize bigrams with the hashing-trick in scikit-learn?

description: Vectorize bigrams with the hashing-trick in scikit-learn


code:
strs='foobar'
le=len(strs)
strs[-1:0:-1]      #the first -1 is equivalent to len(strs)-1
strs[le-1:0:-1]

rawDescription: What does extended slice syntax actually do for negative steps?


code:
def fibo(a=-1,b=1,upto=4000000):
    while a+b<upto:
        a,b = b,a+b
        yield b

rawDescription: Python program to find fibonacci series. More Pythonic way


code:
df1['D'] = g.size()  # unfortunately this doesn't play nice with as_index=False
df1.reset_index()

rawDescription: python pandas groupby() result

description: Python pandas groupby() result


code:
if __name__ == "__main__":
    main(sys.argv[2:])

rawDescription: give parameters to function and load the function the right way

description: Give parameters to function and load the function the right way


code:
def transpose(lists):
   if not lists: return []
   return map(lambda *row: list(row), *lists)

rawDescription: How can I append whole columns to a table (list of lists) in python?

description: Append whole columns to a table (list of lists) in python


code:
with open('file1', 'r') as f1:
    data1 = f1.read().splitlines()
with open('file2', 'r') as f2:
    data2 = f2.read().splitlines()

varlists1 = [[int(x) for x in y.split(', ')] for y in data1] # or float(x) ...
varlists2 = [[int(x) for x in y.split(', ')] for y in data2]

rawDescription: reading in files line by line and storing the content of each line in a list for further processing

description: Reading in files line by line and storing the content of each line in a list for further processing


code:
expected = {
    'l1': ['abc', 'def', 'ghi', 'jkl'],
    'l2': ['abc', 'ghi', 'jkl', 'mno']
}
set(f for files in expected.itervalues() for f in files)

rawDescription: python set comprehension made out of different lists

description: Python set comprehension made out of different lists


code:
def __lt__(self, other):
    return cmp(self.number, other.number)

rawDescription: sorting list of objects python

description: Sorting list of objects python


rawDescription: Assign value to an individual cell in a two dimensional python array


code:
from selenium import webdriver
dr = webdriver.PhantomJS()
dr.get("http://finance.yahoo.com/options/lists/?mod_id=mediaquotesoptions&tab=tab2&rcnt=50")
table = dr.find_element_by_css_selector("div.yfi-panel-container.tabview-content")
headers = ",".join([th.text for th in table.find_elements_by_xpath(".//th/span")])
print(headers)
for row in table.find_elements_by_xpath(".//tr"):
    print(",".join([td.text.replace("\n","") for td in row.find_elements_by_xpath(".//td")]))

rawDescription: unable to extract table data using beautifulsoup

description: Unable to extract table data using beautifulsoup


rawDescription: Scaping a table using mechanize & beautiful when some rows contain additional formatting


code: sorted(data, key=lambda elem: elem[3])

rawDescription: Built-in sorted() function in Python

description: Built-in sorted() function in Python


code:
sq = [['welcome'], ['we', 'are'], ['the', 'champions']]
sl = [['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did'], ['are', 'time', 'to', 'do', 'the', 'champions', 'while', 'am']]
_flat = sum(sq, [])
test = [[1 if item in _flat else 0 for item in nl] for nl in sl]

rawDescription: Taking two lists and comparing for similarities


code: HourFormSet = modelformset_factory(Hour, extra=5, exclude=('user',))

rawDescription: Django Formset: Passing a parameter in each form instance


code:
class Callers(models.Model):
    body = models.CharField()
    from_number = models.CharField()
    last_question = models.IntegerField(default=0) # if you have more than 10 question then I guess using IntegerField is better here

rawDescription: Checking previous SMS senders Django/Twilio


code:
hdf = aggdf.groupby(['a','b']).size()
hdf

rawDescription: Create Contour Plot from Pandas Groupby Dataframe


code:
for lst in (lsta,lstb,lstc):
    print( ' '.join(  '{}'.format(k) for k in lst  ) )

rawDescription: common lisp like format directive to print lists

description: Common lisp like format directive to print lists


rawDescription: Sum while in Python?

description: Sum while in Python


code:
df['logSales'] = np.log(df['Sales'])
df

rawDescription: Python Pandas operate on row

description: Python Pandas operate on row


code:
from .custom import MyBlueprint

admin = MyBlueprint('admin', __name__, url_prefix='/admin')
admin.set_data({'color': '#a569bd', 'enabled': true})

# all the blueprint's routes
...

rawDescription: Flask Blueprint Initialization - Initializing some global variables


code:
import ctypes
dll = ctyes.cdll.thedll
object_from_id = dll.PyObjectFromAdress
object_from_id.restype = ctypes.py_object()

rawDescription: Is it possible to access an object via memory address?


rawDescription: Help using *args in tuple matching Python function


code:
try:
    translated = translation[fruit]
except KeyError:
    print("Unknown translation for %s" % fruit)

rawDescription: Conditional renaming of strings in Python


rawDescription: Python - How to read lines of lists in a text file directly into lists in python


code:
from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

rawDescription: Python sets are not json serializable

description: Python sets are not json serializable


code:
def foo(a, b):
    x = 3
    return locals()
foo(1, 2)

rawDescription: packing named arguments into a dict

description: Packing named arguments into a dict


rawDescription: Python Numpy recarray sort bidirectional


code:
class Page(models.Model):
    test = models.ForeginKey(Test)

    def __unicode__(self):
        return "Page{0} - Test{1}".format(obj.pk, obj.test.pk)

rawDescription: Django admin foreign key dropdown with custom value


code:
df = DataFrame(dict(time = x))
df

rawDescription: Python pandas change duplicate timestamp to unique


rawDescription: Slicing through a grid in a spiral motion, returning xMin, xMax, yMin, yMax for each slice


rawDescription: Convert pandas df multi index to columns


code:
class Mine(unicode):
    #
    def __init__(self, *args, **kwargs):
        super(Mine, self).__init__(*args, **kwargs)
    #
    def __setattr__(self, attr, value):
        try:
            super(Mine, self).__setattr__(attr, value)
        except AttributeError:
            self.__dict__[attr] = value
    #
    def __getattr__(self, attr):
        try:
            super(Mine, self).__getattr__(attr)
        except AttributeError:
            try:
                return self.__dict__[attr]
            except KeyError:
                raise AttributeError

    def __getitem__(self, item):
        obj = Mine(super(Mine, self).__getitem__(item))
        obj.__dict__ = self.__dict__
        return obj

rawDescription: How can I set and retain attributes on characters in a Python 2 string?

description: Set and retain attributes on characters in a Python 2 string


code: filter(lambda x: x >= 0, list2)

rawDescription: Difference between normal looping of list and using slice?


code:
def function_definition():
    pass
function_definition = decorator_expression(function_definition)

rawDescription: How would one decorate an inherited method in the child class?


code:
list("Pla\\net")
list(r"Pla\net")

rawDescription: How is this weird behaviour of escaping special characters explained?


code:
def factorall(x):
    return all(not x % num for num in nums)

rawDescription: Trying to check a condition for every element in a list of integers


code:
try:
    for num, image in enumerate(vid.iter_data()):
        if num % int(vid._meta['fps']):
            continue
        else:
            fig = pylab.figure()
            pylab.imshow(image)
            timestamp = float(num)/ vid.get_meta_data()['fps']
            print(timestamp)
            fig.suptitle('image #{}, timestamp={}'.format(num, timestamp), fontsize=20)
            pylab.show()
except RuntimeError:
    print('something went wrong')

rawDescription: How to read mp4 video to be processed by scikit-image?

description: Read mp4 video to be processed by scikit-image


rawDescription: Getting method parameter names in python


code:
def a(func):
    def x(*args, **kwargs):
            print(args, kwargs)
            func(*args, **kwargs)
    return x
@a
def b(y):
    print("In b", y)
b("Hello")

rawDescription: Create a decorator that has access to both the arguments and function


rawDescription: merge number by using "-" (python)

description: Merge number by using "-" (python)


code:
self.TeamList = myComboBox(self.myvbfrm,(200,20),(100,50))
self.TeamList.Bind(wx.EVT_TEXT, self.onUpdate)
self.EmpList = myComboBox(self.myvbfrm,(200,50),(100,50))

rawDescription: Adding items to wxpython combobox...?

description: Adding items to wxpython combobox...


code:
for i, student in enumerate(student_list):
    print_gender(student)

rawDescription: Is this code simplified? Should I use more functions?


code:
table_name, extension = os.path.splitext("movies.csv")
table_name
extension

rawDescription: Python string.strip stripping too many characters


code:
xtab = (df.set_index(['XY', 'UV', 'BC'])
          .unstack(level='BC')['Val']
          .reset_index())

rawDescription: Pandas dataframe - transform column values into individual columns


code:
def extract_values(f):
    lines = f.readlines()
    for line_number, line in enumerate(lines):
        if some_condition(line):
            data = lines[line_number:]
            break

rawDescription: Extract from current position until end of file


code: bool("e")

rawDescription: Code not working properly

description: Code not working properly


rawDescription: How are numeric and string variables determined in SPSS?


code:
FooClass.method = my_method
foo_instance.method = my_method

rawDescription: In Python can you do prototyping of string functions like in JavaScript


code:
htmlize(string)
htmlize(string2)

rawDescription: Form an unordered list with regex

description: Form an unordered list with regex


code:
from itertools import groupby
print(tuple((e, idx) for _, group in groupby(l) for idx, e in enumerate(group)))

rawDescription: Append an incremental counter to duplicate values in list


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

arr=np.genfromtxt('foo.csv',delimiter=',')
plt.plot(arr[:,0],arr[:,1],'b-')
plt.show()

rawDescription: How can I duplicate this simple matlab plot functionality with mathplotlib?

description: Duplicate this simple matlab plot functionality with mathplotlib


code:
from contextlib import contextmanager

@contextmanager
def flag_regexen(flag):
    import re
    re.my_compile = re.compile
    re.compile = lambda pattern, flags: re.my_compile(pattern, flags | flag)
    yield
    re.compile = re.my_compile

rawDescription: Using a global flag for python RegExp compile


code: df

rawDescription: change column values in CSV using python

description: Change column values in CSV using python


code:
import csv

with open('C:/test/test.csv','r') as csvinput:
    with open('C:/test/output.csv', 'w') as csvoutput:
        writer = csv.writer(csvoutput, lineterminator='\n')
        reader = csv.reader(csvinput)

        all = []
        row = next(reader)
        row.append('Berry')
        all.append(row)

        for row in reader:
            row.append(row[0])
            all.append(row)

        writer.writerows(all)

rawDescription: How to add a new column to a CSV file using Python?

description: Add a new column to a CSV file using Python


code:
name = "testing_kip-win332"

if name.startswith("testing"):
    print ("Uninstalling" + product.Name + "...")
    result = product.Uninstall()

rawDescription: How to specify python regular expression that starts with "testing" without declaring the content variable?

description: Specify python regular expression that starts with "testing" without declaring the content variable


code:
def A(dx, dy):
  return math.atan2(dy, dx) * 180 / math.pi

rawDescription: python - 2 math questions

description: Python - 2 math questions


code:
from itertools import groupby

a = ['AA', 'BB', 'C', 'D']
res = [''.join((str(z) for z in y)) for x, y in groupby(a, key = lambda x: len(x) == 2)]

rawDescription: Joining Subsequent List Elements - Python


code:
def can_be_represented(num, den):
    f = Fraction(num, den)
    return f.denominator & (f.denominator - 1) == 0

rawDescription: How to determine if a decimal fraction can be represented exactly as Python float?

description: Determine if a decimal fraction can be represented exactly as Python float


code:
import weakref, collections
def createLRUCache(factory, maxlen=64):
    weak = weakref.WeakValueDictionary()
    strong = collections.deque(maxlen=maxlen)

    notFound = object()
    def fetch(key):
        value = weak.get(key, notFound)
        if value is notFound:
            weak[key] = value = factory(key)
        strong.append(value)
        return value
    return fetch

rawDescription: Problems with the GC when using a WeakValueDictionary for caches


rawDescription: How can I check numbered lists that matches current n value?

description: Check numbered lists that matches current n value


rawDescription: Combining 2 lists in strange way

description: Combining 2 lists in strange way


code:
class PostSearchForm(SearchForm):
    lan = forms.CharField(required=False)

    def search(self):
        sqs = super(PostSearchForm, self).search()
        if not self.is_valid():
            return self.no_query_found()
        if self.cleaned_data.get('lan'):
            sqs = sqs.filter(lan=self.cleaned_data['lan'])
        return sqs

rawDescription: Django how to get haystack working with django-hvad


rawDescription: How do I multiply integers within a nested list?

description: Multiply integers within a nested list


code:
import requests
from bs4 import BeautifulSoup

url = "https://www.crowdcube.com/investments?sort_by=0&q=&hof=1&i1=0&i2=0&i3=0&i4=0&sort_by=7"

def parse(so):
    return {'title': soup.title.text, 'description': so.find("div", {"class": "pitch-tabs"}).p.text,
            'target': so.find("div",{"class":"cc-pitch__stats clearfix"}).dd.text,
            'raised': so.find("div", {"class": "cc-pitch__raised"}).b.text,
            'category': " ".join(so.find("li",{"class":"sectors"}).span.text.split()),
            "title": so.title.text}

req = requests.get(url)

soup = BeautifulSoup(req.content)

links = {h.a["href"] for h in soup.find_all("h2", {"class": "pitch__title"})}

for link in links:
    print(link)
    soup = BeautifulSoup(requests.get(link).content)
    print(parse(soup))

rawDescription: Web scraping multiple pages with Beautiful Soup


code:
errorIndication, errorStatus, errorIndex, \
varBindTable = cmdgen.CommandGenerator().bulkCmd(
            cmdgen.CommunityData('test-agent', 'public'),
            cmdgen.UdpTransportTarget(('localhost', 161)),
            0,
            25,
            (1,3,6,1,2,1,4,20), # ipAddrTable
            (1,3,6,1,2,1,4,21), # ipRouteTable
        )

rawDescription: Python SNMP GetBulk - Multiple OIDs

description: Python SNMP GetBulk - Multiple OIDs


code:
#! /usr/bin/python3.2

import sys

if __name__ == '__main__':
    if len (sys.argv) < 4:
        print ( ['Usage: myscript [Dir] [Old] [New]',
            'Please enter Old and New',
            'Please enter New'] [len (sys.argv) - 1] )

rawDescription: Python 3: test command line arguments

description: Python 3: test command line arguments


rawDescription: Counting matching dictionaries in python


code:
import numpy
import random
import struct

data = struct.pack('i'*100, *[random.randint(0, 1000000) for _ in range(100)])

numpy.fromstring(data, dtype="int32")
#>>> array([642029, 967046, 599565, ...etc], dtype=int32)

rawDescription: Cython fast conversion of binary string to int array


code: bf = bytes(bf, 'UTF-8')

rawDescription: python struct "unpack requires a bytes object of length 8" while converting binay to float

description: Python struct "unpack requires a bytes object of length 8" while converting binay to float


code:
import pandas as pd
a = pd.to_timedelta('0 days 00:43:00.000000000',unit='s')
a
a.total_seconds()

rawDescription: Extract two dates, result in seconds (pandas)


code:
for field in fields:
    return field.clear()

rawDescription: PySide: how to clean `QLineEdit` field with a button click?


code:
class MyRedisWrapper(object):
    @gen.engine
    def set(self, key, value):
        yield tornado.gen.Task(t.set, key, value)

r = MyRedisWrapper()

class MyHandler(tornado.web.RequestHandler):
    def get(self):
        r.set('key', 'value') #It will work, but not sure about efficiency.

rawDescription: how to do asynchronous writes to redis in tornado

description: Do asynchronous writes to redis in tornado


code:
assert clans.is_functional(data_clan)

def record_in_range(rel):
    date_value = rel('col2').value  # .value extracts the raw literal from the Atom
    return date(2014, 1, 1) < date_value < date(2016, 1, 1)

rawDescription: Comparing date object in a Couplet between two dates


code:
self.typeFrame = tk.Frame(self.frame)
self.typeChoice = tk.StringVar(self.typeFrame)
self.typeChoice.set(None)

rawDescription: Getting Input from Radiobutton

description: Getting Input from Radiobutton


code:
import thread
import time

def dummy():
    time.sleep(1)

def main():
    for i in range(100):
        tid = thread.start_new_thread(dummy, ())
        #print 'created new thread %d' % tid

if __name__ == '__main__':
    main()

rawDescription: Python threading vs. multiprocessing in Linux


code:
keyword = 'Tormented Soul'
coords = lambda line: map(int, line('.ocrx_word').eq(0).attr('title').split()[1:])
result = [coords(line) for line in d('.ocr_line').items() if line.text().startswith(keyword)][0]

rawDescription: Find words in a file then grab the x,y coordinates next to the text


code: f = type(forms.Form)('MyForm', forms.Form, d)

rawDescription: Storing dynamic form in a model

description: Storing dynamic form in a model


code:
p_script = argv
p_user_name = argv
p_id = argv

rawDescription: python - parameters declaration ordering

description: Python - parameters declaration ordering


code:
import csv

reader = csv.reader(open("file.csv", "r"), delimiter=',')
data = [line for line in reader if 'DEFAULT' not in line]
print(data)

rawDescription: How do I put lines into a list from CSV using python

description: Put lines into a list from CSV using python


code:
def f():
    global foo
    print(foo)
    foo += 1

foo = 23
f()
print(foo)

rawDescription: Use a Variable in a Function Without Passing as an Argument


rawDescription: Use string format create a 2D list

description: Use string format create a 2D list


code: results = re.findall(r'(?<!:)\b\w+', string)

rawDescription: match all words not starting with ':' Python regex

description: Match all words not starting with ':' Python regex


rawDescription: generating permutations with repetitions in python

description: Generating permutations with repetitions in python


code:
import os
import trac.web.main

os.environ['TRAC_ENV'] = '/path/to/your/trac/env'

application = trac.web.main.dispatch_request

from flup.server.fcgi import WSGIServer
server = WSGIServer(application, bindAddress=("127.0.0.1", 9000), )
server.run()

rawDescription: How should I debug Trac plugins?

description: How should I debug Trac plugins


code:
from datetime import datetime
dt = datetime.strptime("2013-12-02 22:00:00", "%Y-%m-%d %H:%M:%S")
dt = dt.replace(tzinfo=FixedOffset(-8*60, "GMT+0800"))
dt.isoformat()

rawDescription: Get tz offset from sting

description: Get tz offset from sting


code:
from django.db.models import F

Model.objects.filter(some_col=F(kwargs.get('predicted_value')))

rawDescription: How to compare 2 columns of a table through dynamic querying

description: Compare 2 columns of a table through dynamic querying


code: out, err = p.communicate('104\nq\n')

rawDescription: Running .exe files with user arguments in python


code:
import unittest
from sst.actions import *
from sst import cases, config

#config.results_directory = "C:\Users\{me}\Desktop\Python-pip-SST\results"

go_to('https://www.google.com/')
assert_title_contains('Google')
#Main page is displayed
take_screenshot(filename='home_page.png',add_timestamp=True)

rawDescription: How do you set the results_directory in SST Python

description: Set the results_directory in SST Python


code:
f = open("filter_sequence.txt","w")       # The file to write to.

for sequence in sequence_list:
  if sequence[0] in all_titles:           # sequence[0] is the sequence title.
    write_string = str(sequence[0]) + ":\nSequence:" + str(sequence[1]) + "\n\n"
    f.write(write_string)                 # Write the string above.

f.close()                                 # Close the file.

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

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


rawDescription: addition of int and str

description: Addition of int and str


code: categories["cat1"] = [21, 78]

rawDescription: How to add to python dictionary without replacing

description: Add to python dictionary without replacing


code:
def is_summer_time(aware_dt):
    assert aware_dt.tzinfo is not None
    assert aware_dt.tzinfo.utcoffset(aware_dt) is not None
    return bool(aware_dt.dst())

rawDescription: How to determine if a timezone specific date in the past is daylight saving or not in python?

description: Determine if a timezone specific date in the past is daylight saving or not in python


rawDescription: Why does timedelta function return 0 seconds when datetimes are perfect number of days apart?


code: dd.groupby( dd.index.month ).mean()

rawDescription: Average of a groupby or a groupby of an average on a dataframe with duplicated indexes


code: Popen("curl www.vit.org/downloads/doc/tariff.doc | java -jar tika-app-1.3.jar --text >out_txt.txt", shell=True)

rawDescription: Running Java Application using Popen

description: Running Java Application using Popen


code:
theano.tensor.switch(cyclic_linear_activation < 0.0,
                     (cyclic_linear_activation % 1.0) + 1.0,
                     cyclic_linear_activation )

rawDescription: Is there an fmod in theano?

description: Is there an fmod in theano


code:
import csv

with open("database.txt", "r", newline="") as csvfile:
    csvreader = csv.reader(csvfile, delimiter='\t')
    print("Last Name \t Hours \t Wages")
    for row in csvreader:
        try:
            print('{}\t{}\t{}'.format(row[0], row[2], float(row[1])*float(row[2])))
        except ValueError:
            # Handle cases where the casting of row[1] and row[2] to float fails
            code
        except IndexError:
            # Handle cases where index is out of bounds
            code

rawDescription: Python: Need to get the product of two columns on each line of a text file


code:
x = linspace(0,1,100)
y = cos(x*8*pi)   # your array

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y, 'b',picker=10)

def onpick(event):

    if event.artist!=line:  #check that you clicked on the object you wanted
        return True
    if not len(event.ind):  #check the index is valid
        return True
    ind = event.ind[0]

    ax.plot(x[ind],y[ind],'ro')

    fig.canvas.draw()
    return True

fig.canvas.mpl_connect('pick_event', onpick)
fig.show()

rawDescription: Can matplotlib pick_event return array indeces rather than values or pixels?


code:
from collections import Counter
counters = defaultdict(lambda: count(1))
tally = Counter(inputlist)
[(n, next(counters[n])) if tally[n] > 1 else n for n in inputlist]

rawDescription: Find same elements in a list, and then change these elemens to tuple (f.e. 2 to (2,1))


code:
import json

# ... create matplotlib figure

json01 = json.dumps(mpld3.fig_to_dict(fig))

rawDescription: Display multiple mpld3 exports on a single HTML page


code:
class MyHttpAdapter(requests.adapters.HTTPAdapter):
    throttle = None

    def __init__(self, pool_connections=requests.adapters.DEFAULT_POOLSIZE,
                 pool_maxsize=requests.adapters.DEFAULT_POOLSIZE, max_retries=requests.adapters.DEFAULT_RETRIES,
                 pool_block=requests.adapters.DEFAULT_POOLBLOCK, burst_window=DEFAULT_BURST_WINDOW,
                 wait_window=DEFAULT_WAIT_WINDOW):
        self.throttle = BurstThrottle(pool_maxsize, burst_window, wait_window)
        super(MyHttpAdapter, self).__init__(pool_connections=pool_connections, pool_maxsize=pool_maxsize,
                                            max_retries=max_retries, pool_block=pool_block)

    def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
        request_successful = False
        response = None
        while not request_successful:
            wait_time = self.throttle.throttle()
            while wait_time > datetime.timedelta(0):
                gevent.sleep(wait_time.total_seconds(), ref=True)
                wait_time = self.throttle.throttle()

            response = super(MyHttpAdapter, self).send(request, stream=stream, timeout=timeout,
                                                       verify=verify, cert=cert, proxies=proxies)

            if response.status_code != 429:
                request_successful = True

        return response

rawDescription: Limiting/throttling the rate of HTTP requests in GRequests


code:
precision = tp / fp + tp
recall = tp / fn + tp

rawDescription: IOB Accuracy on NLTK named entity recognition


code:
z=np.empty((1,1),dtype=object)
z[0,0]=np.array([[item]], dtype=dt)
z

rawDescription: scipy and preserving mat file (.mat matlab data file) structure

description: Scipy and preserving mat file (.mat matlab data file) structure


code:
from utils.builtin import time

time.sleep(5)

rawDescription: python import package globally

description: Python import package globally


code:
import re

html = ... # your html goes here

telephone = re.search('Tel: ([+\d\s]+)', html).groups()[0]
fax = re.search('Fax: ([+\d\s]+)', html).groups()[0]
paragraphs = [line for line in html.split('\n') if line.startswith('<p>')]
address = '\n'.join([p.replace('<p>', '').replace('</p>', '')
                     for p in paragraphs[0:2]])

print(telephone)
print(fax)
print(address)

rawDescription: Parse HTML, set datas to variables

description: Parse HTML, set datas to variables


code:
def neighbors(matrix, row, col):
    for i in row-1, row, row+1:
        if i < 0 or i == len(matrix): continue
        for j in col-1, col, col+1:
            if j < 0 or j == len(matrix[i]): continue
            if i == row and j == col: continue
            yield matrix[i][j]

matrix = [[0,1,1,1,0,1], [1,1,1,0,0,1], [1,1,0,0,0,1], [1,1,1,1,1,1]]

for i, row in enumerate(matrix):
    for j, cell in enumerate(cell):
        for neighbor in neighbors(matrix, i, j):
            do_stuff(cell, neighbor)

rawDescription: Python - comparing elements of list with 'neighbour' elements


code:
class JSONDateTimeEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, datetime.datetime):
        return int(time.mktime(obj.timetuple()))
    elif isinstance(ojb, set):
        return list(obj)
    try:
        return json.JSONEncoder.default(self, obj)
    except:
        return str(obj)

rawDescription: Consolidating row data from DB into a list of dicts


rawDescription: Change Marker Style/Color in Python Probplot


code:
from operator import itemgetter

map(itemgetter(1), my_list)

rawDescription: Iterate over a list of tuples

description: Iterate over a list of tuples


code:
slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"])
riskNames = set(["enough", "pop", "final", "stress", "trade"])
d =  {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"}

for k,v in d.items():
    spl = v.split()
    if not slangNames.isdisjoint(spl) and not riskNames.isdisjoint(spl):
        print(k, v)

rawDescription: How to match words in 2 list against another string of words without sub-string matching in Python?

description: Match words in 2 list against another string of words without sub-string matching in Python


code:
s='[text], text, {text}, itextm'
import re
re.sub(r'([[{])[^\]}]*',r'\1replaced',s)

rawDescription: Replace the content in between using python regex


code: pages = re.compile(r'[\n\f](\d+)\n.*?(?=[\n\f](\d+)\n)', flags = re.DOTALL | re.MULTILINE)

rawDescription: Extract section names and starting pages from a text file


code:
sin(radians(12))
sin(radians(33))
# etc

rawDescription: How to offset random sine angles as a whole?

description: Offset random sine angles as a whole


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

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

description: Associate elements in a set with multiple dict entries


code:
def pgm2pil(fname):
    #
    # This method returns a PIL.Image.  Use pbm2numpy function above as a
    # guide.  If it can't load the image, it returns None.
    #
    pass

def wrapper(fname):
    pgm = pgm2pil(fname)

    if pgm is not None:
        return pgm
    return PIL.Image.open(fname)

#
# This is the line that "adds" the wrapper
#
PIL.Image.open = wrapper

rawDescription: How to write PIL image filter for plain pgm format?

description: Write PIL image filter for plain pgm format


code:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(metadata=metadata)

class TreeNode(Base):

    __tablename__ = 'tree'

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('tree.id'))
    name = Column(String(50), nullable=False)

    children = relationship('TreeNode',

                        # cascade deletions
                        cascade="all",

                        # many to one + adjacency list - remote_side
                        # is required to reference the 'remote'
                        # column in the join condition.
                        backref=backref("parent", remote_side='TreeNode.id'),

                        # children will be represented as a dictionary
                        # on the "name" attribute.
                        collection_class=attribute_mapped_collection('name'),
                    )

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

    def append(self, nodename):
        self.children[nodename] = TreeNode(nodename, parent=self)

    def __repr__(self):
        return "TreeNode(name=%r, id=%r, parent_id=%r)" % (
                    self.name,
                    self.id,
                    self.parent_id
                )

rawDescription: Creating a tree from self referential tables in SQLalchemy


code:
def debug(loggername):
    logger = logging.getLogger(loggername)
    def log_(enter_message, exit_message=None):
        def wrapper(f):
            def wrapped(*args, **kargs):
                logger.debug(enter_message)
                r = f(*args, **kargs)
                if exit_message:
                    logger.debug(exit_message)
                return r
            return wrapped
        return wrapper
    return log_

my_debug = debug('my.logger')

@my_debug('enter foo', 'exit foo')
def foo(a,b):
    return a+b

rawDescription: Python - Avoid passing logger reference between functions?


code:
xyarr = np.array(zip(x.flatten(),y.flatten()))
dfun = lambda p,t: [interp.griddata(xyarr,vx.flatten(),np.array([p]))[0], interp.griddata(xyarr,vy.flatten(),np.array([p]))[0]]

rawDescription: Integrating a vector field (a numpy array) using scipy.integrate


rawDescription: Sort a list using selection sort

description: Sort a list using selection sort


code:
from pylab import *
from sympy import *

rawDescription: Evaluation of symbolic Differentiation with Sympy in Python


code: df_greater_10 = df.ix[df.ints >= 1997, 'ints']

rawDescription: How do I create a DataFrame containing a column where rows are greater than a number?

description: Create a DataFrame containing a column where rows are greater than a number


code:
import random
def three_random_square_average():
    z = 0 # initialize your answer
    while(z <= 0.5625): # While the answer is less or equal than 0.5625...
        # Generate three random numbers:
        a, b, c = random.random(), random.random(), random.random()
        # Assign the square of the average to your answer variable
        z = square_of_average(a, b, c)
    # When the loop exits, return the answer
    return z

rawDescription: Random function with break command in Python


code:
import regex

def levenshtein(s1,s2):
    if len(s1) > len(s2):
        s1,s2 = s2,s1
    distances = range(len(s1) + 1)
    for index2,char2 in enumerate(s2):
        newDistances = [index2+1]
        for index1,char1 in enumerate(s1):
            if char1 == char2:
                newDistances.append(distances[index1])
            else:
                newDistances.append(1 + min((distances[index1],
                                             distances[index1+1],
                                             newDistances[-1])))
        distances = newDistances
    return distances[-1]

bigString = "AGAH_I_AM_NOWHERE_HERE_RGHFKXXX_I_AM_THERE_XXX_I_AM_HERE_EREXXMHHGRFS"
cl=[(levenshtein(s,'I_AM_HERE'),s) for s in regex.findall('I_AM_(?:HERE){e<=3}',bigString)]

print(cl)
print([t[1] for t in sorted(cl, key=lambda t: t[0])])

print(regex.search(r'(?e)I_AM_(?:ERE){e<=3}', bigString).group(0))

rawDescription: How to find a substring using partial matching

description: Find a substring using partial matching


code:
class MyCreateView(CreateView):
    form_class = MyModelForm
    ...

    def get_form(self, form_class):
        return self.form_class(self.request.user, **self.get_form_kwargs())

    ...

rawDescription: request.user as a choice in select widget in Django

description: Request.user as a choice in select widget in Django


rawDescription: Make scatter plot from set of points in tuples


code: TimeStart = datetime.datetime.strptime(TimeStart, '%Y-%m-%d %H:%M:%S')

rawDescription: How to get the time difference in minutes in python for time expressed in this format?

description: Get the time difference in minutes in python for time expressed in this format


code:
import re
re.findall(r'[\w\.]+@domain\.[\w\.]+', 'this is our info: info@domain.co.uk')

rawDescription: Python Xpath to find text() that contains @domain


code: [[u'i', u'am', u'going', u'home.', u'i', u'will', u'see,', u'if', u'i', u'can', u'do', u'that!', u'i', u'will', u'see?']]

rawDescription: Stripping punctuation from a list of lists of words


code:
df_null = df.isnull().unstack()
t = df_null[df_null]
t

rawDescription: Retrieve indices of NaN values in a pandas dataframe


code:
prop = font_manager.FontProperties(fname=path)
mpl.rcParams['font.family'] = prop.get_name()

rawDescription: Unicode character render

description: Unicode character render


code: result = [d[key] for key in d if key.startswith(query)]

rawDescription: More efficient way to look up dictionary values whose keys start with same prefix


code:
def myAdding(x, y):
     z = int(x) + int(y)
     return z

rawDescription: Simple function calling doesn't work in Robot Framework


code:
import re
s = """cat
dog"""

re.match(r'cat\ndog',s,re.M)

rawDescription: How to match a new line character in Python raw string

description: Match a new line character in Python raw string


code:
INSTALLED_APPS = (
    # ...
    'key_auth',
)

rawDescription: Security issues with a middleware screener page


code:
def update_some(convert_dict, in_dict):
    in_dict_update = in_dict.copy()
    skipped_values = {}
    for k,v in convert_dict.items():
        try:
            return_value = eval(v, None, in_dict_update)
        except NameError:
            skipped_values[k] = v
        else:
            in_dict_update[k] = return_value
    if skipped_values:
        in_dict_update = update_some(skipped_values, in_dict_update)
    return in_dict_update

rawDescription: Infinite loop while iterating dictionary Python


rawDescription: Check for invariant columns in a numpy array


code:
import locale
locale.setlocale(locale.LC_ALL, 'German')
print(locale.format('%.2f', 32757121.33, True))

rawDescription: How can I print a float with thousands separators?

description: Print a float with thousands separators


code:
dict([(basename(f.getAttribute('name')), f.getAttribute('state').lower() == 'true')
  for f in parseString(raw).getElementsByTagName('feature')])

rawDescription: Fastest way to code iteration through XML items using python's minidom?


code:
for word in words:
    if word[0].isupper():
        list1.append(word)

rawDescription: Code to detect all words that start with a capital letter in a string


rawDescription: Persistent where clause SQLAlchemy

description: Persistent where clause SQLAlchemy


code:
from mongoengine import connect
import sys

if not (len(sys.argv) > 1 and sys.argv[1] == 'test'):
    # Don't run this if we're running in unit tests. The test runner will spin
    # up the appropriate databases and spin them down appropriately.
    for db_name in MONGO_DBS:
        db_meta = MONGO_DBS[db_name]
        if db_meta['enabled'] and 'alias' in db_meta:
            connect(db_meta['name'], alias=db_meta['alias'], host=db_meta['host'], port=db_meta['port'],
                lazy_connect=db_meta.get('lazy', True))

rawDescription: latest django and mongo engine, do you need to edit settings.py to install it?

description: Latest django and mongo engine, do you need to edit settings.py to install it


code:
import pickle, gzip
import numpy as np

#from deeplearning.net
# Load the dataset
f = gzip.open('mnist.pkl.gz', 'rb')
train_set, valid_set, test_set = pickle.load(f, encoding='latin1')
f.close()

#sigmoid function
def nonlin(x, deriv=False):
    if (deriv ==True):
        return 1-x*x
    return np.tanh(x)

#seed random numbers to make calculation
#deterministic (just a good practice)

np.random.seed(1)

def make_proper_pairs_from_set(data_set):
    data_set_x, data_set_y = data_set

    data_set_y = np.eye(10)[:, data_set_y].T

    return data_set_x, data_set_y

train_x, train_y = make_proper_pairs_from_set(train_set)
train_x = train_x
train_y = train_y

test_x, test_y = make_proper_pairs_from_set(test_set)

print(len(train_y))

#train_set's dimension for the pixels are 50000(samples) x 784 (28x28 for each sample)
#therefore the coefficients should be 784x50000 to make the hidden layer 50k x 50k

# changed to 200 hidden neurons, should be plenty
syn0 = (2*np.random.random((785,200)) - 1) / 10
syn1 = (2*np.random.random((201,10)) - 1) / 10

velocities0 = np.zeros(syn0.shape)
velocities1 = np.zeros(syn1.shape)

alpha = 0.01
beta = 0.0001
momentum = 0.99

m = len(train_x) # number of training samples

# moved the forward propagation to a function and added bias neurons
def forward_prop(set_x, m):

    l0 = np.c_[np.ones((m, 1)), set_x]

    l1 = nonlin(np.dot(l0, syn0))
    l1 = np.c_[np.ones((m, 1)), l1]

    l2 = nonlin(np.dot(l1, syn1))

    return l0, l1, l2, l2.argmax(axis=1)

num_epochs = 100
for i in range(num_epochs):
    # forward propagation

    l0, l1, l2, _ = forward_prop(train_x, m)

    # calculate error
    l2_error = l2 - train_y

    print("Error " + str(i) + ": " + str(np.mean(np.abs(l2_error))))
    # apply sigmoid to the error
    l2_delta = l2_error * nonlin(l2,deriv=True)

    l1_error = l2_delta.dot(syn1.T)
    l1_delta = l1_error * nonlin(l1,deriv=True)
    l1_delta = l1_delta[:, 1:]

    # update weights
    # divide gradients by the number of samples
    grad0 = l0.T.dot(l1_delta) / m
    grad1 = l1.T.dot(l2_delta) / m

    v0 = velocities0
    v1 = velocities1

    velocities0 = velocities0 * momentum - alpha * grad0
    velocities1 = velocities1 * momentum - alpha * grad1

    # divide regularization by number of samples
    # because L2 regularization reduces to this
    syn1 += -v1 * momentum + (1 + momentum) * velocities1 - alpha * beta * syn1 / m
    syn0 += -v0 * momentum + (1 + momentum) * velocities0 - alpha * beta * syn0 / m

# find accuracy on test set

predictions = []
corrects = []
for i in range(len(test_x)): # you can eliminate this loop too with a bit of work, but this part is very fast anyway
    _, _, _, rez = forward_prop([test_x[i, :]], 1)

    predictions.append(rez[0])
    corrects.append(test_y[i].argmax())

predictions = np.array(predictions)
corrects = np.array(corrects)

print(np.sum(predictions == corrects) / len(test_x))

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


code:
for var in varnames:
    frame = tk.Frame(...)
    self.entries[var] = ttk.Entry(frame, ...)

rawDescription: Avoid exec in instance variable definition


code:
obj = C(1, 2, 3)
print(obj.a, obj.b, obj.c) # 1 2 3

rawDescription: Passing arguments to superclass constructor without repeating them in childclass constructor


code:
import inspect
class SomethingMeta(type):
    def __init__(cls, name, bases, dct):
        if not hasattr(cls, 'registry'):
            cls.registry = {}
        else:
            interface_id = name.lower()
            attrs, varargs, varkw, defaults = inspect.getargspec(cls.__init__)
            cls.registry[interface_id] = [a for a in attrs
                                          if a not in ('self', None)]

        super(SomethingMeta, cls).__init__(name, bases, dct)

class Something(object):
    __metaclass__ = SomethingMeta

class SomethingA(Something):
    def __init__(self, x, y, *args, **kw):
        self.x = x
        self.y = y

class SomethingB(Something):
    def __init__(self, z=0):
        self.z = z

print(Something.registry)

rawDescription: attibutes of subclassed classes in registry of subclassed classes

description: Attibutes of subclassed classes in registry of subclassed classes


code:
from Tkinter import *

class Window(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.geometry("600x400+30+30")
        self.wButton = Button(self, text='text', command = self.OnButtonClick)
        self.wButton.pack()

    def OnButtonClick(self):
        self.top = Toplevel()
        self.top.title("title")
        self.top.geometry("300x150+30+30")
        self.top.transient(self)
        self.wButton.config(state='disabled')

        self.topButton = Button(self.top, text="CLOSE", command = self.OnChildClose)
        self.topButton.pack()

    def OnChildClose(self):
        self.wButton.config(state='normal')
        self.top.destroy()

if __name__ == "__main__":
    window = Window(None)

    window.title("title")

    window.mainloop()

rawDescription: Python GUI code to click a button to open another window breaks


code:
testval = 1
all(val==testval for val in d.values())   # -> True

rawDescription: in python, how do I check to see if keys in a dictionary all have the same value x?

description: In python, how do I check to see if keys in a dictionary all have the same value x


code:
def order_points(x, regions):
    """Given two lists of the same length, one of x values and one of regions,
    determine how to order the points so that they describe a polygon that
    contains the interior of all regions.

    This function is a generator that yields disjoint polygons.

    Parameters
    ==========

    x: list
       x values at which the regions are defined

    regions: list of lists of tuples
       Each list contains information for one x value.  The sublist contains
       so-called regions that are described by tuples corresponding to the
       bottom and the top of the region.  The y values between the bottom and
       the top of each region are in the interior of a polygon.

       Each list of tuples should be sorted by increasing y value.

    Yields
    ======

    polygon: list of tuples
       Ordered list of (x, y) coordinated of the points on the polygon.

    """
    # Make sure the x values are in ascending order.
    xvals, yregions = zip(*sorted(zip(x, regions)))

    # Direction is -1 when going toward low x, 1 when going toward high x.
    direction = 1
    # Indicate whether the inside of the polygon is below, 0, or above, 1, the
    # current point.
    inside = 1

    # List all possible combinations of x index, region index.
    tovisit = [(pos, rpos) for pos in range(len(xvals))
                            for rpos in range(len(yregions[pos]))]
    pos, rpos = tovisit.pop(0)
    ycur = yregions[pos][rpos][0]

    # Keep track of already visited points.
    visited = set()
    # Keep track of current polygon.
    polygon = []
    while True:
        # Keep track of ordered points.
        xcur = xvals[pos]
        polygon.append((xcur, ycur))
        visited.add((xcur, ycur))

        # Find the minimum vertical distance between the current position and
        # the following points: points at the next (as specified by direction)
        # x value, and points at the current x value

        # For points at the next x, if the polygon is currently above, inside =
        # 1, the points considered are at the bottom of a region, i.e., at
        # index 0 of the tuple.
        next_pos = pos + direction
        if next_pos < 0 or next_pos >= len(xvals):
            next_pos = pos
        distance = -1
        for ri, region in enumerate(yregions[pos]):
            if (xcur, region[inside]) not in visited:
                d = abs(ycur - region[inside])
                if d < distance or distance == -1:
                    distance = d
                    move = ('vertical', (pos, ri, inside))

        # For points at the same x, if the polygon is currently above, the
        # points considered are at the top of a region, i.e., at index 1 of the
        # tuple.
        for ri, region in enumerate(yregions[next_pos]):
            polypos = (not inside)
            if (xvals[next_pos], region[polypos]) not in visited:
                d = abs(ycur - region[polypos])
                if d < distance or distance == -1:
                    distance = d
                    move = ('next', (next_pos, ri, polypos))

        # If no suitable next point is found, the polygon is complete. Yield
        # the polygon and try to find a separate polygon.
        if distance < 0:
            yield polygon
            polygon = []
            direction = 10  # dummy value to detect if no next point is found
            while tovisit:
                pos, slpos = tovisit.pop(0)
                ycur = yregions[pos][slpos][0]
                if (xvals[pos], ycur) not in visited:
                    direction = 1
                    inside = 1
                    break
            if direction == 10:
                break
            continue

        # Make the move.
        if move[0] == 'vertical':
            # Vertical move changes the direction (unless it is the very first
            # move) and toggles inside/outside.
            if len(polygon) > 1:
                direction *= -1
            inside = int(not inside)
        pos, rpos, end = move[1]
        ycur = yregions[pos][rpos][end]

rawDescription: How to order points for Matplotlib's fill function?

description: Order points for Matplotlib's fill function


rawDescription: How can I get the IP address of eth0 in Python?

description: Get the IP address of eth0 in Python


code:
session.query(
    Expense.date,
    func.sum(Expense.value).label('total')
).join(Expense.cost_center
).filter(CostCenter.id.in_([2, 3])
).group_by(Expense.date
).all()

rawDescription: GroupBy and Sum in SQLAlchemy?

description: GroupBy and Sum in SQLAlchemy


rawDescription: How to calculate longitude using PyEphem

description: Calculate longitude using PyEphem


code:
from fake_useragent import UserAgent
ua = UserAgent()
ua.chrome
ua.random

rawDescription: How to use Python requests to fake a browser visit?

description: Use Python requests to fake a browser visit


code: name = raw_input('What is your name?')

rawDescription: How can the user communicate with my python script using the shell?


code:
from nltk.stem import SnowballStemmer as SS
stemmer = SS('english')
stemmer.stem('dance')
stemmer.stem('danced')
stemmer.stem('dancing')
stemmer.stem('dancer')
stemmer.stem('accordance')

rawDescription: Probability count/frequency of related words?


code:
plt.arrow(5, -0.003, 0.1, 0, width=0.015, color="k", clip_on=False, head_width=0.12, head_length=0.12)
plt.arrow(0.003, 5, 0, 0.1, width=0.015, color="k", clip_on=False, head_width=0.12, head_length=0.12)

rawDescription: How to make 'fuller' axis arrows with matplotlib

description: Make 'fuller' axis arrows with matplotlib


code:
return Cleanedlog.objects.filter(dest_url__contains=self.kwargs["url_chunk"]) \
           .exclude(time_received__lt=from_date).exclude(time_received__gt=to_date)

rawDescription: How to handle changing dates in Django Queries

description: Handle changing dates in Django Queries


rawDescription: Django subclassing multiwidget - reconstructing date on post using custom multiwidget


code:
import os

def extract_path_segments(path, sep=os.sep):
    path, filename = os.path.split(os.path.abspath(path))
    bottom, rest = path[1:].split(sep, 1)
    bottom = sep + bottom
    middle, top = os.path.split(rest)
    return (bottom, middle, top)

rawDescription: Python function to extract multiple segments of a file path


code:
item = ['3D', '4D', '6D']
[int(val[0]) for val in item]

rawDescription: Itertools, combinations

description: Itertools, combinations


code: cm.__get__(None, dict).im_func.__name__

rawDescription: How does a classmethod object work?

description: How does a classmethod object work


code:
for d in pre_process(csv.DictReader(open('MyFile.csv'))):
    process(d)

rawDescription: How to convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics?

description: Convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics


code: msplt.set(x_coord = x_coord, y_coord = y_coord, z_coord = z_coord)

rawDescription: mayavi points3d plot animation won't update the next frame

description: Mayavi points3d plot animation won't update the next frame


rawDescription: Python: Naming conventions for modules & variables when they could conflict


code:
Bar.objects.create(name='chocolate')
Foo.objects.create(bar=Out[1])
from django.db import connection
connection.queries
foo = Foo.objects.all()
foo
connection.queries
foo.bar
connection.queries

rawDescription: when does django run the query for a OneToOneField?

description: When does django run the query for a OneToOneField


code: {{ billsec|customFilter }}

rawDescription: Math on Django Templates

description: Math on Django Templates


code:
AUTHENTICATION_BACKENDS = (
    'key_auth.backends.KeyAuthBackend',
    'django.contrib.auth.backends.ModelBackend',
)

rawDescription: Security issues with a middleware screener page


code:
from numpy import array
frame_start_times=array(Frame.objects.all().values_list('start_time'))
frame_end_times=array(Frame.objects.all().values_list('end_time'))
frame_names=array(Frame.objects.all().values_list('frame_name'))
frame_names_for_times=[]
for time in gpstime:
    frame_inds=frame_start_times[(frame_start_times<time) & (frame_end_times>time)]
    frame_names_for_times.append(frame_names[frame_inds].tostring())

rawDescription: Django lte/gte query on a list

description: Django lte/gte query on a list


code: np.vstack((a + b[:,None,:]))

rawDescription: Combine array along axis

description: Combine array along axis


code: ( a_boolean, (s1, s2, s3) )

rawDescription: How to represent dbus type b(oss) in python?

description: Represent dbus type b(oss) in python


code: chunks = [my_list[x:x+size] for x in range(0, len(my_list), size)]

rawDescription: How to create sub list with fixed length from given number of inputs or list in Python?

description: Create sub list with fixed length from given number of inputs or list in Python


code: list('big data examiner')

rawDescription: default dict counts for spaces in python

description: Default dict counts for spaces in python


rawDescription: working with regex

description: Working with regex


code:
def merge(lsta, lstb):
    for i in lstb:
        for j in lsta:
            if j['name'] == i['name']:
                j.update(i)
                break
        else:
            lsta.append(i)

for k,v in dictb.items():
    merge(dicta.setdefault(k, []), v)

rawDescription: Python: Add JSON into Existing JSON

description: Python: Add JSON into Existing JSON


rawDescription: How can I add two functions together in Python 3?

description: Add two functions together in Python 3


code:
def valueWithMaximumLength( dictionary ):
    maxKey = None
    for k, v in dictionary.items():
        if not maxKey or len(dictionary[maxKey]) < len(v):
            maxKey = k
    return maxKey

rawDescription: Python- Code Optimization Help- Find all dictionary-valid anagrams of a word


code:
keys = ["a","b","c","d"]
values = [1,2,3,4]

dict(zip(keys, values))

rawDescription: Python 3 one-liner for 2 lists string format?


code:
psUtilInfo - psutil.Process(pid)
cpuPercentage = int(psUtilInfo.get_cpu_percent())
memoryInfo, _vms =psUtilInfo.get_memory_info()

rawDescription: Is there a way to get processes information of local machine with python?


code:
bytearray(a1)
bytearray(buffer(a1))

rawDescription: When creating a Python bytearray from NumPy array, where does the extra data come from?


code: your_index.search(query)  # This will match the value of city in any field

rawDescription: Is it more performant to do an OR on multiple fields, or combine those field values into a single fieldname


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

# Generate some data
nrows, ncols = 1000, 1000
xmin, xmax = -32.4, 42.0
ymin, ymax = 78.9, 101.3

dx = (xmax - xmin) / (ncols - 1)
dy = (ymax - ymin) / (ncols - 1)

x = np.linspace(xmin, xmax, ncols)
y = np.linspace(ymin, ymax, nrows)
x, y = np.meshgrid(x, y)

z = np.hypot(x - x.mean(), y - y.mean())
x, y, z = [item.flatten() for item in (x,y,z)]

# Scramble the order of the points so that we can't just simply reshape z
indicies = np.arange(x.size)
np.random.shuffle(indicies)
x, y, z = [item[indicies] for item in (x, y, z)]

# Up until now we've just been generating data...
# Now, x, y, and z probably represent something like you have.

# We need to make a regular grid out of our shuffled x, y, z indicies.
# To do this, we have to know the cellsize (dx & dy) that the grid is on and
# the number of rows and columns in the grid.

# First we convert our x and y positions to indicies...
idx = np.round((x - x.min()) / dx).astype(np.int)
idy = np.round((y - y.min()) / dy).astype(np.int)

# Then we make an empty 2D grid...
grid = np.zeros((nrows, ncols), dtype=np.float)

# Then we fill the grid with our values:
grid[idy, idx] = z

# And now we plot it:
plt.imshow(grid, interpolation='nearest',
        extent=(x.min(), x.max(), y.max(), y.min()))
plt.colorbar()
plt.show()

rawDescription: Large matplotlib pixel figure best approach


rawDescription: How to get the list of lists

description: Get the list of lists


code:
auxdict = {}
for i, d in enumerate(hugelist):
  for item in d['ids']:
    if item not in auxdict: auxdict[item] =i

rawDescription: Python: find index of item containing X in list


code: map(sum, itertools.izip_longest(self, other, fillvalue=0))

rawDescription: Is there any way that I can turn this into a list comprehension


code:
s
first_letter = s[0]
last_letter = s[-1]
middle_parts = list(s[1:-1])
random.shuffle(middle_parts)
''.join(middle_parts)

rawDescription: Python splitting strings and jumbling the middle


code:
import subprocess

class Base:
    def __init__(self):  #don't forget `self`!!!
        self.call = subprocess.call

instance = Base()
print (instance.call(['echo','foo']))

rawDescription: Python 3 - function data member of class


rawDescription: Using URLS that accept slashes as part of the parameter in Django


rawDescription: Python loop to write across columns in CSV


rawDescription: NumPy dtype issues in genfromtxt(), reads string in as bytestring


code:
class Definitions():
    def __init__():
        self.variable1 = 3
        self.variable2 = 'stuff'

    def spam(self,arg1):
        return 'spam' + arg1

    def eggs(self,arg1,arg2):
        return 'eggs' + arg1 + arg2

rawDescription: Need help properly using variables, python


rawDescription: Find matching key-value pairs of two dictionaries


code: {u'thread_id': 1791, u'session': u'SeFKQ0SfYZqhh6FTCcKZGw==', u'authenticate': 1}

rawDescription: how to handle this string in python

description: Handle this string in python


code:
import os
import sys

if __name__ == '__main__':
    with open(os.path.abspath('test.png'), 'rb') as f:
        sys.stdout.buffer.write(b"Content-Type: image/png\n\n") # <---
        sys.stdout.buffer.write(f.read())

rawDescription: Output binary data from CGI in Python 3

description: Output binary data from CGI in Python 3


code:
import json
json.dumps(['Hi'])
json.loads(_)
import pickle
pickle.dumps(['Hi'])
pickle.loads(_)

rawDescription: How to pass object as commandline argument in python?

description: Pass object as commandline argument in python


code:
import numpy as np

d = {'A': [(4, 4, 3), [1, 2, 3, 4, 5]],
     'B': [(2, 1, 2), [5, 4, 3, 2, 1]],
     'C': [(4, 1, 1), [2, 4, 1, 2, 4]]}

def makeRanks(d):
    rankDict = {}
    for key in d:
        tup = d[key][0]
        mean = np.mean(tup)
        l = d[key][1]
        rank = np.mean([mean > np.mean(np.random.choice(l,len(tup))) for _ in range(10000)])
        rankDict[key] = rank
    return rankDict

rawDescription: How to create a function (Iteration/Recursion) to run over a dictionary of tuples in Python?

description: Create a function (Iteration/Recursion) to run over a dictionary of tuples in Python


code:
with open('filename') as fin:
    tableau = [extract(data) for data in fin]

rawDescription: How to use "While()" in python

description: Use "While()" in python


code:
mydict = {
    'labyrinth': [
        {
            u'content': u'something',
            u'expected': u''
        },
        {
            u'content': u'somethingelse',
            u'expected': u'thistext\n   user ID: a.b.c\n      user ID: e.f.g\n'
        },
        {
            u'content': u'blah',
            u'expected': u'a. Path:somepath\n   user ID: b.c.d\n'
        }
    ]
}

rawDescription: Extracting elements from dictionary of list of dictionaries


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

def main():
    x, data = generate_data(256, 6)
    model = [invert(x, y) for y in data.T]
    sigma, mu, height = [np.array(item) for item in zip(*model)]
    prediction = gaussian(x, sigma, mu, height)

    plot(x, data, linestyle='none', marker='o')
    plot(x, prediction, linestyle='-')
    plt.show()

def invert(x, y):
    # Use only data within the "peak" (20% of the max value...)
    key_points = y > (0.2 * y.max())
    x = x[key_points]
    y = y[key_points]

    # Fit a 2nd order polynomial to the log of the observed values
    A, B, C = np.polyfit(x, np.log(y), 2)

    # Solve for the desired parameters...
    sigma = np.sqrt(-1 / (2.0 * A))
    mu = B * sigma**2
    height = np.exp(C + 0.5 * mu**2 / sigma**2)
    return sigma, mu, height

def generate_data(numpoints, numcurves):
    np.random.seed(3)
    x = np.linspace(0, 500, numpoints)

    height = 100 * np.random.random(numcurves)
    mu = 200 * np.random.random(numcurves) + 200
    sigma = 100 * np.random.random(numcurves) + 0.1
    data = gaussian(x, sigma, mu, height)

    noise = 5 * (np.random.random(data.shape) - 0.5)
    return x, data + noise

def gaussian(x, sigma, mu, height):
    data = -np.subtract.outer(x, mu)**2 / (2 * sigma**2)
    return height * np.exp(data)

def plot(x, ydata, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    colorcycle = itertools.cycle(mpl.rcParams['axes.color_cycle'])
    for y, color in zip(ydata.T, colorcycle):
        ax.plot(x, y, color=color, **kwargs)

main()

rawDescription: How can I perform a least-squares fitting over multiple data sets fast?

description: Perform a least-squares fitting over multiple data sets fast


code: df = pd.DataFrame(table[1:], columns=table[0]).astype(str)

rawDescription: Reference a table column by its column header in Python


code:
df_a.columns = df_a.columns.map(lambda x: str(x) + '_a')
df_a

rawDescription: pandas join DataFrame force suffix?

description: Pandas join DataFrame force suffix


rawDescription: Django: filter queryset by intersection result


code: from includes import math

rawDescription: include A python file that exisist in the project

description: Include A python file that exisist in the project


code:
for i in range(1,100):
    X=io.imread('/home/oria/Desktop/more pics/%s.ppm' %(i))

rawDescription: Is it possible to use variable name in imread? Basic issue in Python


code:
import numpy as np
import string

# Create some fake data
N = 10
dtype = np.dtype([('a', 'i4'), ('b', 'S8'), ('c', 'f8')])
a = np.zeros(N, dtype)
a['a'] = np.random.random_integers(0,3, N)
a['b'] = np.array([x for x in string.ascii_lowercase[:N]])
a['c'] = np.random.normal(size=(N,))

# Write to a binary file
a.tofile('test.dat')

# Read data into new array
b = np.fromfile('test.dat', dtype=dtype)

rawDescription: Reading a binary file with numpy structured array


code:
def get_clean_text(page):
    return cleanup(get_text(page))
def get_clean_page(url):
    return get_clean_text(get_page(url))

rawDescription: cleaning up nested function calls

description: Cleaning up nested function calls


code:
import string
import random

padding = random.choice(string.letters)
extra = len(s) % 16
if extra > 0:
    s = s + (padding * (16 - extra))

rawDescription: How to make sure the input is a multiple of 16, and if not add padding to it

description: Make sure the input is a multiple of 16, and if not add padding to it


code:
import math
def roundup(x):
    return int(math.ceil(x / 100.0)) * 100

roundup(100)
roundup(101)

rawDescription: Python round up integer to next hundred

description: Python round up integer to next hundred


code:
d2.T
for row in d2.T:
    print(row)

rawDescription: Sort individual components of a list in python


code: from __future__ import with_statements

rawDescription: Pylons Uploading Distorted Images on Windows


code:
Example
import pandas as pd

df = pd.DataFrame({'a': range(501)})
grouped = df.groupby({x: x // 100 for x in range(len(df))})

rawDescription: Pandas: Grouping DataFrame by hundreds

description: Pandas: Grouping DataFrame by hundreds


code:
import numpy as np

def is_subarray_no_repeatition(a, b):
  try:
    i = np.where(a == b[0])[0][0]
  except IndexError:
    # either b is empty, or b[0] not in a
    return b.size == 0
  a = a[i : i+b.size]
  if a.size < b.size:
    return False
  return (a == b).all()

rawDescription: How to check efficiently if numpy array a contains b

description: Check efficiently if numpy array a contains b


code:
import pandas as pd

df1 = pd.DataFrame({'A': range(5)}, index=list('abcde'))
df2 = pd.DataFrame({'B': range(10,20,2)}, index=list('AbCdE'))

print(df1)
#    A
# a  0
# b  1
# c  2
# d  3
# e  4

print(df2)
#     B
# A  10
# b  12
# C  14
# d  16
# E  18

print(df1.join(df2, how='inner'))

rawDescription: Pandas: How to get a new dataframe filled with unions of 2 or 3 or X other dataframes?


rawDescription: Best way to create a dictionary for a later comparison of the elements

description: Create a dictionary for a later comparison of the elements


code:
from System.Windows.Media import VisualTreeHelper

def findChildren(parent, findType):
    count = VisualTreeHelper.GetChildrenCount(parent)
    for i in range(count):
        child = VisualTreeHelper.GetChild(parent, i)
        if isinstance(child, findType):
            yield child
        else:
            for entry in findChildren(child, findType):
                yield entry

rawDescription: Access Controls in Silverlight DataGrid Column Header from Code


code:
# File: views.py
from django.forms.formsets import formset_factory
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from forms import MachineForm, LineForm, BaseLineFormSet

def get_no_of_lines(request):
    if request.method == 'POST':
        machine_form = MachineForm(request.POST)
        if machine_form.is_valid():
            # At this point, form fields have already been
            # converted to Python data types :)
            # so no need to convert `line_no` to an integer
            no_of_lines = machine_form.cleaned_data['no_of_lines']
            return HttpResponseRedirect(reverse('line_form', kwargs={'no_of_lines': no_of_lines}))
    else:
        # It looks to me like you probably don't mean to
        # use formsets here (but a form instead)
        machine_form = MachineForm()

    c = RequestContext(request, {
        'machine_form': machine_form,
    })
    return render_to_response('get_no_of_lines.html', c)

def line_form(request, no_of_lines):
    # You probably should validate this number (again).
    # In fact, you probably need to validate first form (MachineForm).
    # ...But I'm assuming it'll be valid in this example.
    no_of_lines = int(no_of_lines)
    LineFormSet = formset_factory(LineForm, extra=no_of_lines, formset=BaseLineFormSet)
    if request.method == "POST":
        formset = LineFormSet(request.POST, request.FILES)
        if formset.is_valid():
            pass
            # Do stuff with form submission
            # Redirect

    else:
        formset = LineFormSet()

    c = RequestContext(request, {
        'formset': formset,
    })
    return render_to_response('line_form.html', c)

rawDescription: Django: how to change label using formset extra?


code: content = content.encode('latin1')

rawDescription: Convert unicode with utf-8 string as content to str


code:
import numpy as np
import pandas as pd

df = pd.read_table('data',sep=';',na_values=[''],thousands='.',decimal=',',
                   names=['date', '1Y', '2Y', '3Y'])
mask = df['date'].str.contains('^\s*\D')              # 1
df['currency'] = (df['date']
                  .where(mask, np.nan)                # 2
                  .fillna(method='ffill'))            # 3
df = df.loc[~mask]                                    # 4

print(df)

groups = df.groupby(['currency'])
for key, grp in groups:
    print(grp)

rawDescription: Reading chunks of csv file in Python using pandas


code:
for idx, item in enumerate(data):
    ...
    ...

rawDescription: How to know index of a decimal value in a python list

description: Know index of a decimal value in a python list


rawDescription: Cut a Substring of a String which was read by serial in Python


code:
import sys

for line in sys.stdin:
    do_something()

rawDescription: What's perfect counterpart in Python for "while not eof"


code:
@httpretty.activate
def testGetContextReturnFields(self):
  """
  Tests client.getContext() for a sample term.
  Asserts the returned object contains the corrcet fields and have contents as
  expected.
  """
  # Arrange: mock JSON response from API, mock out the API endpoint we expect
  # to be called.
  mockResponseString = getMockApiData("context_foo.json")
  httpretty.register_uri(httpretty.GET,
                         "http://this.is.the.url/query",
                         body=mockResponseString,
                         content_type="application/json")

  # Act: create the client object we'll be testing.
  c = client.Client()
  contexts = c.getContext("foo")

  # Assert: check the result object.
  self.assertTrue(isinstance(contexts, list),
    "Returned object is not of type list as expected.")
  self.assertTrue(("context_label" and "context_id") in contexts[0],
    "Data structure returned by getContext() does not contain"
    " the required fields.")
  self.assertTrue(isinstance(contexts[0]["context_label"], str),
    "The \'context_label\' field is not of type string.")
  self.assertEqual(contexts[0]["context_id"], 0,
    "The top context does not have ID of zero.")

rawDescription: Python unittest mock an API key

description: Python unittest mock an API key


code:
#!/usr/bin/env python
import requests # $ pip install requests

file = 'file content as a file object or string'
r = requests.post('http://example.com/SomeName/action.php',
                  files={'file': ('filename.txt', file)},
                  data={'str1': 'string1', 'str2': 'string2'})
print(r.text) # response

rawDescription: send both string and buffer using httplib with python to the server

description: Send both string and buffer using httplib with python to the server


code:
[{'best meower': 10, 'fanciest': 9, 'id': 'cat', 'cleanest paws': 8},
 {'dumb': 9, 'smelly': 9, 'id': 'dog'}]

rawDescription: iterative long-to-wide python one-liner (or two) using groupby

description: Iterative long-to-wide python one-liner (or two) using groupby


rawDescription: How to take sum and average of indexed values in a list?

description: Take sum and average of indexed values in a list


code:
import subprocess
import sys

subprocess.call(["/path/to/subprocess"] + sys.argv[1:])

rawDescription: Python: How to pass ARGV parameters to another script?


code:
def __getattribute__(self, name):
    attr = super(MySuperclass, self).__getattribute__(name)
    if callable(attr):
        return hierarchywrapper(attr)
    else:
        return attr

rawDescription: Define function stubs enmasse

description: Define function stubs enmasse


rawDescription: Python Lambda if statements

description: Python Lambda if statements


code:
values = np.array(values)
for i in range(len(p)): p_values[i] = np.inner(values[v[i]], w[i])

rawDescription: Interpolation with Delaunay Triangulation (n-dim)


code:
rev_key = ndb.Key('Account', 'Sandy', 'Message', 'greeting', 'Revision', '2')
address = ndb.get(rev_key)

rawDescription: GAE Transaction Alternatives to overcome entity group limit of 5


code:
import subprocess
resultMD5 = subprocess.Popen(["md5sum","myFile"],stdout=subprocess.PIPE).communicate()[0]

rawDescription: Getting Python System Calls as string results


code:
tree=[{'id': 20, 'name': 'education', 'subterms': [
               {'id': 21, 'name': 'schools', 'synonyms': []},
               {'id': 22, 'name': 'schoolbooks', 'synonyms': ['literature']},
               {'id': 23, 'name': 'higher education', 'synonyms': ['university']},
               {'id': 25, 'name': 'conference', 'synonyms': ['lecture']}]},
 {'id': 26, 'name': 'health', 'subterms': [
               {'id': 27, 'name': 'health issues', 'synonyms': []},
               {'id': 28, 'name': 'nutrition', 'synonyms': []},
               {'id': 29, 'name': 'medicine', 'synonyms': []}]},
 {'id': 1, 'name': 'business', 'subterms': [{'id': 2,
                'name': 'industry',
                'subterms': [{'id': 21, 'name': 'service', 'synonyms': []},
                             {'id': 21, 'name': 'agriculture', 'synonyms': []}],
                'synonyms': []},
               {'id': 3, 'name': 'professions', 'synonyms': ['jobs']}]}]

def filter_by_name(node, names):
    if isinstance(node, list):
        return filter(None, (filter_by_name(x, names) for x in node if x))
    subterms = filter(None, filter_by_name(node.get('subterms',[]), names))
    if set([node['name']]+node.get('synonyms',[])).intersection(names):
        return dict(node, subterms=subterms)
    if subterms:
        return dict(node, subterms=subterms)
    return None

from pprint import pprint
pprint(filter_by_name(tree, ['business']))
pprint(filter_by_name(tree, ['literature']))
pprint(filter_by_name(tree, ['literature', 'agriculture']))

rawDescription: How to filter nested JSON and preserve branch hierarchy for matches?

description: Filter nested JSON and preserve branch hierarchy for matches


rawDescription: How to get row, column indices of items in Pandas dataframe

description: Get row, column indices of items in Pandas dataframe


code:
class EntryAdmin(MarkdownModelAdmin):
    ...
    def save_model(self, request, obj, form, change):
        if form.cleaned_data.get('to_publish'):
            obj.publication_date = datetime.now()
        obj.save()

rawDescription: Django: How to custom save a model/form based on a non-persistent field of a form?


code:
try: # Windows
    from msvcrt import putwch

    def print_to_console(message):
        for c in message:
            putwch(c)
        # newline
        putwch('\r')
        putwch('\n')
except ImportError: # Unix
    import os

    fd = os.open('/dev/tty', os.O_WRONLY | os.O_NOCTTY)
    tty = os.fdopen(fd, 'w', 1)
    del fd
    def print_to_console(message, *, _file=tty):
        print(message, file=_file)
    del tty

rawDescription: Python output to Console within Subprocess from the child scricpt


code:
import re
text = r"This is the oldest European-settled town in the continental U.S.\r\nExplore the town at your leisure\r\nUpgrade to add a scenic cruise aboard \r\n"
result = re.sub(r'[ .]*(?:(?:\\r)?\\n)+', '. ', text).strip()
print(result)

rawDescription: regex match certain characters but not with a period at the beginning

description: Regex match certain characters but not with a period at the beginning


rawDescription: How to access multiple dictionaries in list with Python

description: Access multiple dictionaries in list with Python


code:
(a, b), (c, d) = l   # Thanks Lev!
a
# etc.

rawDescription: I have a string that i need to put into an object, but i cant get it to work


code:
class Apple(Fruit):

    def __init__(self):
        super().__init__("apple", 2)

rawDescription: Pythonic way of inheriting many classes?

description: Pythonic way of inheriting many classes


rawDescription: Error while getting a file path using a dialog in PyQt


rawDescription: Python csv processing

description: Python csv processing


code:
...
with Popen(
        [
            'ffmpeg',
            '-f', 'matroska', '-i', 'pipe:0',
            '-f', 'matroska', '-i', 'pipe:%d' % pipe_rfd,
        ],
        stdin=PIPE, pass_fds=[pipe_rfd]) as p:
    ...

rawDescription: How can I read/write from/to file descriptors in Python3's Popen?

description: Read/write from/to file descriptors in Python3's Popen


code:
pantilt=np.column_stack([np.linspace(-180,180,11),np.linspace(0,90,11)])

I = pantilt[:,0]>90
# J = pantilt[:,0]<-90
pantilt[I,0] -= 180
pantilt[I,1] *= -1

I = pantilt[:,0]<-90  # could use J instead
pantilt[I,0] += 180
pantilt[I,1] *= -1

rawDescription: Conditional maths operation on 2D numpy array checking on one dimension and doing different operations on diff dimensions


rawDescription: How to format a floating number to fixed width with forced sign in Python

description: Format a floating number to fixed width with forced sign in Python


code:
raw_unit8_data = np.array([32, 14, 135, 241], dtype='uint8')
raw_unit8_data.view('<f4')

rawDescription: Convert numpy unit8 raw array directly to float32


code:
import os
import requests

os.environ['NO_PROXY'] = 'stackoverflow.com'

response = requests.get('http://www.stackoverflow.com')

rawDescription: requests: how to disable / bypass proxy

description: Requests: how to disable / bypass proxy


code:
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.patches import Rectangle

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels()
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])
    return bbox.expanded(1.0 + pad, 1.0 + pad)

fig, axes = plt.subplots(3,2)

extent = Bbox.union([full_extent(ax) for ax in axes[1,:]])

# It's best to transform this back into figure coordinates. Otherwise, it won't
# behave correctly when the size of the plot is changed.
extent = extent.transformed(fig.transFigure.inverted())

# We can now make the rectangle in figure coords using the "transform" kwarg.
rect = Rectangle([extent.xmin, extent.ymin], extent.width, extent.height,
                 facecolor='yellow', edgecolor='none', zorder=-1,
                 transform=fig.transFigure)
fig.patches.append(rect)

plt.show()

rawDescription: matplotlib: subplot background (axes face + labels) colour [or, figure/axes coordinate systems]

description: Matplotlib: subplot background (axes face + labels) colour [or, figure/axes coordinate systems]


code:
import cv2
img_gray = cv2.imread('./440px-Lenna.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) # image take from http://en.wikipedia.org/wiki/Lenna

rawDescription: Convert a 2D numpy array into a 3d numpy array representing a grayscaled image


code:
xl = list(x) # you gave us a tuple
for i,y in enumerate(xl):
    xx = xl[i]
    xx = [[xx[0],y] for y in xx[1].split('. ')]
    xl[i:i+1] = xx

rawDescription: Convert list into sub-list while maintaining "key"


code:
colHeaders = ["name", "attribute #1", "attribute #2", "counter"]
myTextWidgets = []
for index in range(10):
    subList = []
    for i, header in enumerate(colHeaders):
        text = Text(root,width=20, height=1, bg='white')
        text.grid(row=index,column=i)
        text.insert('0.0',header)
        subList.append(text)
    myTextWidgets.append(subList)

rawDescription: edit entry on special position in a grid

description: Edit entry on special position in a grid


code:
seen = set()
with open(file_name, 'rt') as f:
        reader = csv.DictReader(f)
        for row in reader:
           if row['Name'] in seen:
               continue
           if all((row['Minutes'] == '0', (row['MB'] == '0' or not row['MB']), row['Calls'] == '1')):
               a_lst.append(row)
           elif all((not row['Minutes'], (row['MB'] or not row['MB']), row['Calls'] == '1')):
                a_lst.append(row)
           else:
               seen.add(row['Name'])
         # remove "else:" and just use seen.add(row['Name']) outside the elif if you want all dups removed

rawDescription: How do I remove a dictionary from a list depending on a value being present in a list in Python?

description: Remove a dictionary from a list depending on a value being present in a list in Python


rawDescription: Generate IMEI in python

description: Generate IMEI in python


code:
# a slightly larger example array in order to better illustrate what
# argpartition does
b = np.array([[  5.2,   4.3],
              [200.2,   6.2],
              [  3.6,  85.1],
              [  1.4, 112.2],
              [ 12.8,  60.0],
              [  7.6,  23.4]])

# get a set of indices to reorder the rows of `b` such that b[2, 0] is in its
# final 'sorted' position, and all elements smaller or larger than it will be
# placed before and after it respectively
partial_order = np.argpartition(b[:, 0], 2)

# the first (2+1) elements in the first column are guaranteed to be smaller than
# the rest, but apart from that the order is arbitrary
print(b[partial_order])
# [[   1.4  112.2]
#  [   3.6   85.1]
#  [   5.2    4.3]
#  [ 200.2    6.2]
#  [  12.8   60. ]
#  [   7.6   23.4]]

rawDescription: numpy.partition() with 2-D Array

description: Numpy.partition() with 2-D Array


code:
import re
from itertools import groupby

def regex_key(key):
    """Traditional, regular-expression-based nat-sort key."""
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    return [convert(c) for c in re.split('([0-9]+)', key)]

def fast_key(value):
    """Attempt #1 to go faster than 'slow' 're' library."""
    result = []
    for is_int, chunk in groupby(value.lower(), str.isdigit):
        if is_int:
            result.append(int(''.join(chunk)))
        else:
            result.append(tuple(chunk))
    return result

def faster_key(value):
    """Attempt #2.  'Low-level' python."""
    start_idx = 0
    is_num = None
    result = []
    for idx, c in enumerate(value.lower()):
        now_is_num = c.isdigit()
        if is_num is not None and now_is_num != is_num:
            buf = value[start_idx:idx]
            result.append(int(buf) if is_num else buf)
            start_idx = idx
            is_num = None
        is_num = now_is_num
    buf = value[start_idx:]
    result.append(int(buf) if is_num else buf)
    return result

rawDescription: python natural comparison between strings?

description: Python natural comparison between strings


code:
self.button1.clicked.connect(lambda : do_stuff('btn one'))
self.button2.clicked.connect(lambda : do_stuff('btn two'))

rawDescription: PyQT - modifying main window widgets from other functions


code:
doc = lxml.etree.XML(data)
for parent in doc.iter('*'):
    child=parent.find('node2/[@a1="x2"]')
    if child is not None:
        parent.remove(child)

rawDescription: xml filtering with python

description: Xml filtering with python


code:
# Walk over all elements in the tree and remove all
# nodes that are recursively empty
context = etree.iterwalk(root)
for action, elem in context:
    parent = elem.getparent()
    if recursively_empty(elem):
        parent.remove(elem)

rawDescription: Python lxml - How to remove empty repeated tags


code:
df1
df2

rawDescription: How to merge two data frames based on nearest date

description: Merge two data frames based on nearest date


rawDescription: Given a dictionary of word and frequency pairs, how to proceed with text mining in scikit


code:
hours_difference = abs(start_time - end_time).total_seconds() / 3600.0
hours_difference

rawDescription: Converting date into hours

description: Converting date into hours


code:
def getAppNames():
    result = []
    for app in service.apps:
        result.append(app.name)
    return result

rawDescription: Python: Return function won’t return a list


rawDescription: ArcGIS and ACCESS table

description: ArcGIS and ACCESS table


code:
from itertools import accumulate, groupby
[0] + list(accumulate(sum(1 for _ in g) for _,g in groupby(bool_array)))

rawDescription: How do I identify sequences of values in a boolean array?

description: Identify sequences of values in a boolean array


code:
class Session(object):
    def __init__(self, gref):
        self.init()
        self.gref = gref

    def init(self):
        self.modules = {}
        self.path = None
        self.glob = {}

    def start(self):
        import sys
        self.modules = sys.modules.copy()
        self.path = sys.path[:]
        self.glob = self.gref.copy()
        self.gref['test'] = 'abc'

    def stop(self):
        import sys
        sys.modules = self.modules.copy()
        sys.path = self.path[:]
        for k in self.gref.keys():
            del self.gref[k]
        self.gref.update(self.glob)

    def __repr__(self):
        return repr(self.glob)

rawDescription: Start and end an independent sub-session in Python


rawDescription: Manipulating numpy arrays

description: Manipulating numpy arrays


code:
import urllib2
import lxml.html as LH

site = "http://racing.racingnsw.com.au/InteractiveForm/HorseAllForm.aspx?HorseCode=ODA0ODQ0MTUy&src=horsesearch"
req = urllib2.Request(site)
page = urllib2.urlopen(req)
root = LH.parse(page)
for td in root.xpath('//*[@id="info-container"]/table[2]/tr[33]/td[2]'):
    print(td.text_content())

rawDescription: Text between tag including the text of children within the tag in lxml


code:
teacher =  Teacher.objects.create(name='some name')
student = Student.objects.create(name='some_name')
parent =  Parent.objects.create(name='some_name', address='some_address')

rawDescription: How do I fill in nested ManyToMany fields in Django with Shell?

description: Fill in nested ManyToMany fields in Django with Shell


code:
from django.db import models

def new_init(func):
   def __init__(self, *args,  **kw):
       self.documentation = kw.pop("documentation", None)
       return func(self, *args, **kw)

for name, obj in models.__dict__.items():
    #check if obj is a class:
    if not isinstance(obj, type):
        continue

    obj.__init__ = new_init(obj.__dict__["__init__"])

rawDescription: Override __init__ for all classes in module


rawDescription: Validate Certificate using Python

description: Validate Certificate using Python


code: in_img = numpy.random.random((1000, 1000))

rawDescription: Opencv python: apply arbitrary function to each pixel without iterating


code: dic = dict((y, x) for x, y in enumerate(al, 1))

rawDescription: How to create a dict with letters as keys in a concise way?

description: Create a dict with letters as keys in a concise way


code:
import urllib

URL = "http://host.domain.tld/resource"
XML = "<xml />"

parameter = urllib.urlencode({'XML': XML})

rawDescription: send xml file to http using python

description: Send xml file to http using python


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

X = np.random.rand(1000)*2
Y = np.sin(X)
plt.scatter(X,Y)
plt.show()

rawDescription: Python maplotlib sine curve with random.randn


code: data.sort(key=lambda tup: tup[1])  # sorts in place

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

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


rawDescription: averaging list of lists python

description: Averaging list of lists python


code:
class myReserve():
    def __init__(self, initName):
        self.myList = dict()

rawDescription: Python3: How to create a dict of different objets of the same class?


code:
delay_channel.queue_declare(queue='hello_delay', durable=True,  arguments={
  'x-message-ttl' : 5000,
  'x-dead-letter-exchange' : 'amq.direct',
  'x-dead-letter-routing-key' : 'hello'
})

rawDescription: How to create a delayed queue in RabbitMQ?

description: Create a delayed queue in RabbitMQ


code:
browser = webdriver.Firefox()

username = 'myusername'
password = 'mypassword'

browser.get('http://www.mywebsite.com/')
username_input = browser.find_element_by_id('username') #Using id only as an example
password_input = browser.find_element_by_id('password')
login_button = browser.find_element_by_id('login')

username_input.send_keys(username)
password_input.send_keys(password)
login_button.click()

rawDescription: Use urllib2 cookie in Selenium

description: Use urllib2 cookie in Selenium


rawDescription: Getting a N-element vector of values evenly spaced from -X to X


code: ['df1open', 'df1high', 'df1low', 'df1close']

rawDescription: Renaming columns of dataframe list in Pandas


rawDescription: Grouping a dataframe by X columns

description: Grouping a dataframe by X columns


code: mystr = "mike dc car dc george dc jerry dc"

rawDescription: Python - print tab delimited two-word set


rawDescription: how to get all item with specific value from dict?

description: Get all item with specific value from dict


code:
import re

with open('path/to/file.txt') as inf:
    text = inf.read()  # generally bad practice, but...

numbers = re.findall(r"\d+", text)  # ['95', '90']
for number in numbers:
    print(number)

rawDescription: Python program that is given a line read from a text file and displays the one number found


code:
class Foo(object):
    def __init__(self):
        self._big_calc_result = None

    @property
    def big_calc_result(self):
        if self._big_calc_result is not None:
            return self._big_calc_result
        else:
            self._big_calc_result = self.big_calc_run()
            return self._big_calc_result

    def big_calc_run(self):
        time.sleep(10)  # Takes a long time ...

rawDescription: Check whether class variable has been defined


code:
import sys
data = [line.strip() for line in sys.stdin]

rawDescription: Matching list items to items at the other end of the same list?


code:
directory = "c:\\..."
import os.path
paths = [os.path.join(directory, filename) for filename in filenames]

rawDescription: Leaving one item out in a python list and print paths


rawDescription: intersection of multiple sets in a list

description: Intersection of multiple sets in a list


rawDescription: Playing with the Python zip function

description: Playing with the Python zip function


code:
norm = plt.normalize(min_v, max_v)
hb1 = plt.hexbin(x1, y1, norm=norm)
hb2 = plt.hexbin(x2, y2, norm=norm)

rawDescription: How do I normalize a hexbin plot?

description: Normalize a hexbin plot


code: reverse("name", year=2009, month=9)

rawDescription: question related to reverse function and kwargs

description: Question related to reverse function and kwargs


code:
import itertools as IT
import pandas as pd

pos = pd.DataFrame({'Station(s)':[',1,2,,','0,1,2,3,4'],
                    'Position':['Contractor','President'],
                    'Site(s)':['A,B','A'],
                    'Item(s)':['1','1,2']})

sd = pd.DataFrame({'Site':['A','B','B','C','A','A'],
                   'Station(s)':[',1,2,,',',1,2,,',',,,,',',1,2,,','0,1,2,,',',,2,,'],
                   'Item 1':[1,1,0,0,1,0],
                   'Item 2':[1,0,0,1,1,1]})

mypos = pos.copy()
mypos['Station(s)'] = mypos['Station(s)'].str.findall(r'(\d+)')
mypos['Site(s)'] = mypos['Site(s)'].str.split(r',')
tidypos = pd.DataFrame(
    [(row['Position'], site, station)
     for index, row in mypos.iterrows()
     for site, station in IT.product(
             *[row[col] for col in ['Site(s)', 'Station(s)']])],
    columns=['Position', 'Site', 'Station'])

mysd = sd[['Site', 'Station(s)']].copy()
mysd['Station(s)'] = mysd['Station(s)'].str.findall(r'(\d+)')

tidysd = pd.DataFrame(
    [(index, row['Site'], station)
     for index, row in mysd.iterrows()
     for station in row['Station(s)']],
    columns=['index', 'Site', 'Station'])

merged = pd.merge(tidysd, tidypos, how='left')
pos_count = merged.groupby(['index', 'Position'])['Station'].nunique().unstack()
total_count = tidysd.groupby(['index'])['Station'].nunique()
pos_count = pos_count.reindex(total_count.index, fill_value=0)
for col in pos_count:
    pos_count[col] = (pos_count[col] == total_count).astype(int)
pos_count = pos_count.reindex(sd.index, fill_value=0)
result = pd.concat([sd, pos_count], axis=1)
print(result)

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code:
import re
p = re.compile(r'^([a-z]).*\1$', re.MULTILINE)
test_str = "a sdf sd fdsf sd a\nsdfdsf ASDSDSAD@#$@#ASDASDs\nsadasd Wdsda"

re.findall(p, test_str)

rawDescription: Python regular expression capture re-use


code:
from __future__ import print_function

import sys

from itertools import islice

filepath = sys.argv[1]

with open(filepath, 'rb') as f:
    for line in truncate(islice(f, 6, None), 5):
        print(line, end='')

rawDescription: Skip last 5 line in a file using python

description: Skip last 5 line in a file using python


code:
def interval_assurer(f):
    def func():
        global last_time
        if (datetime.datetime.now() - last_time).seconds < 1:
            print("Too fast...")
            time.sleep(1)
        last_time = datetime.datetime.now()
        return f()
    return func

rawDescription: Assure minimal wait between calls with decorators


code: tr = td.find_element_by_xpath("..")

rawDescription: Python Selenium click on a specific row in a table containing the right data in a column


rawDescription: Python dynamic function attribute

description: Python dynamic function attribute


code:
lis=['joe:  5', 'ed:  9', 'joe:  7', 'ed:  8']
sorted(lis,key=lambda x:int(x.split()[-1]),reverse=True)
['ed:  9', 'ed:  8', 'joe:  7', 'joe:  5']

rawDescription: Converting strings to integers then ordering them in an list with strings


code: [x.text for x in doc]

rawDescription: how to convert xml into list

description: Convert xml into list


code:
def size(l):
    s = 0
    for _ in l:
        s += 1
    return s

rawDescription: Python - finding value position in a list and outputting as a new list


code:
def compare(s, t):
    t = list(t)   # make a mutable copy
    try:
        for elem in s:
            t.remove(elem)
    except ValueError:
        return False
    return not t

rawDescription: How to efficiently compare two unordered lists (not sets) in Python?

description: Efficiently compare two unordered lists (not sets) in Python


rawDescription: numpy bytes to plain string

description: Numpy bytes to plain string


code: myfunc = dec(myfunc)

rawDescription: How to understand python decorator arguments pass

description: Understand python decorator arguments pass


code: fw.write('\n'.join(input().split(' ')))

rawDescription: Input in python on more than one line

description: Input in python on more than one line


code:
from openpyxl import load_workbook
wb2 = load_workbook('test.xlsx')
ws4 = wb2["New Title"]

rawDescription: Python openpyxl select sheet

description: Python openpyxl select sheet