code:
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA

# At this moment request object must contain serialized_payment_details, pki_type and pki_data
request.signature = ""  # Add empty signature
request_hash = SHA256.new(request.SerializeToString())
private_key = RSA.importKey(private_key_der_data)
signer = PKCS1_v1_5.new(private_key)
request.signature = signer.sign(request_hash)
result = request.SerializeToString()

rawDescription: How to add signed certificates to a bitcoin bip70 payment message? python

description: Add signed certificates to a bitcoin bip70 payment message? python


code: next((x for x in lst if matchCondition(x)), None)

rawDescription: Return the first item in a list matching a condition


code:
# save this as greeting.py
class GreetingMaker(object):
    def get_fortune(self, name):
        return "Hello, {0}. Here is your fortune message:\n" \
               "Behold the warranty -- the bold print giveth and the fine print taketh away.".format(name)

rawDescription: How can I send python code to another machine to be executed?

description: Send python code to another machine to be executed


code:
def role_required(role_name):
    def decorator(func):
        @wraps(func)
        def authorize(*args, **kwargs):
            if not current_user.has_role(role_name):
                abort(401) # not authorized
            return func(*args, **kwargs)
        return authorize
    return decorator

rawDescription: What is the best way to protect a flask endpoint?


rawDescription: Importing matrix data from CSV into a numpy array, Issue with slicing the result


code:
class IORedirector(object):
    '''A general class for redirecting I/O to this Text widget.'''
    def __init__(self,text_area):
        self.text_area = text_area

class StdoutRedirector(IORedirector):
    '''A class for redirecting stdout to this Text widget.'''
    def write(self,str):
        self.text_area.write(str,False)

rawDescription: stdout to tkinter GUI

description: Stdout to tkinter GUI


code: # User input below:

rawDescription: Python- Key from dict on user input eval. Send to overloaded operator function


code:
import struct
data = struct.pack('<?3h3h', True, 1,2,3,4,5,6)
result = struct.unpack('<?3h3h', data)
is_enabled = result[0]
cmd_speed = result[1:4]
tach_speed = result[4:7]

print(is_enabled, cmd_speed, tach_speed)

rawDescription: Python - unpack struct into multiple tuples


rawDescription: Komodo - watch variables and execute code while on pause in the program


code: np.where(np.in1d(C, A), B, np.nan)

rawDescription: Get Value From a NumPy Array

description: Get Value From a NumPy Array


code: ''.join(['%08d'%int(bin(ord(i))[2:]) for i in 'This is my string'])

rawDescription: Python 2.5 convert string to binary

description: Python 2.5 convert string to binary


code: dict(Counter(l))

rawDescription: How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python?

description: Obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python


code:
class DemoABC:

    __metaclass__ = ABCMeta

    @abstractclassmethod
    def from_int(cls, n):
        raise NotImplementedError

rawDescription: Python 2.7 Combine abc.abstractmethod and classmethod


code:
lst = ['aaa','dfbbsd','sdfdee']
val = 'bb'
any(val in x  for x in lst)
val = "foo"
any(val in x  for x in lst)
val = "fde"
any(val in x  for x in lst)

rawDescription: How do I check existence of a string in a list of strings, including substrings?

description: Check existence of a string in a list of strings, including substrings


code:
import Tkinter as tk
root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo("Say Hello", "Hello World")

rawDescription: Tkinter messagebox without window?

description: Tkinter messagebox without window


code:
"""All supporting functionality is collected here."""
from numpy import r_, arctan2, cos, sin
from numpy import atleast_2d as a2d

# ToDo: create proper documentation strings
def _a(a0, a1):
    return r_[a2d(a0), a2d(a1)]

def from_polar(p):
    """(theta, radius) to (x, y)."""
    return _a(cos(p[0])* p[1], sin(p[0])* p[1])

def to_polar(c):
    """(x, y) to (theta, radius)."""
    return _a(arctan2(c[1], c[0]), (c** 2).sum(0)** .5)

def d_to_polar(D):
    """Distance matrix to (theta, radius)."""
    # this functionality is to adopt for more general situations
    # intended functionality:
    # - embedd distance matrix to 2D
    # - return that embedding in polar coordinates
    pass

if __name__ == '__main__':
    from numpy import allclose
    from numpy.random import randn
    c= randn(2, 5)
    assert(allclose(c, from_polar(to_polar(c))))

    # ToDO: implement more tests

rawDescription: How do I create a radial cluster like the following code-example in Python?

description: Create a radial cluster like the following code-example in Python


code:
data = []
for n in range(1000):
    d = []
    for m in range(300):
        if random.random() <= 0.1:
            d.append(random.normalvariate(0.0, 1.0))
        else:
            d.append(random.normalvariate(100.0, 1.0))
    data.append(d)

rawDescription: Finding a vector that is approximately equally distant from all vectors in a set


code:
def makeF():
    script="def sayA():\n\tprint('Aah')"
    exec(script)
    return sayA

rawDescription: Defining a function with exec from inside a function in global environment


code:
print>>fout, header
pos = fout.tell()

rawDescription: file.write() the length of file without knowing the length of file beforehand - python

description: File.write() the length of file without knowing the length of file beforehand - python


code: z = x.split('-')

rawDescription: Python way to split a particular string in a specific list


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

# Generate some test data
data = np.arange(100).reshape((10,10))

xlabels = ['capacity', 'failure_rate', 'id', 'margin', 'price', 'prod_cost', 'product_type', 'quality', 'warranty', 'market_share', 'attractiveness']
ylabels = ['capacity', 'failure_rate', 'id', 'margin', 'price', 'prod_cost', 'product_type', 'quality', 'warranty', 'market_share', 'attractiveness']

fig, ax = plt.subplots()

ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)

ax.xaxis.tick_top()
plt.xticks(rotation=90)

ax.set_xticklabels(xlabels, minor=False)
ax.set_yticklabels(ylabels, minor=False)
heatmap = ax.pcolor(data)

ax = plt.gca()

for t in ax.xaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False
for t in ax.yaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False

plt.show()

rawDescription: Python - plot a NxN matrix as a gradient colors grid


code:
import re
mystring = "Field 1: Data 1 Field 2: Data 2 Field 3: Data 3"
a = re.split(r"(Field 1:|Field 2:|Field 3:)",mystring)

rawDescription: Split string by multiple separators?

description: Split string by multiple separators


code:
from datetime import datetime
from datetime import timedelta

for tau in range(0,10):
   d_abrv = "d" + str(tau)
   day = "day" +str(tau)
   d_abrv = (datetime.now() + timedelta(days=tau))
   day = d_abrv.strftime('%a %d-%b-%y')
   image_date = d_abrv.strftime('%Y%m%d')
   plt.savefig(homedir + "/out/_tmax_" + d_abrv + "_ne.png", dpi = 300)

sys.exit()

rawDescription: Define Multiple Variables In While Loop

description: Define Multiple Variables In While Loop


code:
N = 1000000
v_np = np.array(range(N))
v_list = range(N)

rawDescription: Iterating over arrays in cython, is list faster than np.array?


rawDescription: match regular expression without capture

description: Match regular expression without capture


code:
import sys

def sum(a,b=5):
    "Adds two numbers"
    a = int(a)
    b = int(b)
    return a+b

sum.version = "1.0"
sum.author = "Prasad"

if __name__ == '__main__':
    k = sum(1,2)
    print(k)

    print("Function attributes: - ")
    print("Documentation string:",sum.__doc__)
    print("Function name:",sum.__name__)
    print("Default values:",sum.__defaults__)
    print("Code object for the function is:",sum.__code__)
    print("Dictionary of the function is:",sum.__dict__)

    #writing the same information to a file

    f = open('test.txt','w')
    f.write(sum.__doc__)
    f.close()
    print("\n\nthe file is successfully written with the documentation string")

rawDescription: Python is printing everything form module when imported into another module


rawDescription: Confidence Interval for t-test (difference between means) in Python


rawDescription: Limiting a number to a range

description: Limiting a number to a range


code:
transform = vtk.vtkTransform()
transform.Translate(-center[0], -center[1], -center[2])
transformFilter = vtk.vtkTransformPolyDataFilter()
transformFilter.SetInputData(polydata)
transformFilter.SetTransform(transform)
transformFilter.Update()
centeredPolydata = transformFilter.GetOutput()

rawDescription: centering the axis/pivot of a polydata model in python-vtk/three.js

description: Centering the axis/pivot of a polydata model in python-vtk/three.js


code:
config.add_route('path::a', 'path/a')
config.add_route('path::b', 'path/b')

rawDescription: Multiple paths for a route in URL Dispatch


rawDescription: Scikit Learn HMM training with set of observation sequences


code:
observed = np.array([20., 20., 0., 0.])
expected = np.array([.25, .25, .25, .25]) * np.sum(observed)
chisquare(observed, expected)

rawDescription: Chi-Squared test in Python

description: Chi-Squared test in Python


code:
import weakref

def weakmethod(method):
    cls = method.im_class
    func = method.im_func
    instance_ref = weakref.ref(method.im_self)
    del method

    def inner(*args, **kwargs):
        instance = instance_ref()

        if instance is None:
            raise ValueError("Cannot call weak method with dead instance")

        return func.__get__(instance, cls)(*args, **kwargs)

    return inner

class A(object):
    def __del__(self):
        print("DEL")
    def a(self):
        pass

def log_all_calls(function):
    def inner(*args, **kwargs):
        print("Calling {}".format(function))

        try:
            return function(*args, **kwargs)
        finally:
            print("Called {}".format(function))

    return inner

a = A()
a.a = log_all_calls(weakmethod(a.a))

a.a()

rawDescription: Why set a bound method to python object create a circular reference?


rawDescription: Dividing in Python

description: Dividing in Python


code:
from django.utils.functional import curry

lols = {'lols':'lols'}
formset = modelformset_factory(MyModel, form=myForm, extra=0)
formset.form = staticmethod(curry(MyForm, lols=lols))

rawDescription: What is a _curried method in python and how are they generated?


code:
from nltk import sent_tokenize, word_tokenize, pos_tag
text = "This is a foo bar piece of text. And there are many sentences in this text."
tagged_text = [pos_tag(word_tokenize(sent)) for sent in sent_tokenize(text)]
tagged_text

rawDescription: How to tag an article with NLTK?

description: Tag an article with NLTK


rawDescription: Extracting Data with Python Regular Expressions


code: print(lst)

rawDescription: Objects/classes/lists Python

description: Objects/classes/lists Python


code: content = u'\N{TRADE MARK SIGN}'.encode('utf-8')

rawDescription: Python Regex and the Copyright Symbol

description: Python Regex and the Copyright Symbol


rawDescription: Django Context Processor and Form variables


code:
from yourmodule.main import commands

def mynewcommand(arguments=here):
    pass

commands['newcommand'] = mynewcommand

rawDescription: Automatically registering "commands" for a command line program in python


rawDescription: Index and Slice a Generator in Python

description: Index and Slice a Generator in Python


code:
def divisors(start, end, trans=lambda x:x):
    return [sum(i % j == 0 for j in range(1, i + 1)) for i in (trans(t) for t in range(start, end+1))]

divisors(0, 10, lambda x: x**2)
divisors(0, 10)

rawDescription: Using a sieve to find number of divisors but only for n^2


code:
f = open('file')
for a in f:
    a = a.split()
    add_num = list(map(int,a[-1].split(',')[1:]))
    for i in range(len(add_num)):
        print(" ".join([b[0]] + [str(int(b[1])+sum(add_num[:i+1]))] + b[2:]))

rawDescription: how to add a specific value to a column iteratively in python

description: Add a specific value to a column iteratively in python


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

rawDescription: Setting Django up to use MySQL

description: Setting Django up to use MySQL


code: result = 0

rawDescription: How to specify each index number - Python

description: Specify each index number - Python


rawDescription: How to set different parameter ranges within a real valued chromosome using Pyevolve?

description: Set different parameter ranges within a real valued chromosome using Pyevolve


rawDescription: Django Multiple Dictionary Parsing

description: Django Multiple Dictionary Parsing


code:
def read_file(fobj):
    names = set()
    for line in fobj:
        split_line = line.lower().split(',')
        names.add((split_line[0], split_line[1].split()[0]))
    return names

rawDescription: Python Fuzzy Matches in two text files

description: Python Fuzzy Matches in two text files


code: dt = dt.replace(month=dt.day, day=dt.month)

rawDescription: Convert a datetame object to the correct date (MM-DD-YYYY to DD-MM-YYYY)


code:
if 'user' in request.GET:
    user = request.GET['user']

rawDescription: handling multiple query parameters in tastypie

description: Handling multiple query parameters in tastypie


code: print(4 * char,end='') # Or how many ever times you want to repeat it.

rawDescription: String manipulation in for loops

description: String manipulation in for loops


code: datetime.date(year=(d.year + int(d.month % 12 == 0)), month=(d.month + 1) % 12, day=1) - datetime.timedelta(days=1)

rawDescription: Getting the date of the last day of this [week/month/quarter/year]


rawDescription: python dictionary match key values in two dictionaries

description: Python dictionary match key values in two dictionaries


code:
def __next__(self):
    if self.current > self.number:
        raise StopIteration
    current = self.current
    self.current += 2
    return current

rawDescription: Using an iterator in python?

description: Using an iterator in python


rawDescription: Compare list in python to detect an equality


code:
map(list, zip(name, sex))
[list(x) for x in zip(name, sex)]

rawDescription: Fastet way to create 2D list from two 1D list in Python


code:
import re
re.findall(r"\b(?<!<)\w+(?!>)\b", text)

rawDescription: Match words that are not inside the characters < > using regular expressions


code:
for i, row in staticData.iterrows():
    unique_id = i
    exchange = row['exchange']

rawDescription: Iterate through a dataframe by index

description: Iterate through a dataframe by index


code:
class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

rawDescription: Python enum - getting value of enum on string conversion


rawDescription: Why are Python lambdas useful?

description: Why are Python lambdas useful


code:
def centerMap(lats,lons,scale):
    #Assumes -90 < Lat < 90 and -180 < Lon < 180, and
    # latitude and logitude are in decimal degrees
    earthRadius = 6378100.0 #earth's radius in meters

    northLat = max(lats)
    southLat = min(lats)
    westLon = max(lons)
    eastLon = min(lons)

    # average between max and min longitude
    lon0 = ((westLon-eastLon)/2.0)+eastLon

    # a = the height of the map
    b = sd.spheredist(northLat,westLon,northLat,eastLon)*earthRadius/2
    c = sd.spheredist(northLat,westLon,southLat,lon0)*earthRadius

    # use pythagorean theorom to determine height of plot
    mapH = pow(pow(c,2)-pow(b,2),1./2)
    arcCenter = (mapH/2)/earthRadius

    lat0 = sd.secondlat(southLat,arcCenter)

    # distance between max E and W longitude at most souther latitude
    mapW = sd.spheredist(southLat,westLon,southLat,eastLon)*earthRadius

    return lat0,lon0,mapW*scale,mapH*scale

lat0center,lon0center,mapWidth,mapHeight = centerMap(dataLat,dataLon,1.1)

rawDescription: Automatically center matplotlib basemap onto data


code:
p = Popen(["pram_axdnull", str(kmer), input_filename, "-"],
          stdin=PIPE, stdout=PIPE)
output = p.communicate(generate_kmers(3))[0]

rawDescription: Bash style process substitution with Python's Popen


code:
lines = ["<tr>"]
for cell in cells:
    lines.append (cell.prettify().decode('ascii'))
    if (cell.string.strip () == "Accounts Payable"):
        sibling = cell.findNextSibling ()
        while (sibling):
            lines.append (sibling.prettify().decode('ascii'))
            sibling = sibling.findNextSibling ()
lines.append ("</tr>")

f = open ("so_soup_out.txt", "wt")
f.writelines (lines)
f.close ()

rawDescription: Using Python and Beautifulsoup how do I select the desired table in a div?


code:
class StreamProtocol(asyncio.Protocol):
    def __init__(self, loop, queue):
        self.loop = loop
        self.queue = queue

    def data_received(self, data):
        for message in data.decode().splitlines():
            self.queue.put_nowait(message.rstrip())

    def connection_lost(self, exc):
        self.loop.stop()

rawDescription: asyncio queue consumer coroutine

description: Asyncio queue consumer coroutine


code:
import sys
written = sys.stdout.write('10')

rawDescription: Output from sys.stdout in interactive mode


code:
values = [1, np.nan, 2, np.nan, np.nan, 3, np.nan, np.nan, np.nan, 4]
interpolate_gaps(values, limit=1)

rawDescription: Working with NaN values in matplotlib

description: Working with NaN values in matplotlib


code: b if a else c

rawDescription: Python equivalent for a C expression

description: Python equivalent for a C expression


code:
from datetime import datetime, timedelta, time

today = datetime.now().date()
tomorrow = today + timedelta(1)
today_start = datetime.combine(today, time())
today_end = datetime.combine(tomorrow, time())

queryset = KleedkamerIndeling.objects.order_by('-gametimedate').filter(gametimedate__gte=today_start).filter(gametimedate__lt=today_end)

rawDescription: django queryset filter datetimefield

description: Django queryset filter datetimefield


code:
import re
rx = '[%s]' % re.escape(string.punctuation)
re.sub(rx, r" \g<0> ", "foo,,,bar!!1")

rawDescription: How to convert an iterative str.replace() with str.translate()? - python

description: Convert an iterative str.replace() with str.translate()? - python


code:
def empty_adaptor(iterable, sentinel=object()):
    it = iter(iterable)
    item = next(it, sentinel)
    if item is sentinel:
       return None # empty
    else:
       def gen():
           yield item
           for i in it:
               yield i
       return gen()

rawDescription: better for-loop syntax for detecting empty sequences?

description: Better for-loop syntax for detecting empty sequences


code:
s = "*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON "\
    "%d/%b/%y AT %H:%M:%S ***\n\n"
datetime.datetime.now().strftime(s)

rawDescription: How do I convert date to Day/Month/Year (20/Jan/2012) in python

description: Convert date to Day/Month/Year (20/Jan/2012) in python


code:
from flask import jsonify
from werkzeug.security import safe_join

@app.route("/gallery")
def gallery():
    images = get_images_from_dir("some/base/path/*.jpg")
    return render_template("gallery.html", images=images)

@app.route("/search/images", methods=["POST"])
def search_images():
    glob_path = request.form["image_query"]
    glob_path = safe_join("/some/base/path", glob_path)
    return jsonify(images=get_images_from_dir(glob_path))

rawDescription: Changing a variable without reloading the page


code:
#Jinja2 filters
from jinja2 import evalcontextfilter, Markup

#Mind the hack! Babel does not work well within js code
@app.template_filter()
@evalcontextfilter
def generate_string(eval_ctx, localized_value):
    if localized_value is None:
        return ""
    else:
        return Markup("\"" + localized_value + "\"").unescape()

rawDescription: Flask-Babel localized strings within js

description: Flask-Babel localized strings within js


rawDescription: Python 3.3 pyqtgraph can't plot points

description: Python 3.3 pyqtgraph can't plot points


code:
urlpatterns = patterns('',
    url('^sample2/$', message, name="message_view"),
    url('^sample/$', authentication, name="auth_view"),
)

rawDescription: redirecting from one place to another

description: Redirecting from one place to another


code:
if br.form["list"] == ["---"]:
    br.form["list"].value = ["1"]

rawDescription: Mechanize select from dropdown

description: Mechanize select from dropdown


code: df.sample(False, 0.1, seed=0).limit(1)

rawDescription: How take a random row from a PySpark DataFrame?


code:
class Fmt(str):
    def __add__(self, other):
        return Fmt(str.__add__(self, other))
    def __radd__(self, other):
        return Fmt(str.__add__(other, self))
    def format(self, *args):
        return str.format(self, *(int(round(x, -2)) for x in args))

ax = sns.heatmap(flights, annot=True, fmt=Fmt(","))

rawDescription: Possible to round numbers to the hundreds, thousands, etc. using Python 3's number formatting


code:
my_section_new_name = "newSectionName"
_config.add_section(my_section_new_name)

rawDescription: Python - How to change the name of a section use configparser?


rawDescription: How do i find the minimum of two dataframe columns with multi-indices in python pandas?

description: Find the minimum of two dataframe columns with multi-indices in python pandas


rawDescription: Formatting files to be written

description: Formatting files to be written


code:
import pandas.io.data as web

jpy = web.DataReader('DEXJPUS', 'fred')

rawDescription: How can get ' USDJPY'(currency rates) with pandas and yahoo finance?


rawDescription: Determining implementation of Python at runtime?


code:
import serial.tools.list_ports_posix
devices = serial.tools.list_ports_posix.comports()

rawDescription: how to find all serial devices ? (COM*)

description: Find all serial devices ? (COM*)


code:
def script_running(self, script):
    """Check if the script is running."""

rawDescription: Docstrings - one line vs multiple line

description: Docstrings - one line vs multiple line


code:
a=Person()
a.addattr('foo',10)
a.addattr('bar',20)
a.foo
a.bar
b=Person()
b.addattr('spam','somevalue')
b.spam

rawDescription: Python - Dynamic variables

description: Python - Dynamic variables


code:
import itertools

def getStartEnd(sequence):
    start = sequence[0]
    end = sequence[-1]
    start_count = sum(1 for _ in itertools.takewhile(lambda ch: ch == start, sequence))
    end_count = sum(1 for _ in itertools.takewhile(lambda ch: ch == end, reversed(sequence)))
    return start_count, end_count

rawDescription: Function does not work properly in for loop - Python


code:
def power_read(fhandle, identifiers):
    findme = '(?<=%s\W)[0-9.]+' %identifiers[0]
    result = np.zeros(10000)
    cnt = 0
    ALL = fhandle.read()
    fhandle.close()
    found = re.findall(findme, ALL, flags=re.S)
    for f in found:
        result[cnt] = float(f)
    return result[0:cnt]

rawDescription: quick parsing of csv-like file

description: Quick parsing of csv-like file


code:
condition.acquire()
while not queue.has_free_place():
    condition.wait()
add_new_thread_to_queue()
condition.release()

rawDescription: Python - Best practices to queue / dequeue threads


rawDescription: Secondary axis with twinx(): how to add to legend?


code:
from google.appengine.ext import endpoints

@endpoints.api(...)
class SomeClass(...):

    @User.method(request_fields=('email',),
                 path='get_by_mail/{email}',
                 http_method='GET', name='user.get_by_email')
    def get_by_email(self, user):
        if not user.from_datastore:
            raise endpoints.NotFoundException('User not found.')
        return user

rawDescription: Query endpoint user by email

description: Query endpoint user by email


code:
a = NonReturningAdder()
b = ReturningAdder()

rawDescription: What is the difference between `super(...)` and `return super(...)`?


code: results.extend(int(x) for x in values[:3])

rawDescription: remove characters from a list in python\pygame

description: Remove characters from a list in python\pygame


code:
from itertools import islice

for sub in l:
    for a, b, c in zip(islice(sub, 0, None), islice(sub, 1, None), islice(sub, 2, None)):
        if all((a[-1] == "JJ", b[-1] == "CC", c[-1] == "JJ")):
            print("{} {} {}".format(a[0], b[0], c[0]))

rawDescription: How do I extract patterns from lists of POS tagged words? NLTK

description: Extract patterns from lists of POS tagged words? NLTK


code:
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
a = np.array([[1,2,3,-1,5,6],
     [1,-1,3,4,5,6],
     [1,2,3,4,-1,6]])
x = np.array([1,2,3,4,5,6])

A = np.ma.array(a, mask=a<0)

plt.plot(x, A.T)

rawDescription: plot a curve from an array with variable x axis

description: Plot a curve from an array with variable x axis


rawDescription: Pandas - write Multiindex rows with to_csv


code:
import numpy as np
from scipy import stats

a = np.array([[1, 3, 4, 2, 2, 7],
              [5, 2, 2, 1, 4, 1],
              [3, 3, 2, 2, 1, 1]])

m = stats.mode(a)
print(m)

rawDescription: Most efficient way to find mode in numpy array


code: num.divide(denom, axis='index')

rawDescription: pandas apply lambda multiple arguments no query different dataframes

description: Pandas apply lambda multiple arguments no query different dataframes


rawDescription: Coverting Hex array to Decimal in Python


code:
dicts = [{k: v} for (k,v) in myDict.items()]
dicts.sort(key=lambda d: (d.values()[0]['site_location'], d.values()[0]['serial_num'],))

rawDescription: Sort Dictionary of Dictionaries on multiple child dictionary values


code: a = [element['total'] for element in i['counts']]

rawDescription: Colouring the area under curve of plotted list


code:
def gen_portfolio(categories):
  n = len(categories)
  tarr = [0] * (n+1)
  parr = [0] * (n+1)
  karr = [0] * (n+1)
  marr = [ len(c) for c in categories ]
  i = 0
  while True:
    while True:
      if i < n:
        p = categories[i][ karr[i] ]
        t = tarr[i] + p
        if t <= 100:
          parr[i] = p
          tarr[i+1] = t
          i += 1
          karr[i] = 0
          continue
        else:
          break                   # backup
      else:
        parr[n] = 100 - tarr[n]   # set the Cash percentage
        yield parr[:]             # yield a copy of the array parr
        break
    # backup
    while True:
      if i > 0:
        i -= 1
        karr[i] += 1
        if karr[i] < marr[i]: break
      else:
        return  # done!

def portfolios2():
  cats = [ [ 10, 15, 20, 25, 30 ], [ 25, 30, 35, 40, 45, 50 ], [ 10, 15, 20 ], [ 20, 25, 30, 35, 40, 45, 50 ] ]
  return gen_portfolio(cats)

rawDescription: Python - most efficient way to generate combinations of large sets subject to criteria?


code:
string = str({"metadata":{"result_type":"recent","iso_language_code":"et"},
            "created_at":"Tue Dec 03 01:41:53 +0000 2013","id":407686093790662656,"id_str":"407686093790662656","text":"@emblems123 justinbieberfan12599@gamil.com","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":False,"in_reply_to_status_id":407677310821613569,"in_reply_to_status_id_str":"407677310821613569","in_reply_to_user_id":2201997043,"in_reply_to_user_id_str":"2201997043","in_reply_to_screen_name":"emblems123","user":{"id":1220098345,"id_str":"1220098345","name":"PYD","screen_name":"bieberfan12599","location":"NY"}})

rawDescription: Print single word from Parsed Json text

description: Print single word from Parsed Json text


code:
item = QTableWidgetItem()
item.setData(QtCore.Qt.EditRole, 5)

rawDescription: How validate a cell in QTableWidget?

description: How validate a cell in QTableWidget


code:
cols = ['Level_1','Level_2','Level_3','User_ID','User_Flag']
data = [['A','B','C',123,1],
        ['A','B','C',123,0],
        ['D','B','C',124,1],
        ['E','B','C',125,0],
        ['F','B','C',125,1]]
df = pd.DataFrame(data, columns=cols)

agg_dict = {'User_ID':[len,pd.Series.nunique],
            'IDFlag':pd.Series.nunique}

df.loc[df['User_Flag'] == 1, 'IDFlag'] = df.User_ID
output = df.groupby(['Level_1','Level_2','Level_3']).agg(agg_dict)

output = output.astype(int)

rawDescription: Pandas group by into another dataframe

description: Pandas group by into another dataframe


code:
from operator import attrgetter

index = bisect_left(L, x, key=attrgetter('attr_a'))

rawDescription: Searching an attribute_A in a attribute_B-sorted list


code:
x = np.arange(6).reshape(2,3)
x
y = np.zeros((2,3,4))
y[...,:3] = x[...,np.newaxis]
y
np.allclose(y[...,0], x)
np.allclose(y[...,1], x)
np.allclose(y[...,2], x)

rawDescription: Assign same value to different ndarray indices - Python


code: [item.get_ydata()[0] for item in B['whiskers']]

rawDescription: Obtaining values used in boxplot, using python and matplotlib


code:
from collections import defaultdict

example_dictionary = defaultdict(list)
for item in root_values:
    example_dictionary[item['name']].append(item['value'])

rawDescription: Initialize List to a variable in a Dictionary inside a loop


code:
tm = MessageListModel()
for msg in self.aMessages.itervalues():
    tm.addItem(msg[1], msg[0])
ListView.setModel(tm)

rawDescription: Message displaying in QListWidget/View on boolean condition


code:
[{"param331": [tab - 5.0 for tab in myTab],
  "param332": [tab + 5.0 for tab in myTab]}]

rawDescription: How to assign floats to some fields of json dumps using a for loop

description: Assign floats to some fields of json dumps using a for loop


code:
class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserUsernameRetrieve(UserIdRetrieve):
     lookup_field = 'username'

rawDescription: Django Rest required parameters in URL

description: Django Rest required parameters in URL


rawDescription: Can I open an application using python during run time

description: Open an application using python during run time


rawDescription: Creating a heatmap without a colorbar in matplotlib


code:
with open('fileName', 'w') as f:
    f.write(yourString.format(band_subset, spatial_subset_1, spatial_subset_2, para1))

rawDescription: Writing a text file using python

description: Writing a text file using python


code: Literal('alpha') & 'beta' & 'gamma'

rawDescription: pyparsing matching any combination of specified Literals

description: Pyparsing matching any combination of specified Literals


code:
for item in iterable: pass
largest = item

rawDescription: Few questions on generator expressions and speed efficient alternatives


rawDescription: Is there a good reference list for the names of the genericsetup import steps


code:
df3 = df1.merge(df2)
df3
df3[(df3["pos-start"] < df3["pos"]) & (df3["pos"] < df3["pos-end"])]

rawDescription: Merging pandas dataframes on multiple conditions (python/pandas)


code:
marmalade
breakfast

rawDescription: using multiple parameters in python function

description: Using multiple parameters in python function


code: no_singletons = [p for p in with_singletons if ' ' in p]

rawDescription: List ordering in Python. Very simple

description: List ordering in Python. Very simple


rawDescription: re methods in python to append string

description: Re methods in python to append string


code: sum(int(i) for i in str(123))

rawDescription: Sum of digits of a number using While

description: Sum of digits of a number using While


code:
db.define_table('mytable',
    Field('field1', 'integer'),
    Field('field2', 'double'),
    Field('field3', 'boolean'))

rows = db.executesql(db(db.mytable.id > 0)._select())
data = DataFrame.from_records(rows, columns=db.mytable.fields)

rawDescription: web2py webserver - Best way to keep connection to external SQL server?

description: Web2py webserver - Best way to keep connection to external SQL server


code: SillyWalk.walk.im_func.func_defaults[0] # the default argument to .walk

rawDescription: Using class/static methods as default parameter values within methods of the same class


code:
import re

def split_name(filename):
    match = re.match(r'(.*?)(\d+\.[^.]+)', filename)
    if match:
        return match.groups()
    else:
        return None, None

for name in [ 'foo123.jpg', 'bar;)234.png', 'baz^_^456.JPEG', 'notanumber.bmp' ]:
    prefix, suffix = split_name(name)
    print("prefix = %r, suffix = %r" % (prefix, suffix))

rawDescription: Python re.search re.sub string

description: Python re.search re.sub string


code:
right = False
def func():
    global right
    right = True
func()
print (right)

rawDescription: Arrow key input code not working in tkinter


rawDescription: Something about python class

description: Something about python class


code: (df.apply(pd.Series.nunique, axis=1) == 1).astype(int)

rawDescription: Checking column values in python panda

description: Checking column values in python panda


rawDescription: Pythonic loops--how to get multiple elements while iterating a list


code:
@login_required
def add_category(request):
    if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
        return render(request,'main/category_already_exists.html')
    if request.method == 'POST':
        category = Category(author=request.user)
        form = CategoryForm(request.POST, request.FILES, instance=category)
        if form.is_valid():
            form.save(commit=True)
            request.session['categories'] = [ c.name for c in Category.objects.filter(author=request.user)]
            return redirect('category', category_name_url=category.name)

    else:
        form = CategoryForm()
    context = {
        "form":form
    }
    return render(request, 'main/add_category.html',context)

rawDescription: how to to display the category user created by the current user on every page

description: To display the category user created by the current user on every page


code: res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))

rawDescription: How to sort a Python dict by value

description: Sort a Python dict by value


code:
map(str.strip, string.split(','))
#   ^- apply the 'strip' function (~ 'trim' in other languages) to all matches

rawDescription: Splitting a string via regex problems

description: Splitting a string via regex problems


code:
for function in sensor['convert']:
    variables = sensor['convert'][function]
    result = globals()[function](*variables)

rawDescription: Can I store Python function on a MongoDB collection?

description: Store Python function on a MongoDB collection


code:
derp = myfont.render("Derp",newSat,(r,g,b))
newX = random.randint(1,800 - derp.get_width())
newY = random.randint(1,600 - derp.get_height())

rawDescription: Pygame screen width

description: Pygame screen width


code:
for i in range(2,20): print(i,isPrime(i))
isPrime(531455)
isPrime(531457)

rawDescription: How can I work out how long a factorial will take in Python?

description: Work out how long a factorial will take in Python


rawDescription: How to check if a value exists in a dictionary (python)

description: Check if a value exists in a dictionary (python)


code:
class ClosestDict(dict):
    def get(self, key):
        key = min(self.iterkeys(), key=lambda x: abs(x - key))
        return dict.get(self, key)

d = ClosestDict({10: 3, 100: 2, 1000: 1})
print (d.get(20), d.get(60), d.get(200))

rawDescription: Custom dictionary lookup in Python

description: Custom dictionary lookup in Python


code:
from PIL import Image, ImageDraw, ImageFont

# Declare font files and encodings
FONT1 = ('Jin_Wen_Da_Zhuan_Ti.ttf',          'unicode')
FONT2 = ('Zhong_Guo_Long_Jin_Shi_Zhuan.ttf', 'big5hkscs')
FONT3 = ('Zhong_Yan_Yuan_Jin_Wen.ttf',       'big5hkscs')

# Declare a mapping from encodings used by str.encode() to encodings used by
# the FreeType library
ENCODING_MAP = {'unicode':   'unic',
                'big5':      'big5',
                'big5hkscs': 'big5',
                'shift-jis': 'sjis'}

# The glyphs we want to draw
GLYPHS = ((FONT1, u'\u6211'),
          (FONT2, u'\u6211'),
          (FONT3, u'\u6211'),
          (FONT3, u'\u66ce'),
          (FONT2, u'\u4e36'))

# Returns PIL Image object
def draw_glyph(font_file, font_encoding, unicode_char, glyph_size=128):

    # Translate unicode string if necessary
    if font_encoding != 'unicode':
        mb_string = unicode_char.encode(font_encoding)
        try:
            # Try using Python 2.x's unichr
            unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
        except NameError:
            # Use Python 3.x-compatible code
            unicode_char = chr(mb_string[0] << 8 | mb_string[1])

    # Load font using mapped encoding
    font = ImageFont.truetype(font_file, glyph_size, encoding=ENCODING_MAP[font_encoding])

    # Now draw the glyph
    img = Image.new('L', (glyph_size, glyph_size), 'white')
    draw = ImageDraw.Draw(img)
    draw.text((0, 0), text=unicode_char, font=font)
    return img

# Save an image for each glyph we want to draw
for (font_file, font_encoding), unicode_char in GLYPHS:
    img = draw_glyph(font_file, font_encoding, unicode_char)
    filename = '%s-%s.png' % (font_file, hex(ord(unicode_char)))
    img.save(filename)

rawDescription: Generate character images with a font whose name cannot be correctly decoded


rawDescription: python RE: Non greedy matches, repitition and grouping

description: Python RE: Non greedy matches, repitition and grouping


code: df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index

rawDescription: Delete column from pandas DataFrame

description: Delete column from pandas DataFrame


code:
a = [[0,1,2],[3,0,0],[5,6,0]]
no_zeroes = [r[:i] + r[i+1:] for i, r in enumerate(a)]
no_zeroes
sorted_no_zeroes = [sorted(r, reverse=True) for r in no_zeroes]
sorted_no_zeroes
sorted_with_zeroes = [r[:i] + [0] + r[i:] for i, r in enumerate(sorted_no_zeroes)]
sorted_with_zeroes

rawDescription: Sort array in Python without modifying specific element positions


code: listBstrings = {tuple(lst[1:]): lst[0] for lst in listB}

rawDescription: Python join two nested lists

description: Python join two nested lists


code:
imported_foo = importlib.import_module('foo')
globals().update(vars(imported_foo))

rawDescription: Python import lib analogue to "import * from XXX"


code:
input_text = 'Hello World!'
print(''.join('\\u{:04x}'.format(ord(c)) for c in input_text))
input_text = 'Hello world with an em-dash: \u2014\n'
print(''.join('\\u{:04x}'.format(ord(c)) for c in input_text))

rawDescription: String to unicode code point escpe sequences in Python


rawDescription: python list manipulation nesting vertically, making it look like a matrix

description: Python list manipulation nesting vertically, making it look like a matrix


code:
class Completion(models.Model):
    start_date = models.DateField(validators=[validate_current_century])
    end_date = models.DateField(validators=[validate_current_century])

rawDescription: How to restrict user to select date between range of years in django?

description: Restrict user to select date between range of years in django


code:
def main():
    correct = do_quiz()
    print("\nYou solved {} of 10 questions".format(correct))

if __name__ == "__main__":
    main()

rawDescription: Finding something that checks if a particular Arithmetic answer is correct


code:
import json

json.loads(x)

rawDescription: Convert Python string to list

description: Convert Python string to list


code:
lines = vincent.Line(df)
lines.scales[0].type = 'ordinal'
lines.axis_titles(x='WEEKS', y='SCORE')
lines.legend(title='Player')

rawDescription: Creating a multiline graph using Vincent


code: colorder[col1], colorder[col2] = colorder[c2], colorder[c1]

rawDescription: Matrix data structure

description: Matrix data structure


code:
import dis
dis.dis(f)

rawDescription: Assign variable to local scope of function in Python


rawDescription: NumPy: 2D array from a list of arrays and scalars


code:
price_list = [i.get('p') for i in ticket_info]
price_list

rawDescription: How to parse JSON data in scrapy

description: Parse JSON data in scrapy


code: ti,xi = np.meshgrid(ti,xi)

rawDescription: Why is my 2D interpolant generating a matrix with swapped axes in SciPy?


rawDescription: Viewing the content of a Spark Dataframe Column


code:
def foo(x, y):
   return x**2, y**2

a = 1
b = 2
a, b = foo(a, b)

rawDescription: Python functions call by reference

description: Python functions call by reference


code:
status_counts = db.session.query(BarBaz.status, db.func.count(BarBaz.id).label('count_id')
).filter(db.not_(db.or_(BarBaz.name == 'Foo', BarBaz.name == 'Bar'))
).group_by(BarBaz.status
).all()

rawDescription: Convert SQL to SQL alchemy

description: Convert SQL to SQL alchemy


rawDescription: How to find number of users, number of users with a profile object, and monthly logins in Django

description: Find number of users, number of users with a profile object, and monthly logins in Django


code: parser = "foo" + foo_parser | "bar" + bar_parser

rawDescription: choose parser based on previous results

description: Choose parser based on previous results


code:
def sum_range(a, b):
    r_a = (a ** 2 + a) / 2 - a
    r_b = (b ** 2 + b) / 2 - b
    return r_b - r_a

rawDescription: Decorator to time specific lines of the code instead of whole method?


rawDescription: Find in the matrix the first row, in which all elements are arranged in descending order.


code:
from PIL import Image
import numpy as np
import scipy as sp
import matplotlib.colors as colors
from sklearn.cluster import DBSCAN
from math import ceil, sqrt

"""
Inputs:

    rgbimg:         [M,N,3] numpy array containing (uint, 0-255) color image

    hueleftthr:     Scalar constant to select maximum allowed hue in the
                    yellow-green region

    huerightthr:    Scalar constant to select minimum allowed hue in the
                    blue-purple region

    satthr:         Scalar constant to select minimum allowed saturation

    valthr:         Scalar constant to select minimum allowed value

    monothr:        Scalar constant to select minimum allowed monochrome
                    brightness

    maxpoints:      Scalar constant maximum number of pixels to forward to
                    the DBSCAN clustering algorithm

    proxthresh:     Proximity threshold to use for DBSCAN, as a fraction of
                    the diagonal size of the image

Outputs:

    borderseg:      [K,2,2] Nested list containing K pairs of x- and y- pixel
                    values for drawing the tree border

    X:              [P,2] List of pixels that passed the threshold step

    labels:         [Q,2] List of cluster labels for points in Xslice (see
                    below)

    Xslice:         [Q,2] Reduced list of pixels to be passed to DBSCAN

"""

def findtree(rgbimg, hueleftthr=0.2, huerightthr=0.95, satthr=0.7,
             valthr=0.7, monothr=220, maxpoints=5000, proxthresh=0.04):

    # Convert rgb image to monochrome for
    gryimg = np.asarray(Image.fromarray(rgbimg).convert('L'))
    # Convert rgb image (uint, 0-255) to hsv (float, 0.0-1.0)
    hsvimg = colors.rgb_to_hsv(rgbimg.astype(float)/255)

    # Initialize binary thresholded image
    binimg = np.zeros((rgbimg.shape[0], rgbimg.shape[1]))
    # Find pixels with hue<0.2 or hue>0.95 (red or yellow) and saturation/value
    # both greater than 0.7 (saturated and bright)--tends to coincide with
    # ornamental lights on trees in some of the images
    boolidx = np.logical_and(
                np.logical_and(
                  np.logical_or((hsvimg[:,:,0] < hueleftthr),
                                (hsvimg[:,:,0] > huerightthr)),
                                (hsvimg[:,:,1] > satthr)),
                                (hsvimg[:,:,2] > valthr))
    # Find pixels that meet hsv criterion
    binimg[np.where(boolidx)] = 255
    # Add pixels that meet grayscale brightness criterion
    binimg[np.where(gryimg > monothr)] = 255

    # Prepare thresholded points for DBSCAN clustering algorithm
    X = np.transpose(np.where(binimg == 255))
    Xslice = X
    nsample = len(Xslice)
    if nsample > maxpoints:
        # Make sure number of points does not exceed DBSCAN maximum capacity
        Xslice = X[range(0,nsample,int(ceil(float(nsample)/maxpoints)))]

    # Translate DBSCAN proximity threshold to units of pixels and run DBSCAN
    pixproxthr = proxthresh * sqrt(binimg.shape[0]**2 + binimg.shape[1]**2)
    db = DBSCAN(eps=pixproxthr, min_samples=10).fit(Xslice)
    labels = db.labels_.astype(int)

    # Find the largest cluster (i.e., with most points) and obtain convex hull
    unique_labels = set(labels)
    maxclustpt = 0
    for k in unique_labels:
        class_members = [index[0] for index in np.argwhere(labels == k)]
        if len(class_members) > maxclustpt:
            points = Xslice[class_members]
            hull = sp.spatial.ConvexHull(points)
            maxclustpt = len(class_members)
            borderseg = [[points[simplex,0], points[simplex,1]] for simplex
                          in hull.simplices]

    return borderseg, X, labels, Xslice

rawDescription: How to detect a Christmas Tree?

description: Detect a Christmas Tree


code:
for key,value in abridged_data.items():
    x = value[:,0]
    y = value[:,1]
    plt.plot(x,y,label=key)
plt.show()

rawDescription: Plotting with Numpy Arrays

description: Plotting with Numpy Arrays


code:
import log
logger = log.setup_custom_logger('root')
logger.debug('main message')

import submodule

rawDescription: Python: logging module - globally

description: Python: logging module - globally


code:
grouped = {}
for tup in information:
    grouped.setdefault(tup[0], []).append(tup)

bestvalues = {}
for group in grouped.itervalues():
    best = max(group, key=lambda g: g[2])
    bestvalues[tuple(best[:2])] = best[2]

rawDescription: Get the max value for given keys in a dictionary?


code:
out = open('file name', 'w')
for l in result:
  out.write(l)

rawDescription: How to pick lines containg numbers in given positions on the line with python

description: Pick lines containg numbers in given positions on the line with python


code:
from fabric.api import *
# Fabric related conf
env.disable_known_hosts = False
env.reject_unknown_hosts = False
env.use_ssh_config = True
env.connection_attempts = 3
env.coloreize_errors = True
env.forward_agent = True
pool_size=len(env.hosts)

@parallel(pool_size=pool_size)
def update_workers():
    sudo("aptitude update")
    #skip grub update.
    sudo("DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" dist-upgrade")

@parallel(pool_size=pool_size)
def copy_conf_to_worker(local_path):
    env.host_string = env.host
    result = put(local_path,'/tmp/',use_sudo=False)

rawDescription: Fabric, @parallel and dynamically changing hosts


code:
g
g[np.arange(len(g)) != 1]

rawDescription: Conditional index in 2d array in python

description: Conditional index in 2d array in python


code:
links = soup.findAll('a')
pprint(links)

rawDescription: How would I get the text AFTER a link in Python with BeautifulSoup?


code:
def parse(self, response):
    name = response.meta.get('name')
    ...

rawDescription: give names to start_urls in scrapy

description: Give names to start_urls in scrapy


rawDescription: How to check if my list has an item from another list(dictionary)?

description: Check if my list has an item from another list(dictionary)


code:
import os
import subprocess

subprocess.call(['ls', os.path.expanduser('~') + '/testing/;xterm;/blabla'])

rawDescription: How to avoid Shell Injection with a path variable and wait for command exist?

description: Avoid Shell Injection with a path variable and wait for command exist


code: filelist = [line.strip('\n').split('\t') for line in F][1:]

rawDescription: Python: reading line from file with different types of variables


code:
question = self.questions.next()
self.CurrentQString.configure(text=question)

rawDescription: Repeatedly iterating through a list, with buttons and bindings


code:
y_minor_ticks = ax.yaxis.get_minor_ticks()
y_minor_ticks[0].label.set_visible(False)

rawDescription: Matplotlib: add custom tick label and remove custom tick on y-axis


code: parent = models.ForeignKey(Post, related_name='comments')

rawDescription: Get comments of Post (one to many relation)


code:
def draw(fig, sub_plot_args,x,y):
    ax = fig.subplot(*sub_plot_args)
    ax.scatter(x,y)

rawDescription: What is an idiomatic way to specify a matplotlib figure and axes to a function?


rawDescription: Python: compare keys of 2 dictionaries and update the value of one


code:
df['Xcnt'] = df.groupby('c1')['Xcnt'].fillna(method='ffill')
df['Ycnt'] = df.groupby('c1')['Ycnt'].fillna(method='ffill').fillna(0)
df

rawDescription: cumcout groupby --- how to list by groups

description: Cumcout groupby --- how to list by groups


code:
from sklearn.datasets import make_regression

# simulate a dataset with 500 factors, but only 5 out of them are truely
# informative factors, all the rest 495 are noises. assume y is your response
# variable 'Sales', and X are your possible factors
X, y = make_regression(n_samples=1000, n_features=500, n_informative=5, noise=5)

X.shape
Out[273]: (1000, 500)
y.shape
Out[274]: (1000,)

from sklearn.feature_selection import f_regression
# regressing Sales on each of factor individually, get p-values
_, p_values = f_regression(X, y)
# select significant factors p < 0.05
mask = p_values < 0.05
X_informative = X[:, mask]

X_informative.shape
Out[286]: (1000, 38)

rawDescription: Using Python to find correlation pairs

description: Using Python to find correlation pairs


code:
import numpy as np
from scipy import stats
np.random.seed(2016)
h, w = 3, 4

x=np.random.random_integers(4,9,(h,w))
y=np.random.random_integers(4,9,(h,w))

result = np.ones((h,w))
for row in range(h):
    result[row,:] = np.array([stats.binom_test(x[row,_], x[row,_]+y[row,_])
                              for _ in range(w)])

binom_test = np.vectorize(stats.binom_test)
result2 = binom_test(x, x+y)

assert np.allclose(result, result2)
print(result2)

rawDescription: Given two numpy arrays of same size, how to apply a function two each pair of elements at identical position?


code:
# admin.py
from django.contrib import admin

class MembershipInline(admin.TabularInline):
    model = Membership

class DivisionAdmin(admin.ModelAdmin):
    inlines = [
        MembershipInline,
    ]

class PlayerAdmin(admin.ModelAdmin):
    inlines = [
        MembershipInline,
    ]

rawDescription: Simple way to show group members in Django Admin?


code:
import datetime
datestr = "2010-10-12T08:40:01"
datetime.datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%S')

rawDescription: how to parse time stamps in Python from PyPI packages (eg. 12-Oct-2010 06:40)

description: Parse time stamps in Python from PyPI packages (eg. 12-Oct-2010 06:40)


code:
with open("table.csv", "rU") as f:
    output = sorted([line.split(',')[7].strip() for line in f][1:])

rawDescription: Getting a column into an array from excel in python


code:
import scrapy

class MySpider(scrapy.Spider):
    name = "deez"
    start_urls = ["http://www.deezer.com/profile/154723101"]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, self.parse, meta={
                'splash': {
                    'endpoint': 'render.html',
                    'args': {'wait': 1}
                }
            })

    def parse(self, response):
        print(response.xpath("//li[@class='evt-click']").extract())

rawDescription: Why Scrapy cannot find href here?

description: Why Scrapy cannot find href here


code:
#smax.on_changed(update)
chain2 =  chain.generalise(tol)
pp.plotPolylines(chain2)

def update(val):
    tol = tolerance.val # get the value from the slider
    chain2 =  chain.generalise(tol) # shove that value into your code
    ax.cla() # clear the axes
    pp.plotPolylines(chain2) # re-plot your new results

# register the call back
tolerance.on_changed(update)

rawDescription: Matplotlib scroll bar

description: Matplotlib scroll bar


code:
import numbers
sorted(l, key=lambda x: (isinstance(x, numbers.Number), x))

rawDescription: Sorting hybrid lists in Python

description: Sorting hybrid lists in Python


rawDescription: union of two mongoDB documents

description: Union of two mongoDB documents


code: myvar = f.readline().rstrip()

rawDescription: f.readline() != '0' even if reading a line containing only 0

description: F.readline() != '0' even if reading a line containing only 0


code: self.connection = sqlite3.connect(os.path.join(_module_directory, 'feedback.db'))

rawDescription: Sqlite query returns different results from different classes


code:
import json
a = { 'foo' : 'bar' }
s_a = json.dumps(a)
s_s_a = json.dumps(s_a)
a
s_a
s_s_a

rawDescription: Serialize an already serialized json string?


code:
from django.core.urlresolvers import reverse

messages.warning(request, 'WARNING! You have not set your custom URL for this profile. You can set this HERE.' % reverse('change_url'))

rawDescription: Warning message should contain a LINK to a next page


code:
plot.text(0.05, 0.95, df2['example'].values,
     horizontalalignment='left',
     verticalalignment='center',
     transform = ax.transAxes)

rawDescription: Python -- how to plot calculated number on chart without properties detail


rawDescription: Converting string into dictionary containing sets


code: ''.join( ','.join(row) + '\n' for row in mylist)

rawDescription: Insert new row every 2nd element of python list


code:
import pygame
import math
from itertools import cycle

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

# some simple vector helper functions, stolen from http://stackoverflow.com/a/4114962/142637
def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]

def dot(u, v):
    return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

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

class Ball(object):

    def __init__(self, path, screen):
        self.x, self.y = (0, 0)
        self.speed = 2.5
        self.color = (200, 200, 200)
        self.path = cycle(path)
        self.set_target(next(self.path))

        self.screen = screen

    @property
    def pos(self):
        return self.x, self.y

    # for drawing, we need the position as tuple of ints
    # so lets create a helper property
    @property
    def int_pos(self):
        return map(int, self.pos)

    @property
    def target(self):
        return self.t_x, self.t_y

    @property
    def int_target(self):
        return map(int, self.target)

    def next_target(self):
        self.set_target(self.pos)
        self.set_target(next(self.path))

    def set_target(self, pos):
        self.t_x, self.t_y = pos

    def update(self):
        # if we won't move, don't calculate new vectors
        if self.int_pos == self.int_target:
            return self.next_target()

        target_vector = sub(self.target, self.pos)

        # a threshold to stop moving if the distance is to small.
        # it prevents a 'flickering' between two points
        if magnitude(target_vector) < 2:
            return self.next_target()

        # apply the balls's speed to the vector
        move_vector = [c * self.speed for c in normalize(target_vector)]

        # update position
        self.x, self.y = add(self.pos, move_vector)

    def draw(self):
        pygame.draw.circle(self.screen, self.color, self.int_pos, 4)

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

def run(screen):

    #pygame.init() # no need it - inited in menu.py
    #screen = pygame.display.set_mode((300, 300))  # no need it - created in menu.py

    clock = pygame.time.Clock()

    quit = False

    path = [(26, 43),
            (105, 110),
            (45, 225),
            (145, 295),
            (266, 211),
            (178, 134),
            (250, 56),
            (147, 12)]

    path2 = [(26, 43),
             (105, 10),
             (45, 125),
             (150, 134),
             (150, 26),
             (107, 12)]

    ball = Ball(path, screen)
    ball.speed = 1.9

    ball2 = Ball(path2, screen)
    ball2.color = (200, 200, 0)

    balls = [ball, ball2]

    while not quit:
        quit = pygame.event.get(pygame.QUIT)
        pygame.event.poll()

        map(Ball.update, balls)

        screen.fill((0, 0, 0))

        map(Ball.draw, balls)

        pygame.display.flip()
        clock.tick(60)

rawDescription: Combine effects to menu in pygame

description: Combine effects to menu in pygame


code:
@classmethod
def change_immutable(cls, self):
    if len(self.instance_attr) == 1:
        cls.immutable_attr = True

rawDescription: Mutating objects referenced by class attributes through instance methods


code:
def key(x):
    x = ''.join([i for i in x if i.isdigit() or i=='_'])
    return '{1:{f}{a}10}_{2:{f}{a}10}_{3:{f}{a}10}'.format(*x.split('_'), f='0', a='>')

d = mysort(data, 'MyColumn', key)

rawDescription: Sorting numpy matrix for a given column

description: Sorting numpy matrix for a given column


code:
import cloud
def my_func(x):
   import your_fortran_module
   return your_fortran_module.function(x)

cloud.setkey(api-key, api-secretkey)
cloud.rest.publish(my_func, "label_of_my_func", _env="your_environment")

rawDescription: Call a library uploaded in PiCloud from GAE?


code:
orig_str = 'this is a test string ababababa'
stopwords = ['rin', 'hi', 'tri', 'ababa']

rawDescription: Python regex for quickly removing any possible instances of substrings?


code:
import csv

def nested_list_formatter(nested):
    return tuple(','.join(str(item) for item in sublist) for sublist in nested)

def test():
    list1 = [[1, 2, 3, 4], [3, 2, 5], [9, 3, 6, 8, 4]]
    list2 = [[2, 2, 4, 4], [1, 9, 10], [2, 7, 7, 4, 5]]
    with open('doc.csv', 'w', newline='') as file:
        writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow(nested_list_formatter(list1))
        writer.writerow(nested_list_formatter(list2))

if __name__ == '__main__':
    test()

rawDescription: Write list of lists to csv row

description: Write list of lists to csv row


code:
class RssFeed(Base):
    __tablename__ = 'rssfeeds'
    id = Column(Integer, primary_key=True)
    url = Column(String)

rawDescription: Using list as a data type in a column (SQLAlchemy)


code:
from sys import argv

run, filename = argv

f = open(filename)
lines = f.readlines()
f.close()
f = open(filename, 'w')
for line in lines:
    f.write(line[1:])
f.close()

rawDescription: remove first char from each line in a text file

description: Remove first char from each line in a text file


code:
from pandas.tseries.frequencies import to_offset
pd.to_timedelta(to_offset('30T'))

rawDescription: Convert pandas freq string to timedelta

description: Convert pandas freq string to timedelta


code: return [[x/10] for x in tup]

rawDescription: Multiple iterations over different arguments in a tuple (python)


rawDescription: If dictionaries aren't ordered, why do two dictionaries with the same key names return values in the same order?


rawDescription: What's the best way to greyscale in python/django?


code: someobject.lastUpdate = datetime.now()

rawDescription: Fix "unsupported date format" when marshaling data from rest endpoint


code:
df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))
df.where(checkerboard)

rawDescription: Slicing Pandas DataFrame with a Checkerboard Pattern


code:
import random
def random_digits(n):
  range_start = 10**(n-1)
  range_end = (10**n)-1
  random_number= random.randint (range_start, range_end)
  print(random_number)
  return (random_number)

def countzeros(n):
  print(len([c for c in str(n) if c == '0']))

countzeros(random_digits(20))

rawDescription: how to make a function that checks a list of 20 digits

description: Make a function that checks a list of 20 digits


rawDescription: simple regex for following string

description: Simple regex for following string


code:
def login2Subscribe(link):
    return link.replace('https://www.google.com/accounts/ServiceLogin', 'https://accounts.google.com/NewAccount').replace('passive=true', '')

rawDescription: Have user sign up with Google and get redirected back to the site afterwards?


code:
a = '''....xx....
...x..x...
...x..x...
...x..x...
....xx....'''

chars = [ [c for c in line] for line in a.split ('\n') ]
floodfill (chars, 0, 0)
print ('\n'.join (''.join (c for c in line) for line in chars) )

print ('-' * 20)

chars = [ [c for c in line] for line in a.split ('\n') ]
floodfill (chars, 5, 3)
print ('\n'.join (''.join (c for c in line) for line in chars) )

rawDescription: Recursive Function to change both <x and y> in a matrix?


code:
from PIL import Image
im = Image.open("img000.jpg")

rawDescription: Python: Serial Transmission

description: Python: Serial Transmission


rawDescription: how to tell Python that we always want to interpret an object of type Foo as an object of type Bar when there are conflicts?

description: Tell Python that we always want to interpret an object of type Foo as an object of type Bar when there are conflicts


rawDescription: How can I keep this Pandas column type as datetime when using MultiIndex?

description: Keep this Pandas column type as datetime when using MultiIndex


code:
PATH_TO_MY_EXTERNAL_PROGRAM = r"C:\ProgramFiles\MyProgram\MyProgramLauncher.exe"
os.system(PATH_TO_MY_EXTERNAL_PROGRAM)

rawDescription: Python script waiting for some program being launched and then starting another program. (Windows)


rawDescription: SearchCtrl in wxPython looks different

description: SearchCtrl in wxPython looks different


code:
import sys
from PyQt4 import QtCore, QtGui

class TextEditorDlg(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TextEditorDlg, self).__init__(parent)
        self.resize(500, 400)

        self.button = QtGui.QPushButton(self)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)

        self.grid = QtGui.QGridLayout(self)

        # Use the row-span and column-span arguments!
        self.grid.addWidget(self.button, 0, 0, 1, 1)
        self.grid.addWidget(self.lineEdit, 1, 0, 1, 3)
        self.grid.addWidget(self.textEdit, 2, 0, 1, 3)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

rawDescription: Can't change size within layout

description: Can't change size within layout


code: obj = Actual(**dict(l[0]))

rawDescription: Python create list of objects from list of 2 elements lists


code: a = [format(i + 1, '03d') for i in range(300)]

rawDescription: Creating list of defined number pattern

description: Creating list of defined number pattern


code:
def is_digit(n1,op,n2):
    while True:
        try:
            n = int(input("What is {} {} {} ?".format(n1,op,n2)))
            return n
        except ValueError:
            print("Invalid input")

for _ in range(a):
    question = is_digit(n1,op,n2) # will only return a value when we get legal input
    ans = ops[op](n1, n2)
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")

rawDescription: How to type negative number with .isdigit?

description: Type negative number with .isdigit


code:
class MainHandler(webapp.RequestHandler):
    def get(self):
        table = self.request.url
        self.response.out.write(table)

rawDescription: app-engine: Request Data

description: App-engine: Request Data


code:
class DeviceView(APIView):
    def get(self, request, format=None):
        battery = Battery.objects.get(id=1)
        charger = Charger.objects.get(id=1)
        # create a dict with required objects and pass it as instance of serializer
        device = {'battery': battery, 'charger': charger, 'some_field': 'some_text'}
        serializer = DeviceSerializer(instance=device)
        return Response(serializer.data)

rawDescription: Django Rest Framework doesn't serialize SerializerMethodField


code:
from django.views.generic.list_detail import object_list
def category_list(request, category_id):
    queryset = ModelObject.objects.filter(category=category_id)
    return object_list(request, queryset=queryset)

rawDescription: Passing arguments to the generic views Django queryset


rawDescription: How can I format a float to variable precision in Python?

description: Format a float to variable precision in Python


code:
import sqlite3
conn = sqlite3.connect('/path/to/my.db')
curs = conn.cursor()
curs.execute("SELECT a_column FROM my_table;").fetchone()
curs.close()
conn.close()

rawDescription: How to create tables in sqlite 3?

description: Create tables in sqlite 3


code:
def flatten(d, prefix=''):
    prefix = prefix + '_' if prefix else ''
    new = {}
    for k, v in d.items():
        if isinstance(v, bool):
            new[prefix + k] = int(v)
        elif isinstance(v, dict):
            new.update(flatten(v, prefix=prefix + k))
        elif isinstance(v, basestring):  # python3 -- str
            new[prefix + k + '_' + v] = 1
        else:
            raise TypeError('Unknown item type.')
    return new

rawDescription: Flatten Python Dict for All Values Down to True/False


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

def plot_refined_tri(x, y, z, ax, subdiv=4, **kwargs):
    triang = tri.Triangulation(x, y)
    refiner = tri.UniformTriRefiner(triang)
    interpolator = tri.LinearTriInterpolator(triang, z)
    new, new_z = refiner.refine_field(z, interpolator, subdiv=subdiv)
    ax.plot_trisurf(new.x, new.y, new_z, triangles=new.triangles, **kwargs)

x=numpy.array([0.00498316, 0.00498316, 0.00996632, 0.00996632])
y=numpy.array([-0.00037677, -0.00027191, -0.00078681, -0.00088475])
z=numpy.array([0., -0.0049926, 0., -0.00744763])

fig = plt.figure()
ax = Axes3D(fig)
# note: I normalized on z-values to "fix" the colormap
norm = plt.Normalize(vmax=z.max(), vmin=z.min())
kwargs = kwargs = dict(linewidth=0.2, cmap=cm.jet, norm=norm)

idx = [3,2,1]
plot_refined_tri(x[idx], y[idx], z[idx], ax, **kwargs)

idx = [1,2,0]
plot_refined_tri(x[idx], y[idx], z[idx], ax, **kwargs)

plt.show()

rawDescription: Shifting the triangles order to match colormap


code:
body = Message.Body

if body.startswith('!'):
    parts = body.split()    # ['!ping', 'google.com']
    command = parts[0][1:]  # 'ping'

    result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
    Message.Chat.SendMessage(result)  # Prints out the resulting string

rawDescription: Skype4py !command with arguments

description: Skype4py !command with arguments


code:
myTree=html.fromstring(someString)
table_tops = set(myTree.cssselect('table'))-set(myTree.cssselect('table table'))

rawDescription: When using LXML why is the body element not the parent of the table element in this snippet of html


code:
df_stack = pd.concat(ids, ignore_index=True)
df_stack['multiple_requests'] = (df_stack['dummy_numeric'] > 1).astype(int)

rawDescription: Count repeating events in pandas timeseries


code:
def getChildForRequest(resource, request):
    """
    Traverse resource tree to find who will handle the request.
    """
    while request.postpath and not resource.isLeaf:
        pathElement = request.postpath.pop(0)
        request.prepath.append(pathElement)
        resource = resource.getChildWithDefault(pathElement, request)
    return resource

rawDescription: Override all default resources / responses from Twisted.web


code:
from django.core.management import call_command

fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))
fixture_filename = 'initial_data.json'

def load_fixture(apps, schema_editor):
    fixture_file = os.path.join(fixture_dir, fixture_filename)
    call_command('loaddata', fixture_file)

rawDescription: Loading initial data with Django 1.7 and data migrations


code:
def application(environ, start_response):
    write = start_response(status, headers)
    write('content block 1')
    return ['content block 2',
            'content block 3']

rawDescription: WSGI: what's the purpose of start_response function


code:
# update_data (imshow)
im.set_data(data2)
plt.draw()

rawDescription: How to update pcolor in matplotlib?

description: Update pcolor in matplotlib


code:
class A(object):
    def __get__(self, cls, instance):
        if instance is not None:
            def wrapper():
                print("I was called with", cls, "and", instance)
            return wrapper
        return self

class B(object):
    a = A()

B.a()

rawDescription: callable object as method of a class - Can I get `self` to be the class that owns the method?

description: Callable object as method of a class - Can I get `self` to be the class that owns the method


code:
tmp = {}
for med in meds:
    name = med.pop('medication_name')
    tmp.setdefault(name, []).append(med)
res = [{'medication_name': k, 'trend': v}  for k, v in tmp.items()]

rawDescription: Merging a list of dicts in python based on common element


rawDescription: How to retain the selection when updating a PyGTK combobox?

description: Retain the selection when updating a PyGTK combobox


code: [y.strip('+-') for y in x]

rawDescription: Python: remove multiple character in list of string


rawDescription: Storing the values of an iteration to a numpy array - Python, Numpy


rawDescription: Getting and storing methods of a python class


code:
def foo(): pass

foo.__call__

rawDescription: Python 'Functions are objects'

description: Python 'Functions are objects'


rawDescription: Pandas Dataframe column with both Strings and Floats


code:
input_SetNum = input("How many data sets are you comparing: ")
print ("You entered " + input_SetNum)

data_sets = {}
for i in range(1, int(input_SetNum)+1):
    data_sets[i] = input("Please enter the file path a data set: ")

print(data_sets)

rawDescription: How to create a number of variables from a number entered by user

description: Create a number of variables from a number entered by user


code: json.dumps({'success': True, 'data': [dict(d, Week=k) for k, d in celldict.iteritems()]})

rawDescription: format python output to json

description: Format python output to json


code:
import re

def flatten(expression, mapping):
    pattern = re.compile('|'.join(map(re.escape, mapping)))
    while pattern.search(expression):
        expression = pattern.sub(lambda m: mapping[m.group()], expression)
    return expression

mapping = {
    'a': 4,
    'b': 6,
    'c': 'a+b',
    'd': 'c+a+4'
}

# Convert all values to strings.
mapping = {key: str(mapping[key]) for key in mapping}

rawDescription: Flatten expression algorithm

description: Flatten expression algorithm


code: LetterChanges('sentence')

rawDescription: How to solve this Python puzzle in a much more elegant manner?

description: Solve this Python puzzle in a much more elegant manner


rawDescription: $unwind with group and count

description: $unwind with group and count


code:
class MyUserGroup(models.Model):
    name = models.CharField(max_length=100)

rawDescription: Renaming a django model class-name and corresponding foreign keys with south, without loosing the data


code:
s3a = "strin"
s3 = s3a + "g"
s3 is "string"
intern(s3) is "string"

rawDescription: Python string interning

description: Python string interning


code: yes_votes.set(yes_votes, str(int(yes_votes) + 1))

rawDescription: How can I modify the attributes of an SVG file from Python?

description: Modify the attributes of an SVG file from Python


code:
def key(branch):
    id, flows = branch
    return order_dict[id]

rawDescription: Sorting the contents of one list via the contents of another (Python)


rawDescription: Pause an infinite while loop with a single keypress


code:
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)]

rawDescription: does adding element to a set return true if it is successful in python?

description: Does adding element to a set return true if it is successful in python


rawDescription: Turn an application or script into a shell command


code:
class Group(object):
    class cls1(object):
       ...

    class cls2(object):
       ...

rawDescription: Is there a benefit to defining a class inside another class in Python?


code:
class MyTestCase(unittest.TestCase):
    def tearDown(self):
        print('Tearing down {}'.format(self))

rawDescription: Calling a function after or before tearDown of each unit testcase


code: 'http://{}:{}@{}:{}'.format(username, password, server, port)

rawDescription: Python 3 Print Variables

description: Python 3 Print Variables


code:
from tkinter import *

wd = Tk()
wd.config(height=500, width=500)
can = Canvas(wd, bg = 'red', height=100, width=100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)

rawDescription: How to center Tkinter wiget?

description: Center Tkinter wiget


code: handles = ["one", "two", "three"]

rawDescription: Twitter User Details and Python

description: Twitter User Details and Python


code:
def string_similarity(string):
    len_string = len(string)
    total = len_string # similarity with itself
    for i in xrange(1, len_string):
        for n, c in enumerate(string[i:]):
            if c != string[n]:
                break
        else:
            n += 1

        total += n
    return total

rawDescription: How to optimize this python script further?

description: Optimize this python script further


code:
from itertools import product
from string import ascii_letters

for k in product(*3*[ascii_letters]):
    str_key = ''.join(k)

rawDescription: Influence of choosing string as seed of random on the output


code:
from __future__ import division

def f(x, y, n=3):
    for i in range(1, n+1):
        if min(x, y) <= i/n:
            return i
    else:
        return n

rawDescription: How to return value for different layers of (x,y) levels

description: Return value for different layers of (x,y) levels


code:
from os import urandom as _urandom

class Random(_random.Random):

    def __init__(self, x=None):
        self.seed(x)

    def seed(self, a=None, version=2):
        if a is None:
            try:
                a = int.from_bytes(_urandom(32), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256) # use fractional seconds

# Create one instance, seeded from current time, and export its methods
# as module-level functions.  The functions share state across all uses
#(both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.

_inst = Random()

rawDescription: How does Python seed the Mersenne twister


code:
r.rpush('ClientID:127.0.0.1', json.dumps({'test':'1', 'status':'success'}))
r.rpush('ClientID:127.0.0.1', json.dumps({'test':'2', 'status':'failure'}))
[json.loads(x) for x in r.lrange('ClientID:127.0.0.1', 0, -1)]

rawDescription: redis, python and a storing information

description: Redis, python and a storing information


code:
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType

class Client(models.Model):
    city = models.CharField(max_length=16)

    # These aren't required, but they'll allow you do cool stuff
    # like "person.sent_messages.all()" to get all messages sent
    # by that person, and "person.received_messages.all()" to
    # get all messages sent to that person.
    # Well...sort of, since "received_messages.all()" will return
    # a queryset of "MessageRecipient" instances.
    sent_messages = generic.GenericRelation('Message',
        content_type_field='sender_content_type',
        object_id_field='sender_id'
    )
    received_messages = generic.GenericRelation('MessageRecipient',
        content_type_field='recipient_content_type',
        object_id_field='recipient_id'
    )

    class Meta:
        abstract = True

class PersonClient(Client):
    first_name = models.CharField(max_length=16)
    last_name = models.CharField(max_length=16)
    gender = models.CharField(max_length=1)

    def __unicode__(self):
        return u'%s %s' % (self.last_name, self.first_name)

class CompanyClient(Client):
    name = models.CharField(max_length=32)
    tax_no = models.PositiveIntegerField()

    def __unicode__(self):
        return self.name

class Message(models.Model):
    sender_content_type = models.ForeignKey(ContentType)
    sender_id = models.PositiveIntegerField()
    sender = generic.GenericForeignKey('sender_content_type', 'sender_id')
    msg_body = models.CharField(max_length=1024)

    def __unicode__(self):
        return u'%s...' % self.msg_body[:25]

class MessageRecipient(models.Model):
    message = models.ForeignKey(Message)
    recipient_content_type = models.ForeignKey(ContentType)
    recipient_id = models.PositiveIntegerField()
    recipient = generic.GenericForeignKey('recipient_content_type', 'recipient_id')

    def __unicode__(self):
        return u'%s sent to %s' % (self.message, self.recipient)

rawDescription: Generic many-to-many relationships

description: Generic many-to-many relationships


rawDescription: Type Unicode code points into Python CLI


rawDescription: check if numpy array is subset of another array

description: Check if numpy array is subset of another array


code: df = pd.read_csv('file_name.csv')

rawDescription: date range in csv using pandas in python

description: Date range in csv using pandas in python


code:
def detect_onset_event(measurements):
    armed = False
    for offset, (timestamp, value) in enumerate(measurements):
        if value > 90:
            armed = True
        if armed and value < 85:
            return offset
    return -1  # failure condition, might want to raise ValueError()

rawDescription: Detecting regions in (x, y) data

description: Detecting regions in (x, y) data


code:
user_scores = {}

# 'with' will automatically closes the file after leaving its code block:
with open("Class1.txt") as scorefile:

    for line in reversed(scorefile.readlines()):
        name, score = line.split()

        # nested if inside if/else is better than if-and plus if not:
        if name in user_scores:
            if len(user_scores[name]) < 3:
                user_scores[name].append(int(score))
        else:
            user_scores[name] = [int(score)]

# If you want to sort by the numeric value, replace 'sorted(user_scores)' with
# 'sorted(user_scores, key=lambda k: user_scores[k])':
for name in sorted(user_scores):
    # in Python 3 the '/' operator always returns the appropriate format.
    # to get a pure integer division without decimal places, you would use '//'.
    # Therefore no need for the float(...) conversion.
    average = sum(user_scores[name]) / len(user_scores[name])
    # str.format(...) is more flexible than just printing multiple items:
    print("{}'s average from the last 3 scores is {}".format(name, average))

# No need to store another dictionary with best scores.
# If you want to sort by the numeric value, replace 'sorted(user_scores)' with
# 'sorted(user_scores, key=lambda k: user_scores[k])':
for name in sorted(user_scores):
    print("{}'s best score is {}".format(name, max(user_scores[name])))

rawDescription: Using more than the last 3 scores to analyse data; also repeating analysis?


code:
import ssl

class SocksIMAP4SSL(IMAP4_SSL):
    def open(self, host, port=IMAP4_SSL_PORT):
        self.host = host
        self.port = port
        #actual privoxy default setting, but as said, you may want to parameterize it
        self.sock = create_connection((host, port), PROXY_TYPE_HTTP, "127.0.0.1", 8118)
        self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
        self.file = self.sslobj.makefile('rb')

rawDescription: Python - How can I fetch emails via POP or IMAP through a proxy?


code:
student_averages = ((sum(scores) / len(scores), s) for s, scores in classScores.items())

for average, student in sorted(student_averages, reverse=True):
    print(student, "Average:", average)

rawDescription: Sorting a dictionary by average of list in value


code:
import msvcrt
ch = msvcrt.getch()

rawDescription: command CHOICE in DOS batch replacement/reproduction in python

description: Command CHOICE in DOS batch replacement/reproduction in python


code:
def remove_extras_and_sort(my_list):
    for item in my_list[:]:
        count = my_list.count(item)
        if count > 1:
            for _ in range(count-1):
                my_list.remove(item)
    my_list.sort()
    return my_list

rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


rawDescription: Beautiful Soup Extracting Data After href (not url)


rawDescription: Extract directories from a list of paths


code: timeit(bar, number=10000)

rawDescription: Why is Python 3 is considerably slower than Python 2?


rawDescription: What actually happens when broadcasting a NumPy array


rawDescription: Python "R Cut" function

description: Python "R Cut" function


code:
d = { 0 : (1, 2, 3) , 1 : (2, 3, 4), 2: (5, 6, 7)}
for key in d.keys():
    for val in d[key]:
        try:
            d[key]+=d[val]
        except KeyError:
            pass

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


code:
#!/usr/bin/env python

''' Toggle disable / normal of Tkinter widgets

    Written by PM 2Ring & R. Murray 2015.11.15
    See http://stackoverflow.com/q/33711472/4014959
'''

#Python 3 / Python 2 Tkinter import
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

class CActivity(tk.Frame):
    def today_cb(self):
        if self.todayVar.get():
            state = "disabled"
        else:
            state = "normal"
        #print(state)

        self.day.configure(state=state)
        self.month.configure(state=state)
        self.year.configure(state=state)

    def create_widgets(self):
        title_text = ("Click the 'Today' Checkbutton to\n"
            "disable / enable date Entry widgets")
        title = tk.Label(self, text=title_text)
        title.grid(row=0, column=0, sticky="W", padx=5, pady=5)

        self.todayVar = tk.IntVar()

        tk.Label(self,text="Today").grid(row=1, column=1,
            sticky="W", padx=0, pady=5)
        today = tk.Checkbutton(self, variable=self.todayVar,
            command=self.today_cb)
        today.grid(row=2, column=1, sticky="W", padx=0, pady=5)

        #Date Entry widgets
        tk.Label(self,text="Day").grid(row=3, column=1,
            sticky="W", padx=2, pady=5)
        self.day = tk.Entry(self, width=2)
        self.day.grid(row=4, column=1, sticky="W", padx=2, pady=5)

        tk.Label(self,text="Month").grid(row=3, column=2,
            sticky="W", padx=2,pady=5)
        self.month = tk.Entry(self, width=2)
        self.month.grid(row=4, column=2, sticky="W", padx=2, pady=5)

        tk.Label(self,text="Year").grid(row=3, column=3,
            sticky="W", padx=2, pady=5)
        self.year = tk.Entry(self, width=4)
        self.year.grid(row=4, column=3, sticky="W", padx=2, pady=5)

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.pack()
        self.parent = parent
        self.create_widgets()

if __name__ == '__main__':
    master = tk.Tk()
    master.title("Disable widgets demo")
    frame = CActivity(master)
    master.mainloop()

rawDescription: Python 3.4 tkinter checkbutton variable handling not working / responding


code:
import json

def some_view(request, param):
    my_queryset = SomeModel.objects.filter(...).select_related(...)
    list_data = [x.some_related_field for x in my_queryset]
    return HttpResponse(json.dumps(list_data), content_type='application/json')

rawDescription: Django - json response allowing for json[i][j] reference rather than json[0].field.field_name


code:
app.route('/<major>/')
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.encode('utf8', 'ignore').upper() }))
    return flask.Response(response=json.dumps(course_list), status=200, mimetype='application/json')

rawDescription: Flask Display Json in a Neat Way

description: Flask Display Json in a Neat Way


code:
import md5
md5.digest('hello')

rawDescription: How can I make a Python Wheel from an existing native library?

description: Make a Python Wheel from an existing native library


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(0,5,size=(20, 3)), columns=list('ABC'))
print(df)

print(df.groupby('C').agg({'A': max, 'B':min}))

rawDescription: Multiple aggregation in group by in Pandas Dataframe


code:
@register.filter(name='lookup')
def cut(value, arg):
    return value.get(arg, '{} not found'.format(arg))

{{ person.test_set|lookup:'date' }}

rawDescription: Django look up dictionary value in template and sort by date


code:
import os
os.system("ps")

rawDescription: How to get the process name by pid in Linux using Python?

description: Get the process name by pid in Linux using Python


code:
L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
it = iter(L)
zip(it, it)

rawDescription: Convert List to a list of tuples python

description: Convert List to a list of tuples python


code:
from settings import *
settings = Settings()
username = settings.name

rawDescription: Storing application settings in Python

description: Storing application settings in Python


code:
import dbus
_session_bus = dbus.SessionBus()

_dbus_screensaver = _session_bus.get_object('org.freedesktop.ScreenSaver','/ScreenSaver')

simulate_activity = _dbus_screensaver.get_dbus_method('SimulateUserActivity','org.freedesktop.ScreenSaver')

simulate_activity()

rawDescription: How can I prevent system from suspending/locking (Python/C/Bash)

description: Prevent system from suspending/locking (Python/C/Bash)


code:
import csv

with open('input.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    [next(reader) for _ in range(3)]
    data = [[1 if entry=='X' else 0 for entry in row[1:]] for row in reader]

rawDescription: How to parse of a simple csv file?

description: Parse of a simple csv file


code:
class A(object):
    def __init__(self):  # Instance attribute, created anew for each new object
        self.v = []

rawDescription: Terrifying initial values - mutable types share same reference?


code:
from itertools import groupby

entities = Entity.objects.order_by('start_time')
for start_date, group in groupby(entities, key=extract_date):
    do_something_with(start_date, list(group))

rawDescription: Django model group by datetime's date

description: Django model group by datetime's date


rawDescription: Stumped - In Python obtaining unique keys with multiple associated values from a list of ditionaries


code:
iterator = iter(right)
try:
    while True:
        r = next(iterator)
        if stack.endswith(r):
            stack = stack.replace(r, left[right.index(r)])
            iterator = iter(right)

except StopIteration:
    pass

rawDescription: how to reset pointer of list in for loop after a condition becomes true in python?

description: Reset pointer of list in for loop after a condition becomes true in python


code: zipped[:] = []

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

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


code:
def common_fields(group):
    def in_all_members(key, value):
        return all(member[key] == value for member in group[1:])
    return {key: value for key, value in group[0].items() if in_all_members(key, value)}

rawDescription: Correct use of a fold or reduce function to long-to-wide data in python or javascript?


code:
df = pd.DataFrame([[10.0, 0.0, 9.0, 7.2],[5.4, 1.0, 0.0, 8.0], [1.7, 4.4, 3.2, 0.0],[5.4, 3.1, 6.1, 0.0]], columns=['value', 'A', 'B', 'C'])
df = df.set_index('value').stack().reset_index()
df.columns = ['value', 'Column', 'split_value']
df = df.set_index('split_value')

def f(value):
    if value==0:
        return 'zero'
    else:
        return 'non-zero'
print(df.groupby(['Column', f])['value'].sum())

rawDescription: Define Splitting Condition in Pandas Groupby


rawDescription: How to add parameters to the homepage URL in Django

description: Add parameters to the homepage URL in Django


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
class ReadOnlyCachedAttribute(object):
    '''Computes attribute value and caches it in the instance.
    Source: Python Cookbook
    Author: Denis Otkidach http://stackoverflow.com/users/168352/denis-otkidach
    This decorator allows you to create a property which can be computed once and
    accessed many times. Sort of like memoization
    '''
    def __init__(self, method, name=None):
        self.method = method
        self.name = name or method.__name__
        self.__doc__ = method.__doc__
    def __get__(self, inst, cls):
        if inst is None:
            return self
        elif self.name in inst.__dict__:
            return inst.__dict__[self.name]
        else:
            result = self.method(inst)
            inst.__dict__[self.name]=result
            return result
    def __set__(self, inst, value):
        raise AttributeError("This property is read-only")
    def __delete__(self,inst):
        del inst.__dict__[self.name]

rawDescription: How to create decorator for lazy initialization of a property

description: Create decorator for lazy initialization of a property


code:
import asyncio

dsn = "..."

class Foo(object):
    @classmethod
    async def create(cls, settings):
        self = Foo()
        self.settings = settings
        self.pool = await create_pool(dsn)
        return self

async def main(settings):
    settings = "..."
    foo = await Foo.create(settings)

rawDescription: How to set class attribute with await in __init__

description: Set class attribute with await in __init__


rawDescription: How to get folder name, in which given file resides, from pathlib.path?

description: Get folder name, in which given file resides, from pathlib.path


code: sorted(addr_list, key=lambda ip: map(int, reversed(ip.split('.'))))

rawDescription: Sort on the last octet of an IP address in a Python list


code:
def foo(bar, baz):
    """Function foo()

* Summary:
    Function foo() handles all your foo-ish needs.  You pass in a bar and a baz and it foos them.

* Developers:
    When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.

* Testers:
    When you test foo, be sure to try negative values for baz.
"""
    pass # code would go here

rawDescription: More than 1 docstrings for a single module/function etc.?


code:
v
tea.decipher(tea.encipher(v,key),key)

rawDescription: Python TEA implementation

description: Python TEA implementation


rawDescription: Decoding an encoded text file - Python

description: Decoding an encoded text file - Python


code:
t.contents
t.text

rawDescription: Extracting text from a nested tags in XML using BeautifulSoup in python


code:
link = crawl()
if link is not None:
    found.append(link)

rawDescription: How to make a function return nothing?

description: Make a function return nothing


code: score = sum(student==correct for student, correct in zip(student_answers, answer_key))

rawDescription: comparing each element in a string with another string at the same position

description: Comparing each element in a string with another string at the same position


code:
for infile in infiles:
    for line in open(infile):
        lines.append(line.rstrip("\n"))

rawDescription: From files to list of lines

description: From files to list of lines


code: elem = np.argmax(n)

rawDescription: Find the x value corresponding to a histogram max


rawDescription: Choosing marker size in Matplotlib

description: Choosing marker size in Matplotlib


code:
if need_more_workers():
    newcomm = get_new_comm(comm)
    # ...

rawDescription: Python context manager: conditionally executing body?


code:
your_columns = P_total.columns.str.contains('a')
P_total.ix[0, your_columns]

rawDescription: Add value to Row for every column except one


code:
m = re.search(r'TP-LINK.+(WA\w+)', re1)
"TL" + m.group(1)

rawDescription: How to use regex to search in a string

description: Use regex to search in a string


code:
def validate(obj):
    import bpy, bmesh

    if obj.type == 'MESH':
        bm = bmesh.new()
        bm.from_object(obj, bpy.context.scene)

        if len(bm.faces) > 0 and 0 not in (len(e.link_faces) for e in bm.edges):
            return True
    return False

rawDescription: Scene object selective export using Blender Python API 2.6


code:
def numpy_assign(values, row, col):
    # arrange the values so that entries are contiguous
    ix = np.ravel_multi_index((row, col), (2,2))
    sort_ix = np.argsort(ix)

    ix = ix[sort_ix]
    values = values[sort_ix]

    # now we need to construct the funny index argument
    # to the `reduceat` ufunc method
    reduce_ix = np.where(np.diff(ix))[0] + 1
    reduce_ix = np.insert(reduce_ix, 0, 0)

    # reduce the amounts
    amount = np.add.reduceat(values, reduce_ix).reshape(2,2)

    # and count the number of times we've done so
    _, counts = np.unique(ix, return_counts=True)
    counts = counts.reshape(2,2)

    return amount, counts

rawDescription: Sum array values into a matrix in python in a quick way


rawDescription: numpy, h5py: How do I make an array sorted by one of its columns from a bigger one saved with h5py?

description: Numpy, h5py: How do I make an array sorted by one of its columns from a bigger one saved with h5py


code:
def prefix_length_checker(length):
    """Consider group if the prefix is of at least the given length."""
    return lambda x: len(x) >= length

def prefix_regex_checker(regex):
    """Consider group if the prefix matches a certain regex."""
    return regex.match

def prefix_ratio_checker(pattern, threshold):
    """Consider group if the prefix is "similar" to a given pattern.

    This fundamentally uses an extension of Levenstein distance.
    """
    matcher = difflib.SequenceMatcher()
    matcher.set_seq1(pattern)
    def check_ratio(prefix, matcher=matcher):
        matcher.set_seq2(prefix)
        return matcher.ratio() >= threshold
    return check_ratio

rawDescription: How to cluster similar file paths?

description: Cluster similar file paths


rawDescription: Python list max function when a list item is present


code:
chunk = sock.recv(65535)
if not chunk:
    break
data += chunk

rawDescription: recv() keep returning the same data

description: Recv() keep returning the same data


code:
def generate_iterables():
    for i in range(10):
        yield range(i)

itertools.chain.from_iterable(generate_iterables())

rawDescription: What is the difference between chain and chain.from_iterable in itertools?


code:
paths = sys.argv[1:]
sys.path.extend(paths)

rawDescription: Importing Python Librarys over C#?

description: Importing Python Librarys over C#


code:
from decimal import *

class FixedPointDecimal(Decimal):

    def _fix(self, context):
        # always fit to 2dp
        return super()._fix(context)._rescale(-2, context.rounding)
        # use context to find number of decimal places to use
        # return super()._fix(context)._rescale(-context.decimal_places, context.rounding)

# setup decimal module to use FixedPointDecimal
decimal.Decimal = FixedPointDecimal
Decimal = FixedPointDecimal

rawDescription: Python decimal context for fixed point

description: Python decimal context for fixed point


code:
@app.route("/")
def index():
    return send_file('templates/index.html')

rawDescription: Typical Angular.js workflow and project structure (with Python Flask)


rawDescription: Understanding Python name objects, immutable data, and memory management


code:
import csv
import glob

def get_site_files():
    with open('out.csv', 'w') as out_file:
        csv_out = csv.writer(out_file, delimiter=',')
        for fname in glob.glob('*.txt'):
            with open(fname) as f:
                for line in f:
                    vals = line.split(',')
                    csv_out.writerow(vals)

get_site_files()

rawDescription: Python automating text data files into csv


rawDescription: Can I trust the order of a dict to remain the same each time it is iterated over?

description: Trust the order of a dict to remain the same each time it is iterated over


code:
from django.contrib import admin
from myapp.models import Program, Course, Grade

admin.site.register(Program)
admin.site.register(Course)
admin.site.register(Grade)

rawDescription: Is it possible to filter choices on a foreign key in Django Admin panel?


code:
from setings import *
try:
    from local.py import *
except ImportError:
    pass

rawDescription: How do I access imported local settings without a circular import?

description: Access imported local settings without a circular import


code:
import subprocess

def suspend_screensaver():
    window_id = subprocess.Popen('xwininfo -root | grep xwininfo | cut -d" " -f4', stdout=subprocess.PIPE, shell=True).stdout.read().strip()

    #run xdg-screensaver on root window
    subprocess.call(['xdg-screensaver', 'suspend', window_id])

def resume_screensaver(window_id):
    subprocess.Popen('xdg-screensaver resume ' + window_id, shell=True)

rawDescription: Inhibit screensaver with Python

description: Inhibit screensaver with Python


code: layout = BoxLayout(size_hint=(0.5, None), height=50, pos_hint={'top': 1, 'center_x':0.5})

rawDescription: python kivy boxlayout set position

description: Python kivy boxlayout set position