code:
dic2 = defaultdict(list)

dic2

rawDescription: Can I group / aggregate elements in a list (or dict) comprehension?

description: Group / aggregate elements in a list (or dict) comprehension


code:
l = [5, 6, 7, 8]
for source, dest in zip(l, l[1:]):
    print('Source = {}'.format(source))
    print('Destination = {}'.format(dest))

rawDescription: How to add a matrix to itself in an iterative way?

description: Add a matrix to itself in an iterative way


code:
def removeCloseItems(items, howFar):
    if items:
        lastItem = items[0]
        yield items[0]
        for currentItem in items[1:]:
            lastItem = currentItem
            if ((currentItem - lastItem) > howFar):
                yield currentItem

rawDescription: Remove items from list if they are within a given range


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

     täkäen
''')
soup
soup.findAll(text=u'täkäen')

rawDescription: bs4: search for special characters like 'ä'

description: Bs4: search for special characters like 'ä'


code:
import numpy as np
import cv2

im0 = cv2.imread('objects/pix0.png',0)
im1 = cv2.imread('objects/pix1.png',0)
im2 = cv2.imread('objects/pix2.png',0)
im3 = cv2.imread('objects/pix3.png',0)
im4 = cv2.imread('objects/pix4.png',0)
im5 = cv2.imread('objects/pix5.png',0)

h0, w0 = im0.shape[:2]
h1, w1 = im1.shape[:2]
h2, w2 = im2.shape[:2]
h3, w3 = im3.shape[:2]
h4, w4 = im4.shape[:2]
h5, w5 = im5.shape[:2]
maxh=max(h0,h1,h2,h3,h4,h5)

#add 50 for space between the objects

new = np.zeros((maxh, w0+w1+w2+w3+w4+w5+50),np.uint8)
new=(255-new)
new[maxh-h0:, :w0] = im0
new[maxh-h1:, w0+10:w0+w1+10] = im1
new[maxh-h2:, w0+w1+20:w0+w1+w2+20] = im2
new[maxh-h3:, w0+w1+w2+30:w0+w1+w2+w3+30] = im3
new[maxh-h4:, w0+w1+w2+w3+40:w0+w1+w2+w3+w4+40] = im4
new[maxh-h5:, w0+w1+w2+w3+w4+50:] = im5
gray = cv2.cvtColor(new, cv2.COLOR_GRAY2BGR)

cv2.imshow('norm',gray)
cv2.imwrite('objects/new_image.jpg',gray)
key = cv2.waitKey(0)

rawDescription: How segment image in python?

description: How segment image in python


rawDescription: Pandas Grouping and Reducing DataFrame

description: Pandas Grouping and Reducing DataFrame


code:
subprocess.Popen(['program_name'], env={
  'first_var': first_var,
  'second_var': second_var,
})

rawDescription: How to pass more than one variable from Python script to c shell script

description: Pass more than one variable from Python script to c shell script


code:
def f():
    call_some_function_A()
    if whatever:
        call_some_function_B()
        call_some_function_C()
    call_some_function_D()

rawDescription: Executing a function in reverse in Python


rawDescription: Reading from a file directly into a 2D list python


code:
from os import environ, path

from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *

MODELDIR = "../../../model"
DATADIR = "../../../test/data"

# Create a decoder with certain model
config = Decoder.default_config()
config.set_string('-hmm', path.join(MODELDIR, 'en-us/en-us'))
config.set_string('-allphone', path.join(MODELDIR, 'en-us/en-us-phone.lm.dmp'))
config.set_float('-lw', 2.0)
config.set_float('-beam', 1e-10)
config.set_float('-pbeam', 1e-10)

# Decode streaming data.
decoder = Decoder(config)

decoder.start_utt()
stream = open(path.join(DATADIR, 'goforward.raw'), 'rb')
while True:
  buf = stream.read(1024)
  if buf:
    decoder.process_raw(buf, False, False)
  else:
    break
decoder.end_utt()

hypothesis = decoder.hyp()
print ('Phonemes: ', [seg.word for seg in decoder.seg()])

rawDescription: convert sound to list of phonemes in python

description: Convert sound to list of phonemes in python


rawDescription: Computing pseudo inverse of a matrix using sympy


code: len(a & b)

rawDescription: Finding partial subsets python

description: Finding partial subsets python


code:
strings = [
    '24', '277', '277 24', '139 24', '139 277 24', '139 277', '139', '136 24',
    '136 277 24', '136 277', '136', '136 139 24', '136 139 277 24', '136 139 277',
    '136 139', '246']

def find_supersets(strings):
    superstrings = set()
    set_to_string = dict(zip([frozenset(s.split()) for s in strings], strings))
    for s in set_to_string.keys():
        for sup in superstrings.copy():
            if s <= sup:
                # print('{s!r} <= {sup!r}'.format(s = s, sup = sup))
                break
            elif sup < s:
                # print('{sup!r} <= {s!r}'.format(s = s, sup = sup))
                superstrings.remove(sup)
        else:
            superstrings.add(s)
    return [set_to_string[sup] for sup in superstrings]

print(find_supersets(strings))

rawDescription: Finding superstrings in a set of strings in python


code: subprocess.call("cmd /c wscript MyScript.vbs")

rawDescription: My Visual Basic scripts Open instead of running


code: ''.join([format(el, '<10') for el in list_of_strings])

rawDescription: Is there is way to justify substrings while performing join operation


rawDescription: What is the right way to organize python unittests into suites?


code: response not in ('y', 'n', 'yes', 'no')

rawDescription: Python mock multiple return values

description: Python mock multiple return values


rawDescription: Hashing a tuple in Python where order matters?


code:
fields = query_data.keys()
fields_string = ', '.join(fields)

rawDescription: Python sql query insert data in columns

description: Python sql query insert data in columns


rawDescription: Extract Information From a File

description: Extract Information From a File


code:
for char in word:
    if char in vowels:
        print(4 * char, end='')
    else:
        print(char, end='')

rawDescription: String manipulation in for loops

description: String manipulation in for loops


code:
def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):
    return [round(ride_time * cpm + ride_distance * cpmile, 1)
            for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]
fareEstimator(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5])

rawDescription: How to get the result in single List?

description: Get the result in single List


code:
import itertools as it
import operator as op

a = [3, 4, 6, 7, 8, 9]
b = [1, 2, 5, 10]
srcs = [a, b]
dsts = [[], []]

for which, elems in it.groupby(sorted((x, i) for i in (0,1) for x in srcs[i]), key=op.itemgetter(1)):
    dsts[which].append(next(elems)[0])
a, b = dsts

rawDescription: compare elements of two lists

description: Compare elements of two lists


code:
from lxml import etree
tree = etree.parse('some.xml')
root = tree.getroot()
# Get the whole XML content as  string
xml_in_str = etree.tostring(root)

# Replace all \n with space
new_xml_data = xml_in_str.replace(r'\n', ' ')

# Do the processing with the new_xml_data string which is formatted

# Maybe also write to a new XML file, without the \n
with open('newxml.xml', 'w') as f:
    f.write(new_xml_data)

rawDescription: Replace `\n` in html page with space in python LXML


code: age_range, freq = zip(*sorted(age_freq.items()))

rawDescription: Python - Easiest way to get ordered key/value pairs from dictionary?


code:
data_stream = Popen(mycmd, stdin=PIPE, stdout=PIPE)
data_stream.stdin.write("do something\n")
for line in data_stream:
  ...  # BAD!

rawDescription: python subprocess module: looping over stdout of child process

description: Python subprocess module: looping over stdout of child process


code: True

rawDescription: Why does this iteration didn't return anything out?


code:
# Blogs who have either hockey or django tags.
from django.db.models import Q
Blog.objects.filter(
    Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')
)

rawDescription: Union and Intersect in Django

description: Union and Intersect in Django


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


code:
import json, jsonrpclib
from pprint import pprint
server = jsonrpclib.Server("http://localhost:8080")
pprint(json.loads(server.parse('John loves Mary.')))  # doctest: +SKIP

rawDescription: Stanford Universal Dependencies on Python NLTK


code:
class Foo(object):
    def bar(self):
        pass

Foo().bar
Foo().bar.__get__

rawDescription: How to add property to a python class dynamically?

description: Add property to a python class dynamically


code:
def __init__(self, thing_args, ex_arg1, ex_arg2):
    super().__init__(*thing_args)
    # ...

rawDescription: How to Extend Large Class Methods?

description: Extend Large Class Methods


rawDescription: Why does s[len(s)-1:-1:-1] not work?

description: Why does s[len(s)-1:-1:-1] not work


rawDescription: How to count number of unique strings in two columns?

description: Count number of unique strings in two columns


rawDescription: How to store bash shell script in the JSON document effectively for Python script

description: Store bash shell script in the JSON document effectively for Python script


code:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)

rawDescription: Is there a simple way to increment a datetime object one month in Python?


code:
import inspect
import sys

def some_function():
       ...

print(dict(inspect.getmembers(sys.modules[__name__], inspect.isfunction)))

rawDescription: Python: Passing a list of function names and parameters to a class instance


code:
class X(object):
    def __init__(self):
        self.i = 1

rawDescription: Cython: how to make an python object as a property of cython class


code: histogram = dict(Counter(args))

rawDescription: Python setdefault not lvalue, any work-arounds?


rawDescription: Retrieve the ranking of elements in various list to compute the weighted average of their ranking scores Python


code:
for ch in character:
    if ch in lowerLetters:
        lowerCount += 1
    elif ch in upperLetters:
        upperCount += 1
    elif ch in digits:
        digitCount += 1
    else:
        nonAlphaCount += 1

rawDescription: How to determine if character is uppercase, lowercase, digit, or non-alphanumeric without string methods

description: Determine if character is uppercase, lowercase, digit, or non-alphanumeric without string methods


code:
for line in data.readlines():
    new_data.append(int(line.strip()))

rawDescription: How to extract numerical data from a text file

description: Extract numerical data from a text file


code:
T(lambda : 'four' in d.itervalues()).repeat()
T(lambda : 'four' in d.values()).repeat()
T(lambda : 'four' in d.viewvalues()).repeat()

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

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


code:
toolbar = tk.Frame(root)
save_button = tk.Button(toolbar, ...)

toolbar.pack(side="top", fill="x")
save_button.pack(side="left")

rawDescription: Is there any better method to manage place in Tkinter in Python?


rawDescription: How to convert rows values in dataframe to columns labels in Python after groupby?

description: Convert rows values in dataframe to columns labels in Python after groupby


code:
with open("xmlbasic.txt") as lines_file:
    lines = lines_file.read()

import xml.etree.ElementTree as ET

root = ET.Element('root')

for line in lines:
    head, subhead, tail = line.split(":")

    head_branch = root.find(head)
    if not head_branch:
        head_branch = ET.SubElement(root, head)

    subhead_branch = head_branch.find(subhead)
    if not subhead_branch:
        subhead_branch = ET.SubElement(branch1, subhead)

    subhead_branch.text = tail

tree = ET.ElementTree(root)
ET.dump(tree)

rawDescription: creating xml tree from a textfile with Python

description: Creating xml tree from a textfile with Python


code: c = numpy.linalg.lstsq(b.T, a.T)[0].T

rawDescription: Array division- translating from MATLAB to Python


code:
def enforce(requirements):
    def wrapper(func):
        @wraps(func)
        def wrapped(self, *args, **kwargs):
            return func(self, *args, **kwargs)
        while requirements:
            func = requirements.pop()(func)
        return wrapped
    return wrapper

class FooBar(object):
    @enforce([reguires_foo, requires_bar])
    def do_something_to_foo_and_bar(self):
        pass

rawDescription: Python decorators just syntactic sugar?

description: Python decorators just syntactic sugar


code:
import cgi
import os

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.datastore import entity_pb

rawDescription: Is there an include file for class statements in python?


code:
from scipy.sparse import csr_matrix

# make single column/row sparse matrix reps of Rip
row = np.array( [ i for (i,x) in enumerate(Rip) if x != 0 ] )
col = np.zeros( row.size, dtype=np.int32 )
dat = np.array( [ x for (i,x) in enumerate(Rip) if x != 0 ] )
Rip_col_mat = csr_matrix( (dat,(row,col) ) )
Rip_row_mat = csr_matrix( (dat,(col,row) ) )

# make single column/row sparse matrix reps of Rjp
row = np.array( [ i for (i,x) in enumerate(Rjp) if x != 0 ] )
col = np.zeros( row.size, dtype=np.int32 )
dat = np.array( [ x for (i,x) in enumerate(Rjp) if x != 0 ] )
Rjp_col_mat = csr_matrix( (dat,(row,col) ) )
Rjp_row_mat = csr_matrix( (dat,(col,row) ) )

rawDescription: Special cosine between scipy sparse matrices


rawDescription: auto run python result in "EOF when reading a line "

description: Auto run python result in "EOF when reading a line "


rawDescription: Pandas: How to iterate over level one and randomly select from level 2 then add subselection to dataframe


rawDescription: list index comparison in python

description: List index comparison in python


code: df['ids'] = df['ids'].apply(lambda x: list(set(x)))

rawDescription: How to merge two list columns when merging DataFrames?

description: Merge two list columns when merging DataFrames


code:
gmeans['Type'] = 'GeoM'

newdata = pandas.concat([data, gmeans.reset_index()], axis=0)

rawDescription: Add calculated row to pandas DataFrame

description: Add calculated row to pandas DataFrame


code:
import pickle
with open('kmeans.dat', 'w') as f:
    pickle.dump(kmeans, f)

rawDescription: i want to classify data by distance from centroids in python

description: I want to classify data by distance from centroids in python


code:
from sklearn.datasets import load_files
from sklearn.cross_validation import train_test_split
bunch = load_files('./Topics')
X_train, X_test, y_train, y_test = train_test_split(bunch.data, bunch.target, test_size=.4)

rawDescription: Load Custom Dataset (which is like 20 news group set) in Scikit for Classification of text documents


code:
class StrategyExample:
    def __init__(self, func=None):
        if func:
             self.execute = func

    def execute(self):
        print("Original execution")

def executeReplacement1():
    print("Strategy 1")

def executeReplacement2():
    print("Strategy 2")

if __name__ == "__main__":
    strat0 = StrategyExample()
    strat1 = StrategyExample(executeReplacement1)
    strat2 = StrategyExample(executeReplacement2)

    strat0.execute()
    strat1.execute()
    strat2.execute()

rawDescription: How to write Strategy Pattern in Python differently than example in Wikipedia?

description: Write Strategy Pattern in Python differently than example in Wikipedia


code:
import numpy as np

for method_name, method in np.random.__dict__.items():
    try:
        docstring_lines = method.__doc__.split('\n')
    except (AttributeError,):
        continue
    if len(docstring_lines) == 0:
        continue
    for line in docstring_lines:
        if method_name in line:
            print(line.strip())
            break

rawDescription: How to massage numpy function arguments

description: Massage numpy function arguments


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


rawDescription: heap sort in Python for advice

description: Heap sort in Python for advice


code:
class Location(models.Model):
    class Title:
        CLASSROOM = 'classroom'
        PLAYGROUND = 'playground'
        STAFF_ROOM = 'staff_room'

    TITLE_CHOICES = (
        (Title.CLASSROOM, 'Classroom'),
        (Title.PLAYGROUND, 'Playground'),
        (Title.STAFF_ROOM, 'Staff Room'),
    )

    user = models.ForeignKey(User,null=True)
    title = models.CharField('Incident Type', max_length=200,choices=TITLE_CHOICES,default=Title.CLASSROOM)
    parent_location_id = models.CharField('Parent Location', max_length=100, null=True, blank=True)
    is_active = models.BooleanField('Is Active', default=True)

rawDescription: create row of date while creating superuser

description: Create row of date while creating superuser


code:
class Car: # class names are generally capitalized so that you can tell they're not local variable names.
    def __init__(self, tires, color, age):
        self.tires = tires
        self.color = color
        self.age = age

    def paint(self): # We make paint() a method of car
        print("So you want to paint your car?")
        color = input("What color will it be? ")
        self.color = color

rawDescription: Do something for every instance of a class


code:
def formatter(start, end, step):
    return '{}-{}:{}'.format(start, end, step)
    # return '{}-{}:{}'.format(start, end + step, step)

def helper(lst):
    if len(lst) == 1:
        return str(lst[0]), []
    if len(lst) == 2:
        return ','.join(map(str,lst)), []

    step = lst[1] - lst[0]
    for i,x,y in zip(itertools.count(1), lst[1:], lst[2:]):
        if y-x != step:
            if i > 1:
                return formatter(lst[0], lst[i], step), lst[i+1:]
            else:
                return str(lst[0]), lst[1:]
    return formatter(lst[0], lst[-1], step), []

def re_range(lst):
    result = []
    while lst:
        partial,lst = helper(lst)
        result.append(partial)
    return ','.join(result)

rawDescription: Convert List of Numbers to String Ranges


rawDescription: How to pickle unicodes and save them in utf-8 databases

description: Pickle unicodes and save them in utf-8 databases


code: data['new_col'] = data.apply(lambda x: [','.join(x.dropna())], axis=1)

rawDescription: How to concatenate pandas dataframe columns into iterable lists?

description: Concatenate pandas dataframe columns into iterable lists


code: cdefghijklmnopqrstuvwxyzab

rawDescription: Returning the value of an index in a python list based on other values


code:
for row in xrange(rows - 2):
    self.neurons.append([Neuron(parents=self.neurons[-1] + [self.bias]) for output in xrange(hidden)])

rawDescription: What caused my ANN to take drastically less time to run?


code:
filename = raw_input("Please enter your filename:\n")
openedFile = open(filename, "rb")
startAddress = raw_input("From the EEPROM file, enter 'Start Address':\n")
endAddress = raw_input("From the EEPROM file, enter 'End Address':\n")

rawDescription: Python--Need to Read and find data, and copy a file to another location (beginner)


rawDescription: Convert int to raw data in python

description: Convert int to raw data in python


code:
l = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2']
numbersPerLetter = 2
lsorted = []
for i in range(len(l) / numbersPerLetter):
   lsorted.extend([l[x+i] for x in range(0, len(l), len(l) / numbersPerLetter)])
print(lsorted)

rawDescription: sorting the list in Python without .sorted()

description: Sorting the list in Python without .sorted()


code:
sum=0.0
for i in range(1,6):
    x,y=eval(input("Please enter length and width of room:"))
    sf=(x*y)
    sum=sum+sf
print("The total square footage is",sum)

rawDescription: Python-Need to turn this into a loop so it look like my picture?


code:
Demonstration
np.random.seed([3,1415])
s = pd.Series(np.random.randn(100) / 100, name='price').add(1.001).cumprod()

bollinger_bands(s).plot()

rawDescription: python panda to calculate rolling means

description: Python panda to calculate rolling means


code:
def compose1(fnlist):
    if not fnlist:
        return lambda x: x

    # compose 1 function of x from two others
    def compose2fns(fn1, fn2):
        return lambda x : fn1(fn2(x))
    # or if you really love lambdas
    # compose2fns = lambda fn1,fn2: lambda x: fn1(fn2(x))

    # use reduce to cumulatively apply compose2fns to the functions
    # in the given list
    return reduce(compose2fns, fnlist)

rawDescription: Python lambda expression compose iterator script


rawDescription: Python: How to generate a full rank square binary matrix in which each row only has 3 bits 1


rawDescription: Using Zip to read a file vertically and search through the zipped list


code:
to_check = [120, 49]
"Not in" if all(to_check not in cluster for cluster in clusterList) else "In"

rawDescription: Check to see if a list is in a list of lists


code:
arr2D = np.column_stack((df['col1'],df['col2'],df['col1'],df['col3']))
out_list = np.vsplit(arr2D.reshape(-1,2),arr2D.shape[0])

rawDescription: convert separate 1D np.arrays into a list of 2D np.arrays

description: Convert separate 1D np.arrays into a list of 2D np.arrays


code: temp_df = pd.DataFrame({'Request': df.Request.unique(), 'Request_id':range(len(df.Request.unique()))})

rawDescription: Map string values in a Pandas Dataframe with integers


code:
fdist = nltk.FreqDist()  # Empty distribution

for filename in speeches.fileids():
    fdist.update(nltk.trigrams(speeches.words(filename)))

rawDescription: Finding trigrams for entire corpus with NLTK


code:
def shorten_hostnames(machines):
    keys, values = zip(*machines.items())
    values = [v.split('.') for v in values]
    for i, s in ((-1, slice(-1)), (0, slice(1, None))):
        while all(values):
            if not len(set(v[i] for v in values)) == 1:
                break
            if any(len(v) <= 1 for v in values):
                break
            values = [v[s] for v in values]
    return {k: '.'.join(v) for k, v in zip(keys, values)}

rawDescription: Remove common elements of hostnames (shorten hostnames) - DRY


code:
from urlparse import urlparse
from os.path import splitext

def get_ext(url):
    """Return the filename extension from url, or ''."""
    parsed = urlparse(url)
    root, ext = splitext(parsed.path)
    return ext  # or ext[1:] if you don't want the leading '.'

rawDescription: Identify the file extension of a URL

description: Identify the file extension of a URL


code:
@partial
def twitter_email(backend, user, response, is_new=None,  *args, **kwargs):
     ...
     submit_social_data = backend.strategy.session.get('submit_social_data', None)
     if is_new and not submit_social_data:
                return redirect('redirect_url')

rawDescription: Python social auth partial pipeline resume after form submit button


code: rgb = numpy.sum(np_pix)

rawDescription: Python: Iterate over a sub-2d (nested) array to calculate its sum


rawDescription: pythonic way to replace special char at beginning or at the end of string

description: Pythonic way to replace special char at beginning or at the end of string


code:
class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        # use new style signals
        self.ui.buttonBox.accepted.connect(self.accept)
        self.ui.buttonBox.rejected.connect(self.reject)

rawDescription: PyQt4 - closing a dialog window, exec_() not working


code:
import sys
from itertools import groupby
for k, g in groupby(sys.stdin, key=lambda x:x.split()[0]):
    ...

rawDescription: count file wise as well as datewise in Map reduce Python

description: Count file wise as well as datewise in Map reduce Python


code:
import math
epsilon = 0.000001

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y
    def dist_to_point(self, other):
        'Compute the Euclidean distance between two Point objects'
        delta_x = self._x - other._x
        delta_y = self._y - other._y
        return (delta_x ** 2 + delta_y ** 2) ** 0.5

rawDescription: Python Class Desgin

description: Python Class Desgin


code:
import pyorient

db_name = 'TestDatabaseName'

print("Connecting to the server...")
client = pyorient.OrientDB("localhost", 2424)
session_id = client.connect("root", "root")
print("OK - sessionID: ", session_id, "\n")

if client.db_exists(db_name, pyorient.STORAGE_TYPE_PLOCAL):
    client.db_open(db_name, "root", "root")
    functionCall = client.command("SELECT myFunction() UNWIND myFunction")
    for idx, val in enumerate(functionCall):
        print("Field name:  " + val.myFunction)

client.db_close()

rawDescription: Finding all properties for a schema-less vertex class


code:
class MyResource(ModelResource):
    ...
    class Meta:
        ...
        max_limit = None

rawDescription: Disable pagination in Django tastypie?

description: Disable pagination in Django tastypie


code: last_name, other_names, plcass, sex, age

rawDescription: How do I split a csv field that has quotations into two fields?

description: Split a csv field that has quotations into two fields


rawDescription: How do you find the IQR in Numpy?

description: Find the IQR in Numpy


code:
parts = s.split(',')
result = []
for part in parts:
    if not is_numeric(part):
        result = []
        break
    else:
        result.append(float(part))

rawDescription: Check if input is either digits or period


code:
import numpy as numpy

grey_levels = 256
# Generate a test image
test_image = numpy.random.randint(0,grey_levels, size=(11,11))

# Define the window size
windowsize_r = 5
windowsize_c = 5

# Crop out the window and calculate the histogram
for r in range(0,test_image.shape[0] - windowsize_r, windowsize_r):
    for c in range(0,test_image.shape[1] - windowsize_c, windowsize_c):
        window = test_image[r:r+windowsize_r,c:c+windowsize_c]
        hist = numpy.histogram(window,bins=grey_levels)

rawDescription: Divide an image into 5x5 blocks in python and compute histogram for each block


code: df.query('date < date_threshold')

rawDescription: Dropping rows fast from a multi-indexed data frame conditional on the level 1 index


code:
s ='some text here, songs: song1, song2, song3, fro: othenkl'
re.search(r'(?<=songs:)(.+),', s,flags=re.I).group(1).split(',')

rawDescription: Regex one-liner for matching only what comes after a certain word?


code:
from glob import glob
import os.path
import time

def find_sessions_to_delete(cutoff):
    # produce a list of (timestamp, path) tuples for each session directory
    session_dirs = [(os.path.getctime(p), p) for p in glob('/root/job*/session*')]
    session_dirs.sort(reverse=True)  # sort from newest to oldest
    # remove first two elements, they are kept regardless
    session_dirs = session_dirs[2:]
    # return a list of paths whose ctime lies before the cutoff time
    return [p for t, p in session_dirs if t <= cutoff]

cutoff = time.time() - (7 * 86400)  # 7 days ago
sessions_to_delete = find_sessions_to_delete(cutoff)

rawDescription: Retrieving specific directories using os.walk()


code:
import ctypes
from ctypes import wintypes

__all__ = ['get_known_folder_path', 'FOLDERID']

ole32 = ctypes.OleDLL('ole32')
shell32 = ctypes.OleDLL('shell32')

class GUID(ctypes.Structure):
    _fields_ = (('Data1', ctypes.c_ulong),
                ('Data2', ctypes.c_ushort),
                ('Data3', ctypes.c_ushort),
                ('Data4', ctypes.c_char * 8))
    def __init__(self, guid_string):
        ole32.IIDFromString(guid_string, ctypes.byref(self))

IID = GUID
LPIID = ctypes.POINTER(IID)
LPCOLESTR = wintypes.LPCWSTR
ole32.IIDFromString.argtypes = (LPCOLESTR,
                                LPIID)

ole32.CoTaskMemFree.restype = None
ole32.CoTaskMemFree.argtypes = (wintypes.LPVOID,)

REFKNOWNFOLDERID = LPIID
shell32.SHGetKnownFolderPath.argtypes = (REFKNOWNFOLDERID,
                                         wintypes.DWORD,
                                         wintypes.HANDLE,
                                         ctypes.POINTER(wintypes.LPWSTR))

def get_known_folder_path(folder_id):
    pszPath = wintypes.LPWSTR()
    shell32.SHGetKnownFolderPath(ctypes.byref(folder_id),
                                 0, None, ctypes.byref(pszPath))
    folder_path = pszPath.value
    ole32.CoTaskMemFree(pszPath)
    return folder_path

# KNOWNFOLDERID
# https://msdn.microsoft.com/en-us/library/dd378457

# fixed
FOLDERID_Windows         = GUID('{F38BF404-1D43-42F2-9305-67DE0B28FC23}')
FOLDERID_System          = GUID('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}')
FOLDERID_SystemX86       = GUID('{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}')
FOLDERID_Fonts           = GUID('{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}')
FOLDERID_ResourceDir     = GUID('{8AD10C31-2ADB-4296-A8F7-E4701232C972}')
FOLDERID_UserProfiles    = GUID('{0762D272-C50A-4BB0-A382-697DCD729B80}')
FOLDERID_Profile         = GUID('{5E6C858F-0E22-4760-9AFE-EA3317B67173}')
FOLDERID_Public          = GUID('{DFDF76A2-C82A-4D63-906A-5644AC457385}')
FOLDERID_ProgramData     = GUID('{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}')
FOLDERID_ProgramFiles    = GUID('{905e63b6-c1bf-494e-b29c-65b732d3d21a}')
FOLDERID_ProgramFilesX64 = GUID('{6D809377-6AF0-444b-8957-A3773F02200E}')
FOLDERID_ProgramFilesX86 = GUID('{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}')
FOLDERID_ProgramFilesCommon    = GUID('{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}')
FOLDERID_ProgramFilesCommonX64 = GUID('{6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D}')
FOLDERID_ProgramFilesCommonX86 = GUID('{DE974D24-D9C6-4D3E-BF91-F4455120B917}')

# common
FOLDERID_PublicDesktop   = GUID('{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}')
FOLDERID_PublicDocuments = GUID('{ED4824AF-DCE4-45A8-81E2-FC7965083634}')
FOLDERID_PublicDownloads = GUID('{3D644C9B-1FB8-4f30-9B45-F670235F79C0}')
FOLDERID_PublicMusic     = GUID('{3214FAB5-9757-4298-BB61-92A9DEAA44FF}')
FOLDERID_PublicPictures  = GUID('{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}')
FOLDERID_PublicVideos    = GUID('{2400183A-6185-49FB-A2D8-4A392A602BA3}')
FOLDERID_CommonStartMenu = GUID('{A4115719-D62E-491D-AA7C-E74B8BE3B067}')
FOLDERID_CommonPrograms  = GUID('{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}')
FOLDERID_CommonStartup   = GUID('{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}')
FOLDERID_CommonTemplates = GUID('{B94237E7-57AC-4347-9151-B08C6C32D1F7}')

# peruser
FOLDERID_Desktop         = GUID('{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}')
FOLDERID_Documents       = GUID('{FDD39AD0-238F-46AF-ADB4-6C85480369C7}')
FOLDERID_Downloads       = GUID('{374DE290-123F-4565-9164-39C4925E467B}')
FOLDERID_Music           = GUID('{4BD8D571-6D19-48D3-BE97-422220080E43}')
FOLDERID_Pictures        = GUID('{33E28130-4E1E-4676-835A-98395C3BC3BB}')
FOLDERID_Videos          = GUID('{18989B1D-99B5-455B-841C-AB7C74E4DDFC}')
FOLDERID_LocalAppData    = GUID('{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}')
FOLDERID_LocalAppDataLow = GUID('{A520A1A4-1780-4FF6-BD18-167343C5AF16}')
FOLDERID_RoamingAppData  = GUID('{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}')
FOLDERID_StartMenu       = GUID('{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}')
FOLDERID_Programs        = GUID('{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}')
FOLDERID_Startup         = GUID('{B97D20BB-F46A-4C97-BA10-5E3608430854}')
FOLDERID_Templates       = GUID('{A63293E8-664E-48DB-A079-DF759E0509F7}')
FOLDERID_UserProgramFiles = GUID('{5CD7AEE2-2219-4A67-B85D-6C9CE15660CB}')

class SimpleNamespace(object):
    def __init__(self, **kwds):
        vars(self).update(kwds)
    def __dir__(self):
        return [x for x in sorted(vars(self)) if not x.startswith('__')]

FOLDERID = SimpleNamespace(
    # fixed
    Windows = FOLDERID_Windows,
    System = FOLDERID_System,
    SystemX86 = FOLDERID_SystemX86,
    Fonts = FOLDERID_Fonts,
    ResourceDir = FOLDERID_ResourceDir,
    UserProfiles = FOLDERID_UserProfiles,
    Profile = FOLDERID_Profile,
    Public = FOLDERID_Public,
    ProgramData = FOLDERID_ProgramData,
    ProgramFiles = FOLDERID_ProgramFiles,
    ProgramFilesX64 = FOLDERID_ProgramFilesX64,
    ProgramFilesX86 = FOLDERID_ProgramFilesX86,
    ProgramFilesCommon = FOLDERID_ProgramFilesCommon,
    ProgramFilesCommonX64 = FOLDERID_ProgramFilesCommonX64,
    ProgramFilesCommonX86 = FOLDERID_ProgramFilesCommonX86,
    # common
    PublicDesktop=FOLDERID_PublicDesktop,
    PublicDocuments=FOLDERID_PublicDocuments,
    PublicDownloads=FOLDERID_PublicDownloads,
    PublicMusic=FOLDERID_PublicMusic,
    PublicPictures=FOLDERID_PublicPictures,
    PublicVideos=FOLDERID_PublicVideos,
    CommonStartMenu=FOLDERID_CommonStartMenu,
    CommonPrograms=FOLDERID_CommonPrograms,
    CommonStartup=FOLDERID_CommonStartup,
    CommonTemplates=FOLDERID_CommonTemplates,
    # user
    Desktop=FOLDERID_Desktop,
    Documents=FOLDERID_Documents,
    Downloads=FOLDERID_Downloads,
    Music=FOLDERID_Music,
    Pictures=FOLDERID_Pictures,
    Videos=FOLDERID_Videos,
    LocalAppData=FOLDERID_LocalAppData,
    LocalAppDataLow=FOLDERID_LocalAppDataLow,
    RoamingAppData=FOLDERID_RoamingAppData,
    StartMenu=FOLDERID_StartMenu,
    Programs=FOLDERID_Programs,
    Startup=FOLDERID_Startup,
    Templates=FOLDERID_Templates,
    UserProgramFiles=FOLDERID_UserProgramFiles,
)

if __name__ == '__main__':
    for fid in dir(FOLDERID):
        print("%s = %s" % (fid, get_known_folder_path(getattr(FOLDERID, fid))))

rawDescription: Python: Finding user id and moving directories (Windows)


code:
import re
photos.sort(key = lambda x : int(re.findall('\d+', x)[0]))

rawDescription: Sorting a list and dict keys

description: Sorting a list and dict keys


code: finger_lengths, finger_names = zip(*sorted(zip(finger_lengths, finger_names)))

rawDescription: How to sort object attributes

description: Sort object attributes


code:
x=np.random.random((10,2))
x
idx = np.argsort(x[:,0])
idx
xsorted = x[idx,:]
xsorted

rawDescription: Sorting an Array Alongside a 2d Array

description: Sorting an Array Alongside a 2d Array


code:
p = 0.40

def generate():
    return random.random() >= p

rawDescription: Python - modelling probability

description: Python - modelling probability


rawDescription: How to plot a PMF of a sample?

description: Plot a PMF of a sample


code:
success_codes = range(200, 300)
retry_code    = range(400, 405) + range(500, 504)
fail_codes    = range(504, 507)

rawDescription: Python Integer for loop 200 to 205

description: Python Integer for loop 200 to 205


code:
class DictControl(Control):
        def __len__(self):
                return 3
        def __getitem__(self, k):
                if k == 'device_control':
                        return self.word
                elif k == 'device_read_permissions':
                        return self.low
                elif k == 'device_write_permissions':
                        return self.high
                else: raise KeyError
        def __setitem__(self, k, v):
                if k == 'device_control':
                        self.word = v
                elif k == 'device_read_permissions':
                        self.low = v
                elif k == 'device_write_permissions':
                        self.high = v
                else: raise KeyError

rawDescription: Creating pythonic objects that share memory


rawDescription: Slicing by start and stop string values in Python


rawDescription: searching web-client for python that can handle frames

description: Searching web-client for python that can handle frames


code:
from xml.dom import minidom

xmldoc = minidom.parse('filePath')
root = xmldoc.documentElement

ones = root.getElementsByTagName('one')

L = []
for one in ones:
    m = {}
    #print onn.getElementsByTagName('a')[0].childNodes[0].nodeValue
    #print n.getElementsByTagName('b')[0].childNodes[0].nodeValue
    #print n.getElementsByTagName('c')[0].childNodes[0].nodeValue
    for n in one.childNodes:
         if n.nodeType == n.ELEMENT_NODE:
                 m[n.nodeName] =n.firstChild.nodeValue
    L.append(m)

rawDescription: parsing a xml file

description: Parsing a xml file


code:
def import_path(name):
    modname, _, attr = name.rpartition('.')
    if not modname:
        # name was just a single module name
        return __import__(attr)
    m = __import__(modname, fromlist=[attr])
    return getattr(m, attr)

rawDescription: Dynamically import a callable given the full module path?


code: s.replace("%0", "something")

rawDescription: Replace % followed by a number in a string


code:
# page.py
class Page(object):
    # ...
    def something(self):
        import session
        self.other_session = session.Session()

rawDescription: Way to alter behavior based on caller using property getter without reflection or making caller a member in Python


rawDescription: Change set of indices

description: Change set of indices


code:
from collections import Counter
a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2]]

cn = Counter(map(tuple,a))

print([sub for sub in a if cn[tuple(sub)] > 1])

rawDescription: How should I get a list of duplicate sublists in a list?


code:
domain = 'http://www.example.com/'
'.'.join(domain.replace('http://','').split('/')[0].split('.')[-2:])

rawDescription: Strip URL - Python

description: Strip URL - Python


code:
d = D((e, i) for i, e in enumerate('abc'))
d
d.a
d.get('b')
d.setdefault('d', []).append(3)
d.foo = 'bar'
print(d)

rawDescription: How would I implement a dict with Abstract Base Classes in Python?


code: df = df.reset_index()

rawDescription: how to create columns out of a multi-index in a pandas dataframe?

description: Create columns out of a multi-index in a pandas dataframe


code:
import  requests
from bs4 import BeautifulSoup

r = requests.get("https://cm.jefferson.edu/rna22/Precomputed/InputController?download=ALL&ident=hsa_miR_107%20hsa_miR_5011_5p%20hsa_miR_326&minBasePairs=12&maxFoldingEnergy=-12&minSumHits=1&maxProb=.1&version=MB21E78v2&species=HomoSapiens&type=mRNA")

soup =  BeautifulSoup(r.content)
for b in soup.find_all("br"):
    b.replace_with("\n")
print(soup.text)

rawDescription: Print a line of HTML, keeping the right format


rawDescription: How do I do this type of 2D "fancy" indexing without python loops?

description: Do this type of 2D "fancy" indexing without python loops


code: del str

rawDescription: Overloaded or rewritten str() function in Python


code:
m = re.search('^!.*^!', text, re.MULTILINE | re.DOTALL)
m.group(0)

rawDescription: Matching between two ! in a file in python


code:
from PyQt4 import QtCore, QtGui, QtWebKit

class WebPage(QtWebKit.QWebPage):
    def __init__(self):
        QtWebKit.QWebPage.__init__(self)
        self.mainFrame().setScrollBarPolicy(
            QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff)
        self.mainFrame().setScrollBarPolicy(
            QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff)
        self.mainFrame().loadFinished.connect(self.handleLoadFinished)
        printer = QtGui.QPrinter()
        printer.setPaperSize(QtGui.QPrinter.A4)
        self.setViewportSize(printer.paperSize(
            QtGui.QPrinter.DevicePixel).toSize())

    def capture(self, url):
        self._url = QtCore.QUrl(url)
        QtCore.QTimer.singleShot(0, self.handleLoad)

    def handleLoad(self):
        self.mainFrame().load(self._url)

    def handleLoadFinished(self):
        image = QtGui.QImage(self.viewportSize(),
                             QtGui.QImage.Format_ARGB32)
        painter = QtGui.QPainter(image)
        self.mainFrame().render(painter)
        painter.end()
        output = QtCore.QFile()
        output.open(1, QtCore.QIODevice.WriteOnly)
        image.save(output, 'PNG')
        sys.exit(0)

if __name__ == '__main__':

    import sys, signal
    app = QtGui.QApplication(sys.argv)
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    page = WebPage()
    page.capture(sys.argv[1])
    sys.exit(app.exec_())

rawDescription: Set Parameters of Screenshot taken by Python


rawDescription: Converting positive and negative values to a bitstring using numpy.clip


code:
from django.conf.urls.defaults import *
urlpatterns = patterns('django.views.generic.simple',
    (r'^$',                    'direct_to_template', {'template': 'page.html'}),
    (r'^external/content/a/$', 'direct_to_template', {'template': 'a.html'}),
    (r'^external/content/b/$', 'direct_to_template', {'template': 'b.html'}),
)

rawDescription: Django + Jquery, expanding AJAX div

description: Django + Jquery, expanding AJAX div


code:
import asyncio
from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory

from ..transport import Transport

class Protocol(WebSocketClientProtocol):

    def __init__(self):
        self.ws = None
        super().__init__()

    @asyncio.coroutine
    def onConnect(self, response):
        pass # connect handeled when SocketIO 'connect' packet is received

    @asyncio.coroutine
    def onOpen(self):
        self.ws.onOpen()

    @asyncio.coroutine
    def onMessage(self, payload, isBinary):
        self.ws.onMessage(payload=payload, isBinary=isBinary)

    @asyncio.coroutine
    def onClose(self, wasClean, code, reason):
        if not wasClean:
            self.ws.onError(code=code, reason=reason)

        self.ws.onClose()

class Websocket(Transport):

    name = 'websocket'

    def __init__(self, socket, **kwargs):
        super().__init__(socket)

        loop = kwargs.pop('loop', None)
        self.loop = loop or asyncio.get_event_loop()

        self.transport = None
        self.protocol = None

        self.ready = True

    def open(self):
        url = self.prepareUrl()
        if bool(self.socket.options.query):
            url = '{0}?{1}'.format(url, self.socket.options.query)

        factory = WebSocketClientFactory(url=url, headers=self.socket.options.headers)
        factory.protocol = Protocol

        coro = self.loop.create_connection(factory, host=self.socket.options.host, port=self.socket.options.port, ssl=self.socket.options.secure)

        task = self.loop.create_task(coro)
        task.add_done_callback(self.onWebSocketInit)

    def onWebSocketInit(self, future):
        try:
            self.transport, self.protocol = future.result()
            self.protocol.ws = self
        except Exception:
            self.onClose()

    def send(self, data):
        self.protocol.sendMessage(payload=data.encode('utf-8'), isBinary=False)
        return self

    def close(self):
        if self.isOpen:
            self.protocol.sendClose()
        return self

    def onOpen(self):
        super().onOpen()
        self.socket.setBuffer(False)

    def onMessage(self, payload, isBinary):
        if not isBinary:
            self.onData(payload.decode('utf-8'))
        else:
            self.onError('Message arrived in binary')

    def onClose(self):
        super().onClose()
        self.socket.setBuffer(True)

    def onError(self, code, reason):
        self.socket.onError(reason)

rawDescription: Callbacks from autobahn WebSocketClientProtocol to another object


rawDescription: NumPy: using loadtxt or genfromtxt to read a ragged structure


code:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.path as mpath
import matplotlib.transforms as mtrans

import numpy as np

class FixedPointOffsetTransform(mtrans.Transform):
    """
    Always returns the same transformed point plus
    the given point in device coordinates as an offset.
    """
    def __init__(self, trans, fixed_point):
        mtrans.Transform.__init__(self)
        self.input_dims = self.output_dims = 2
        self.trans = trans
        self.fixed_point = np.array(fixed_point).reshape(1, 2)

    def transform(self, values):
        fp = self.trans.transform(self.fixed_point)
        values = np.array(values)
        if values.ndim == 1:
            return fp.flatten() + values
        else:
            return fp + values

plt.scatter([3.1, 3.2, 3.4, 5], [2, 2, 2, 6])

ax = plt.gca()
fixed_pt_trans = FixedPointOffsetTransform(ax.transData, (0, 2))

xdata_yfixed = mtrans.blended_transform_factory(ax.transData, fixed_pt_trans)

x = [3.075, 3.425] # x range of box (in data coords)
height = 20 # of box in device coords (pixels)
path = mpath.Path([[x[0], -height], [x[1], -height],
                   [x[1], height],  [x[0], height],
                   [x[0], -height]])
patch = mpatches.PathPatch(path, transform=xdata_yfixed,
                           facecolor='red', edgecolor='black',
                           alpha=0.4, zorder=0)
ax.add_patch(patch)

plt.show()

rawDescription: Matplotlib artist to stay same size when zoomed in but ALSO move with panning?


code: self.children = {}

rawDescription: How and when to appropriately use weakref in Python


code:
def do_all(iterable, func):
    dispose(itertools.imap(func, iterable))

rawDescription: In Python, is there a way to call a method on every item of an iterable?


code:
if MyNewCube in MyMoveCube:
    do_whatever()

rawDescription: Check if object is already in list (Python)


code:
list = [1,2,3]
it3 = iter(list)
it4 = iter(list)
id(it3)
id(it4)
id(list)

rawDescription: Finding words that are the reverse of each other in a file


code:
import timeit
timeit.Timer('p1 = np.dstack((PARTS[k].partposit for k in sorted(PARTS.keys())))', "from __main__ import np, PARTS").timeit(number = 1)

rawDescription: efficiently dstack arrays from dictionary python

description: Efficiently dstack arrays from dictionary python


code:
from threading import Lock

_balance_lock = Lock()

class BalanceStale(Exception):
    pass

def set_balance_if_known_value_is_still_current(old_value, new_value):
    with _balance_lock:
        if _balance != old_value:
            raise BalanceStale('{} != {}'.format(_balance, old_value))
        else:
            _balance = new_value

rawDescription: How do I import and change a value from one script to another in python?

description: Import and change a value from one script to another in python


code:
from django.shortcuts import render

def my_view(request):
    return render(request, 'template.html' )

rawDescription: Including user statistics for multiple views


code:
@cache_w_keyfunc(lambda foo, bar: (bar,))
def my_function(foo, bar):
    pass

@cache_w_keyfunc(lambda user, foo, bar: (foo, bar))
def another_function(user, foo, bar):
    pass

rawDescription: python decorator parameter using variable from function its wrapping

description: Python decorator parameter using variable from function its wrapping


code:
 # Event methods
def __commit_update__(self):

    # create a new db session, which avoids the ResourceClosedError
    session = create_db_session()

    from techmuseum.modules.sensors.models import SoundsRaw
    # Get the SoundsRaw record by uuid (self contains the object being updated,
    # but we can't just update/commit self -- we'd get a ResourceClosedError)
    sound = session.query(SoundsRaw).filter_by(uuid=self.uuid).first()

    # Extract text from audio file
    audio_text = compute_text_from_audio_file(sound)

    # Update the 'text' field of the sound
    sound.text = audio_text

    # Commit the update to the sound
    session.add(sound)
    session.commit()

def create_db_session():
    # create a new Session
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker

    psql_url = app.config['SQLALCHEMY_DATABASE_URI']
    some_engine = create_engine(psql_url)

    # create a configured "Session" class
    session = sessionmaker(bind=some_engine)

    return session

rawDescription: SQLALchemy "after_insert" doesn't update target object fields


code:
import itertools

l1 = 'AB'
l2 = 'CDE'

n = min(len(l1),len(l2))
print('; '.join(
    ','.join(a+b for a,b in zip(s1,s2))
    for s1,s2 in itertools.product(
        itertools.permutations(l1,n),
        itertools.combinations(l2,n),
    )
))

rawDescription: Contracting elements from two different lists


code:
class Item:
    def __init__(self,a):
        self.a=a

class Sub(Item):
    def __init__(self,a,b):
        self.b=b
        Item.__init__(self,a)

class SubSub(Sub):
    def __init__(self,a,b,c):
       self.c=c
       Sub.__init__(self,a,b)

obj1=Item(1)
obj2=Sub(1,2)
obj3=SubSub(1,2,3)
isinstance(obj2, type(obj1))
issubclass(type(obj2), Item)

rawDescription: Test an object is a subclass of the type of another instance


code:
def main(): #This is the self.osc.main() function
    while True: #run forever
        doSomething()

def main(): #This is the self.main() function
    while True: #also run forever
        doSomethingElse()

rawDescription: How can I start a graphical widget without control flow getting stuck in its main loop in python?

description: Start a graphical widget without control flow getting stuck in its main loop in python


code:
object_id = int([i for i in str(request.path).split('/') if i][-1])
print(object_id)

rawDescription: How to extract a number from a request.path in Django

description: Extract a number from a request.path in Django


code:
unq, unq_idx, unq_cnt = np.unique(a[:, -1], return_inverse=True,
                                  return_counts=True)

rawDescription: balance numpy array with over-sampling

description: Balance numpy array with over-sampling


code:
nextcustomer = "yes"
while nextcustomer != "no":
    amtgiven = 0
    change = 0
    quantity = 0
    foodprice = 0
    totalprice = 0
    billtax = 0
    finalbill = 0
    itemnum = 0

rawDescription: Nested while loop with trailer values

description: Nested while loop with trailer values


code:
import ast
import json

with open('file.txt') as f:
    lines = f.read().split('\n')
contents = [ast.literal_eval(line) for line in lines]

# ...and now choose from above how you'd like to write it back to the file

rawDescription: how do i find and replace items in a text file in pyscripter?

description: Find and replace items in a text file in pyscripter


rawDescription: Inner print statement not working

description: Inner print statement not working


code:
p = sns.pairplot(data=g, hue="Label", palette="Set2",
             diag_kind="kde", size=4, vars=labels)
#bottom labels
p.fig.text(0.33, -0.01, "Bin: %s"%(n), ha ='left', fontsize = 15)
p.fig.text(0.33, -0.04, "Num Points: %d"%(len(g)), ha ='left', fontsize = 15)

rawDescription: How to annotate seaborn pairplots?

description: Annotate seaborn pairplots


code:
pat = re.compile('''
    [^A-Z]    # any character except a capital letter
    [A-Z]{3}  # three capital letters
    (         # the beginning of a capturing group
    [a-z]     # one lowercase letter
    )         # the end of the group
    [A-Z]{3}  # three capital letters
    [^A-Z]    # any character except a capital letter
    ''', re.VERBOSE)

rawDescription: Python Challenge Lvl 3 Explaination (warning spoilers!)


code:
from PyQt4 import QtCore, QtGui

class ClickHandler():
    def __init__(self, time):
        self.timer = QtCore.QTimer()
        self.timer.setInterval(time)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.timeout)
        self.click_count = 0

    def timeout(self):
        if self.click_count == 1:
            print('Single click')
        elif self.click_count > 1:
            print('Double click')
        self.click_count = 0

    def __call__(self):
        self.click_count += 1
        if not self.timer.isActive():
            self.timer.start()

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        self.button1 = QtGui.QPushButton("Button 1")
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.button1)
        self.setLayout(hbox)

        self.click_handler = ClickHandler(300)
        self.button1.clicked.connect(self.click_handler)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = MyDialog()
    w.show()
    sys.exit(app.exec_())

rawDescription: Pyqt Mouse MouseButtonDblClick event

description: Pyqt Mouse MouseButtonDblClick event


code:
from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

rawDescription: Django What is the best way to format forms?


code:
a = soup.select_one("div.address > a")
a.br.replace_with(" ")
a.get_text().strip()

rawDescription: BS4 How to get text without using .text?

description: BS4 How to get text without using .text


code:
y_s1 = y_s1 + sphere_vel          # 1
if y_s1 > 370:
    sphere_vel = sphere_vel * -1  # 2
if y_s1 < 0:
    sphere_vel = sphere_vel * -1

y_s2 = y_s2 + sphere_vel          # 3
if y_s2 > 370:
    sphere_vel = sphere_vel * -1
if y_s2 < 0:
    sphere_vel = sphere_vel * -1  # 4

rawDescription: Strange timing issues in PyGame when animating bouncing balls


rawDescription: Create adjacency matrix in python from csv dataset


code:
while gaming == 1:
    game()

rawDescription: Python Rock Paper Scissors function

description: Python Rock Paper Scissors function


code:
#!/usr/bin/env python
from gi.repository import Gtk, GdkPixbuf, GLib
import sys

class ImageWindow(Gtk.Window):
    def __init__(self, image_data):
        Gtk.Window.__init__(self, title="image test")
        self.connect('delete-event', Gtk.main_quit)

        self.image = Gtk.Image()
        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.add(self.image)
        self.add(scrolled_window)

        if len(image_data) == 0:
            return

        self.loader = GdkPixbuf.PixbufLoader()
        self.loader.write(image_data)
        self.loader.close()
        self.pixbuf = self.loader.get_pixbuf()
        self.image.set_from_pixbuf(self.pixbuf)

        width = self.pixbuf.get_width()
        height = self.pixbuf.get_height()
        self.dimension = float(width) / height
        self.set_default_size(width, height)
        self.connect('check-resize', self.on_resize)

    def on_resize(self, window):
        width, height = self.get_size()
        if float(width) / height > self.dimension:
            self.pixbuf = self.pixbuf.scale_simple(
                self.dimension * height,
                height,
                GdkPixbuf.InterpType.NEAREST
            )
        else:
            self.pixbuf = self.pixbuf.scale_simple(
                width,
                width / self.dimension,
                GdkPixbuf.InterpType.NEAREST
            )
        GLib.idle_add(self.image.set_from_pixbuf, self.pixbuf)

win = ImageWindow(sys.stdin.read())
win.show_all()
Gtk.main()

rawDescription: pyGtk: Image prevents window resize

description: PyGtk: Image prevents window resize


code:
class Foo:
    def __init__(self, x):
        self.x = x
    def __hash__(self):
        return self.x**2
    def __eq__(self, o):
        return o.x == self.x

rawDescription: Three tiers of equality comparison in Python


code:
from sympy import sum, var, solve
x = var('x')
f = lambda N: sum(n**2, (n, 1, N))
n = var("n")
f(x)

rawDescription: taking symbol in sum [sympy]

description: Taking symbol in sum [sympy]


code:
# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
from winpexpect import winspawn as spawn

child = spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
def get_list_of_vowel_count(name_list):
    vowels = "aeiouAEIOU"
    for name in name_list:
        yield sum([name.count(vowel) for vowel in vowels])

rawDescription: Counting vowels using nested loop in python


code:
final_df = raw_df.copy()
final_df['ID1'] = final_df['ID1'].map(id2)
final_df = final_df.rename(columns={'ID1': 'ID2'})

rawDescription: Random sampling and Pandas dataframes

description: Random sampling and Pandas dataframes


code:
if mv in ['n', 'N']:
    Me.Position.Y += 10

rawDescription: python if statement always

description: Python if statement always


code:
t = "The world is a small place, we should try to take care of it."
search(t,3)
(('is', 'a', 'small'), ('we', 'should', 'try'))

rawDescription: Extract words surrounding a search word

description: Extract words surrounding a search word


code: (k for k in set(sourceDict).intersection(targetDict) if sourceDict[key] != targetDict[key])

rawDescription: Compare values from two different dictionaries in Python?


code:
def put(my_list, x, positions):
    return [x if n in positions else i for n, i in enumerate(my_list)]
put(a, 1, [1, 2])

rawDescription: Is there a python method to set the specified elements to be some value in a list?


code:
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

gs = gridspec.GridSpec(4, 4)
m = 0

for i in range(0, 4, 2):
  for j in range(0, 4, 2):
    if m < 3:
      ax = plt.subplot(gs[i:i+2, j:j+2])
      ax.plot(range(0, 10), range(0, 10))
      m+=1
    else:
      ax = plt.subplot(gs[i:i+2, 1:3])
      ax.plot(range(0, 10), range(0, 10))

plt.show()

rawDescription: How to manually position one subplot graph in matplotlib.pyplot

description: Manually position one subplot graph in matplotlib.pyplot


code: x.GET(sys.argv[1], sys.argv[2])

rawDescription: How to call a class's method in python?

description: Call a class's method in python


code: np.histogram2d(x, y, bins=2)

rawDescription: Obtain frequencies in each bin for histogram2d


rawDescription: Changing hostname in a url

description: Changing hostname in a url


code:
def get_slice_along_first_dim(array_with_arbitrary_dimensions, idx):
    return array_with_arbitrary_dimensions[idx, ...]

def get_slice_along_last_dim(array_with_arbitrary_dimensions, idx):
    return array_with_arbitrary_dimensions[..., idx]

rawDescription: Python use array axis to select slice

description: Python use array axis to select slice


code:
magic_id_str = 'x100\x88\xce\xcf\xcfOrCAD '
magic_id = binascii.a2b_qp(magic_id_str)

rawDescription: What config file format to use for user-friendly strings of arbitrary bytes?


code:
@register.assignment_tag
def get_current_time(format_string):
    return datetime.datetime.now().strftime(format_string)

rawDescription: Put the result of simple tag into a variable


code:
logger = logging.getLogger(__name__)
logger.addHandler(someutils.null_handler)

rawDescription: Elegant setup of Python logging in Django


code:
c = 'F'
ord(lower(c)) - ord('a') + 1

rawDescription: Python code for calculating number of an alphabet


rawDescription: Pandas DataFrame group by value and get column & row indexes


code:
def extract_csv(fileobj, keywords, comment_tags, options):
    """Extract messages from XXX files.
    :param fileobj: the file-like object the messages should be extracted
                    from
    :param keywords: a list of keywords (i.e. function names) that should
                     be recognized as translation functions
    :param comment_tags: a list of translator tags to search for and
                         include in the results
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message, comments)``
             tuples
    :rtype: ``iterator``
    """
    import csv

    reader = csv.reader(fileobj, delimiter=',', quotechar='"')
    for row in reader:
        if row and row[0] != '':
            yield (lineno, ',', row[0], 'No comment')

rawDescription: xgettext from a csv file

description: Xgettext from a csv file


code:
mask = ~np.isclose(prices['price'], prices['price'].shift())
prices[mask]

rawDescription: Python: Using apply efficiently on a pandas GroupBy object


code: d = dict.fromkeys(doc_uid,project_name)

rawDescription: Create dictionary where keys from the list and value is common


code:
L = [['loraine','jessica'],'philip',['dave', 'jones'], 8, 7]
capitalizeNested(L)
L

rawDescription: python capitalize nested list with strings and integers

description: Python capitalize nested list with strings and integers


code:
x = np.random.rand(4, 5)
x[[0, 2], [1, 4]] = np.nan
x
x[~np.isnan(x)]  # 1D array with NaNs removed
x[~np.any(np.isnan(x), axis=1)]  # 2D array with rows with NaN removed

rawDescription: Remove NaN row from X array and also the corresponding row in Y


rawDescription: Python regexp everything between parenthesis on multiple lines


code:
import numpy as np
import pandas as pd
df = pd.read_table('data', sep='\s{2,}')
df['DateTimes'] = pd.to_datetime(df['DateTimes'])

microseconds = df.groupby(['DateTimes']).cumcount()
df['DateTimes'] += np.array(microseconds, dtype='m8[us]')

print(df)

rawDescription: Change datetime if duplicate found in dataframe


code: pat = re.compile(r'.(?=[A-Z])')

rawDescription: Using the .split() function based on conditions?


rawDescription: Pandas dataframe hide index functionality?


code:
class DatabaseConfig(Configuration):
    MYSQL_DB = 'DEFAULT'
    MYSQL_USER = os.environ.get('MYSQL_USER')
    MYSQL_PASS = os.environ.get('MYSQL_PASS')
    MYSQL_HOST = os.environ.get('MYSQL_HOST', 'localhost')
    MYSQL_PORT = os.environ.get('MYSQL_PORT', 3306)

    def MYSQL_URI(self):
        return 'mysql://{user}:{password}@{server}:{port}'.format(
            user=self.MYSQL_USER,
            password=self.MYSQL_PASS,
            server=self.MYSQL_HOST,
            port=self.MYSQL_PORT )

    def SQLALCHEMY_DATABASE_URI(self):
        return str(self.MYSQL_URI) + '/' + self.MYSQL_DB

DatabaseConfig()

rawDescription: How to implement compound configuration variables, or "module level properties?"

description: Implement compound configuration variables, or "module level properties?"


code:
msg = "Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n"
msg
import StringIO
buf = StringIO.StringIO(msg)
buf.readline()
buf.readline()

rawDescription: Python readline() from a string?

description: Python readline() from a string


code:
statement = "SELECT * FROM table WHERE column IN ({0})".format(
    ', '.join(['%s'] * len(filterList)))
cursor.execute(statement, filterList)

rawDescription: MySQL and PYTHON. How to query an WHERE 'column' IN tuple


code:
distA = stats.gamma(*stats.gamma.fit(A))
distB = stats.gamma(*stats.gamma.fit(B))

rawDescription: How can I manipulate the CDF of a sample such that it matches that of a different sample?

description: Manipulate the CDF of a sample such that it matches that of a different sample


code:
def recurseDict(nested_dict):
    output = []

    for key, value in nested_dict.iteritems():
        if isinstance(value,dict):
            output = output + recurseDict(value)
        else:
            # Do whatever you want here, I'll just add the values to a list
            output.append(nested_dict[key])
    return output

rawDescription: Python: How to continue a nested for loop?


code:
(1 << np.arange(m))
d[:,None] & (1 << np.arange(m))

rawDescription: Convert integer to binary array with suitable padding


rawDescription: partial_fit Sklearn's MLPClassifier

description: Partial_fit Sklearn's MLPClassifier


code:
L = [None, 1, 2]
min(x for x in L if x is not None)

rawDescription: List minimum in Python with None?

description: List minimum in Python with None


code:
shared_username = ['[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>, <User: awesome>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]']
[r.findall(item) for item in shared_username]

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

description: Convert this list in a given format


rawDescription: python: Sorting a list of lists over a range of elements

description: Python: Sorting a list of lists over a range of elements


rawDescription: How to keep my original dict when doing additon of Counter

description: Keep my original dict when doing additon of Counter


code:
with open("file") as i: # open file for reading, i = input file
  with open("temp", "w") as o: # open temp file in write mode, o = output
     for l in i: # read line by line
         o.write("'%s',text\n" % l[:-1]) # concate ' and text
          #       ^  ^ added `'` for each line
os.remove("file") # delete old file. Note:this is not needed in postfix system
os.rename("temp", "file")  # rename file

rawDescription: Appending Quotations in Text File to Each line


code: dict (zip (keys, values) )

rawDescription: Obtain a dict from an array of keys and one array of values


code:
# Define inverse transform, transforms display coordinates (pixels) to axes coordinates
inv = ax[1].transAxes.inverted()
# Inverse transform two points on the display and find the relative distance
pad_axes = inv.transform((pad_pixels, 0)) - inv.transform((0,0))
pad_xaxis = pad_axes[0]

rawDescription: Matplotlib: Adjust legend location/position


code:
a = np.array([2,3,4,5,6,7])
b = np.zeros((4, 4), dtype=a.dtype)
b[my_triu_indices(4, 1)] = a
b
b[my_triu_indices(4, 1)]

rawDescription: Wrapping/unwrapping a vector along array diagonals


code:
for row in range(HEIGHT):
    for col in range(WIDTH):
        if keygrid[row][col] in stockgrid[row][col]:
           stockgrid[row][col][keygrid[row][col]]+=1

rawDescription: Retreiving data from a nested deep.copy dictionary made by list comprehension in Python


code:
"pc 10 appears 4 times. First on row 4, last on row 101"
"pc 8 appears 3 times. First on row 3, last on row 13"

rawDescription: Time complexity of a huge list in python 2.7


code:
import io
import StringIO     # for Python 2.X
import pandas as pd

data = """\
      id1        id2           type       number
0     IE345      E90              I           38
1     IE345      E92              E           26
2     IE345      E93              E           21
3     IE345      E95              R            9
4     IE346      E94              I           41
7     IE346      BLK              E            1
"""

#loads = pd.read_csv(io.StringIO(data), sep='\s+', index_col=0)  # for Python 3.X
loads = pd.read_csv(StringIO.StringIO(data), sep='\s+', index_col=0)  # for Python 2.X

# **** interesting part starts here ****

# save all unique types, we will use it later
types = loads.type.unique()

df = pd.pivot_table(loads, values=['number'],
                       index = ['id1', 'id2'],
                       columns=['type'], margins=True,
                       aggfunc='sum', fill_value=0) \
       .reset_index()

# reset column names
df.columns = [c[1] if c[1] else c[0] for c in df.columns.tolist()]

df['max'] = df[types].idxmax(axis=1)

rawDescription: Unpivot/Flatten pandas pivot table into one level index


code: c = a.reshape((3, 4), order='F')

rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
inspect.ismodule(object)
inspect.isclass(object)
inspect.ismethod(object)
inspect.isfunction(object)

rawDescription: Test if function or method is normal or asynchronous


code:
class Vector(object):
    def __init__(self, x=0, y=0, z=0):
        self.x = x
        self.y = y
        self.z = z
    x = JonProperty('_x')
    y = JonProperty('_y')
    z = JonProperty('_z')

rawDescription: Can I add parameters to a python property to reduce code duplication?

description: Add parameters to a python property to reduce code duplication


code: self.foo = wx.StaticBoxSizer(self.box, wx.ORIENT)

rawDescription: How do I add items inside a static box while using Sizers?

description: Add items inside a static box while using Sizers


code:
class Translation (ndb.Expando):
    """ string_id: language, parent: question.key"""
    answers = ndb.LocalStructuredProperty(Answer, repeated = True) #Defined because GenericProperty doesn't support storing an entity.

class Answer (ndb.Model):
    text = ndb.StringProperty()
    is_correct = ndb.BooleanProperty(required = True, default = False)
    times_picked = ndb.IntegerProperty(default = 0)

class Question (ndb.Model):
    text = ndb.StringProperty()
    answers = ndb.LocalStructuredProperty(Answer, repeated = True)
    times_used = ndb.IntegerProperty(default = 0)

rawDescription: What would be the appropiate design for storing content in multiple languages in Google App Engine?


code:
class MyImage(QWidget):

    def __init__(self):
        super(MyImage, self).__init__(parent = None)
        self.mainLayout = QtGui.QHBoxLayout()
        self.setLayout(self.mainLayout)
        self.setPicture()

    def setPicture(self):
        picPath = os.getcwd() + "/someFolder/image.jpg"
        print(picPath) # Check if the path to your picture is correct.
        picMap = QtGui.QPixmap(picPath)

        picLabel = QtGui.QLabel(parent = None)
        picLabel.setGeometry(10,10,800,600)
        picLabel.setPixmap(picMap.scaled(780,580,QtCore.Qt.KeepAspectRatio))
        self.mainLayout.addWidget(picLabel)

rawDescription: Insert a Pixmap created in another class


rawDescription: How to print JSON with keys in numeric order (i.e. as if the string keys were integers)

description: Print JSON with keys in numeric order (i.e. as if the string keys were integers)


code: sorted(tuples, key=lambda t: t[::-1])

rawDescription: Sorting Tuples in a descending order based on the last item given in the tuple


rawDescription: Convert rgb color to english color name, like 'green'


code:
list_to_add_to = []
def add_to_list(a_list):
    a_list.append('test')
print(list_to_add_to)
add_to_list(list_to_add_to)
print(list_to_add_to)

rawDescription: Outcome of Function - Python

description: Outcome of Function - Python


code:
data = []
for line in infile:
    row = {}
    row['time'] = ...
    row['type'] = ...
    ...
    ...
    data.append(row)

rawDescription: How do I make one python dictionary to csv with headers?

description: Make one python dictionary to csv with headers


rawDescription: How to unpack a list?

description: Unpack a list


code:
timeit.timeit("sum(myList[0], [])", 'from __main__ import myList')
timeit.timeit("reduce(add, myList[0])", 'from __main__ import myList; from operator import add')
timeit.timeit("reduce(lambda a, b: a.extend(b) or a, myList[0], [])", 'from __main__ import myList')
timeit.timeit("list(chain.from_iterable(myList[0]))", 'from __main__ import myList; from itertools import chain')

rawDescription: How to print list of list into one single list in python without using any for or while loop?

description: Print list of list into one single list in python without using any for or while loop


rawDescription: several replacements in single regular expression

description: Several replacements in single regular expression


code:
def test_row(row):
    assert row  # or whatever

def test_column(col):
    assert col  # or whatever

rawDescription: pytest parameterize - row from CSV as a testcase

description: Pytest parameterize - row from CSV as a testcase


code:
def file_aware(docstring, mode):
    def deco(func):
        @functools.wraps(func)
        def wrapped(f, *args, **kwargs):
            if isinstance(f, str):
                file_obj = open(f, mode)
            else:
                file_obj = f
            return func(file_obj, *args, **kwargs)
        wrapped.__doc__ = docstring
        return wrapped
    return deco

rawDescription: What should I do with the docstring of a decorated function if the decorator changes the API?


code: wx.PostEvent(self.wxWindow, evt)

rawDescription: Simple wxPython post event from Process

description: Simple wxPython post event from Process


code: self.hitPaddle = false

rawDescription: How do I make the ball bounce off the paddle?

description: Make the ball bounce off the paddle


rawDescription: Index a numpy array with another array

description: Index a numpy array with another array


rawDescription: Obtain span title using beautifulsoup

description: Obtain span title using beautifulsoup


code:
for count,pos in enumerate(coords,1):
    setattr(self, "x%s" % count, pos)

rawDescription: Issue with creating variables on the go in a class in python


code:
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)

rawDescription: How to add first name and last name to Django-registeration-redux registeration form?

description: Add first name and last name to Django-registeration-redux registeration form


code:
import argparse
import sys

mangle_args=('file1','file2')
arguments=['--'+arg if arg in mangle_args else arg for arg in sys.argv[1:]]

parser=argparse.ArgumentParser()
parser.add_argument('--file1')
parser.add_argument('--file2')
options=parser.parse_args(arguments)

rawDescription: Python: argparse optional arguments without dashes


code:
ranks1 = dict(map(reversed, enumerate(sorted(dict1, key=dict1.get))))
ranks2 = dict(map(reversed, enumerate(sorted(dict2, key=dict2.get))))
diffs = dict((k, ranks2[k] - ranks1[k]) for k in dict1)

rawDescription: python dictionary values sorting

description: Python dictionary values sorting


code:
def top_k(students, k):
    toptobottom = sorted(students, key = lambda x: x[2], reverse = True)
    takeout= toptobottom[:k+1]
    result = []
    for takethat in takeout:
        if takethat[2] == 21:
            result.append(takethat)  # I indented this
            result.sort( key= lambda x: x[0])
        elif takethat[2] ==15:
            result.append(takethat)
    return result

rawDescription: Syntax in sorting code Python

description: Syntax in sorting code Python


rawDescription: Convert Java byte array to Python byte array


code:
result=''
...
result += '' #whatever
...
return result

rawDescription: Why am I getting a None value, and why is the number still being printed in Python?


code:
vals = [i.count(' ') for i in lst]
lst[vals.index(max(vals))]

rawDescription: Finding how many of a certain character in each element in a list


code:
def ParseBoolean (b):
    # ...
    if len(b) < 1:
        raise ValueError ('Cannot parse empty string into boolean.')
    b = b[0].lower()
    if b == 't' or b == 'y' or b == '1':
        return True
    if b == 'f' or b == 'n' or b == '0':
        return False
    raise ValueError ('Cannot parse string into boolean.')

rawDescription: how to parse a boolean argument in a script?

description: Parse a boolean argument in a script


code:
def hello():
    print("hi")

import types
type(hello) is types.BuiltinFunctionType
type(hello) is types.FunctionType

rawDescription: retrieve non built-in functions in python

description: Retrieve non built-in functions in python


code:
enemy1 = dict(name = "gargoyle",
              strength = 30,
              armour = 25,
              health = 50)

rawDescription: How to assign multiple values to one variable

description: Assign multiple values to one variable


code:
# not strictly necessary
class Persist(object):
    """
    Do not clear this variable with reset().
    """
    def __init__(self, val):
        self.val = val

# necessary
class Reset(object):
    """
    Clear this variable with reset().
    """
    def __init__(self, val):
        self.val = val

def BuildResets(cls):
    reset = cls.resetable = []
    persist = cls.persistent = []
    for name, obj in cls.__dict__.items():
        if isinstance(obj, Reset):
            setattr(cls, name, obj.value)
            reset.append(name)
        elif isinstance(obj, Persist):
            setattr(cls, name, obj.value)
            persist.append(name)
    return cls

rawDescription: Python object state tracking idiom

description: Python object state tracking idiom


code:
with open('to_output.tmp','a') as to_output:
    for a in App:
        # ... do your reading thing into the sets ...

        if row_id in cells and (row_id in biochemicals or row_id in enzymes):
            to_output.write('%s,' % row_id)
            cells.remove(row_id)
            biochemicals.remove(row_id)
            enzymes.remove(row_id)

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


rawDescription: Combining MultiIndex and Index in a PANDAS DataFrame


code: vTest = self.state

rawDescription: Django attribute is not up to date

description: Django attribute is not up to date


code:
import calendar
import datetime
df['AdjustedDateToEndOfMonth'] = df['ArrivalDate'].map(
    lambda x: datetime.datetime(
        x.year,
        x.month,
        max(calendar.monthcalendar(x.year, x.month)[-1][:5])
    )
)

rawDescription: Extracting just Month and Year from Pandas Datetime column (Python)


code:
def foo(): pass
foo.__dict__
foo.bar = 'baz'

rawDescription: If everything is an object, why can't I add attributes to some?


code:
values = [1,2,3,1,2,3,4]

from collections import defaultdict

def get_matches(x):
    my_dict = defaultdict(list)
    for ind, ele in enumerate(x):
        my_dict[ele].append(ind)
    return my_dict

rawDescription: Optimize search to find next matching value in a list


code:
from multiprocessing import Value
file_a = Value('i', 0)
file_b = Value('i', 0)
file_c = Value('i', 1)

rawDescription: Python share values

description: Python share values


code:
urlpatterns = patterns('',
    url(r'^faculty/(?P<slug>\w+)/$', FacultyDetail.as_view()),
)

rawDescription: django user queries to get data from database

description: Django user queries to get data from database


code:
from sklearn.preprocessing import LabelBinarizer, LabelEncoder, StandarScalar

encoders = ['gradelevel', 'subject', 'districtid']
scalars = ['sbmRate', 'pRate', 'assn1', 'assn2', 'assn3', 'assn4', 'assn5', 'attd1', 'attd2', 'attd3', 'attd4', 'attd5', 'sbm1', 'sbm2', 'sbm3', 'sbm4', 'sbm5']
mapper = DataFrameMapper(
    [('gender', LabelBinarizer())] +
    [(encoder, LabelEncoder()) for encoder in encoders] +
    [(scalar, StandardScaler()) for scalar in scalars]
)

rawDescription: how to apply preprocessing methods on several columns at one time in sklearn

description: Apply preprocessing methods on several columns at one time in sklearn


code:
#!/usr/bin/env python
import sys
from lxml import etree

def process(fname):
    f = open(fname)
    tree = etree.parse(f)
    root = tree.getroot()
    old = [112.907, 158.96, -54.7539, -10.1357]
    new = [1,2,3,4]
    d = dict(zip(old,new))
    nodes = root.findall('.//gco:Decimal', root.nsmap)
    for node in nodes:
        node.text = str(d[float(node.text)])
    f.close()
    return etree.tostring(root, pretty_print=True)

def main():
    fname = sys.argv[1]
    text = process(fname)
    outfile = open('out.xml', 'w+')
    outfile.write(text)
    outfile.close()

if __name__ == '__main__':
    main()

rawDescription: How to replace node values in XML with Python

description: Replace node values in XML with Python


code:
import os
files = os.listdir(path)
def func(x):
   return os.path.splitext(x)[::-1]
files.sort(key = func)

rawDescription: Listdir sorted by extension PYTHON

description: Listdir sorted by extension PYTHON


code:
import struct
from array import array

response = (0, 0, 117, 143, 6)
bytes = array('B', response[:-1])
struct.unpack('>I', bytes)

rawDescription: How do I convert part of a python tuple (byte array) into an integer

description: Convert part of a python tuple (byte array) into an integer


code:
class CustomWidget(QtGui.QWidget):

    # No argument signal
    custom_signal = QtCore.pyqtSignal()

    # Signal with int argument and a custom name
    custom_signal_int = QtCore.pyqtSignal(int, name='integerSignal')

    def atSomePointEvent(self, event):
        value = event.someValue()
        if isinstance(value, int):
            self.custom_signal_int.emit(value)
        else:
            self.custom_signal.emit()

rawDescription: Creating a class signal with pyqt4

description: Creating a class signal with pyqt4


rawDescription: Python, Regular Expression Postcode search


code:
import LoggingTools
if __name__ == '__main__':
    # Configure logger
    LoggingTools.initLogger(logging.DEBUG)
    #LoggingTools.initLogger(logging.INFO)

rawDescription: Python logging in multiple modules

description: Python logging in multiple modules


rawDescription: call __str__ inside a class? python 3.X

description: Call __str__ inside a class? python 3.X


rawDescription: Selecting the first index after a certain timestamp with a pandas TimeSeries


code:
# Inputs
original_approach(a,b)
vectorized_approach(a,b)

rawDescription: Cumulative addition/multiplication in NumPy


code: subprocess.call(['./arraytest'] + [str(s) for s in HSPACE], shell=False)

rawDescription: How to pass an array from python to shell script and execute it?

description: Pass an array from python to shell script and execute it


code:
a = ['Hello', 'and', 'welcome']
print( ' '.join(a) ) # Prints: Hello and welcome

rawDescription: Python-Unable to convert a list to string


code:
'drama'
'mystery'
'horror'
'psychological'
'fantasy',
'romance',
'adventure',
'science fiction'

rawDescription: trouble with nltk python NaiveBayesClassifier, I keep getting same probabilities inputs correct?

description: Trouble with nltk python NaiveBayesClassifier, I keep getting same probabilities inputs correct


rawDescription: Biopython: extract sequences not covered by any SeqFeatures


code:
query = """INSERT INTO `data` (frame, sensor_row, sensor_col, value) VALUES (%s, %s, %s, %s ) """
rows, cols, frames = numpy.nonzero(data)
values = [(row, col, frame, val) for row, col, frame, val in zip(rows, cols, frames, data[rows,cols,frames])]
cur.executemany(query, values)

rawDescription: How can I improve my INSERT statement performance?

description: Improve my INSERT statement performance


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from ScrolledText import *
import tkFileDialog
import tkMessageBox
from Tkinter import Tk, Text, BOTH, W, N, E, S, Menu
from ttk import Frame, Button, Label, Style

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Grades")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Grades:")
        lbl.grid(sticky=W, pady=4, padx=5)

        lbl = Label(self, text="Average\n Grade:")
        lbl.grid(row=3, column=3, pady=5)

        self.textPad = ScrolledText(self)
        self.textPad.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)

        abtn = Button(self, text="Save",command=self.save_command)
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close", command=self.onExit)
        cbtn.grid(row=2, column=3, pady=4)

        hbtn = Button(self, text="Help", command=self.about_command)
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu = Menu(fileMenu)
        submenu.add_command(label="Student")
        submenu.add_command(label="New Student")

        fileMenu.add_cascade(label='Import', menu=submenu, underline=0)
        fileMenu.add_command(label="Open...", command=self.open_command)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)

        menubar.add_cascade(label="File", underline=0, menu=fileMenu)

    def onExit(self):
        self.parent.destroy()

    def about_command(self):
        label = tkMessageBox.showinfo("About", "Grade keeping\n program by Starwarsfan2099")

    def save_command(self):
        file = tkFileDialog.asksaveasfile(mode='w')
        if file != None:
        # slice off the last character from get, as an extra return is added
            data = self.textPad.get('1.0', 'end-1c')
            file.write(data)
            file.close()

    def open_command(self):
            file = tkFileDialog.askopenfile(mode='rb',title='Select a file')
            if file != None:
                contents = file.read()
                self.textPad.insert('1.0', contents)
                file.close()

def main():
    root = Tk()
    root.geometry("350x300+300+300")
    app = Example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python Tk display and edit a file

description: Python Tk display and edit a file


rawDescription: Remove a value from a set with a function decorator


code: df

rawDescription: Python Pandas Dataframe to Nested Tuples


code: window["foo"]

rawDescription: javascript locals()?

description: Javascript locals()


rawDescription: Restore __builtins__ to default

description: Restore __builtins__ to default


code:
df
df[(df != df.shift()).any(axis=1)]

rawDescription: Drop Duplicate in market data

description: Drop Duplicate in market data


code:
def collatz(n, iterations = None):
    if iterations is None:
        iterations = []
    # Stuff
    elif n % 2 == 0:
        even = n / 2
        collatz(even, iterations)
    else:
        odd = (3 * n) + 1
        collatz(odd, iterations)

rawDescription: Copy a function in python

description: Copy a function in python


code: value = data.get(target, 'Target not found')

rawDescription: Finding a string in a list and returning a secondary value with python


code:
import numpy as np
import pymc as pm
import matplotlib.pyplot as plt
from pymc import glm

## Make some data
x = np.array(range(0,50))
y = np.random.uniform(low=0.0, high=40.0, size=50)
y = 2*x+y
## plt.scatter(x,y)

data = dict(x=x, y=y)
with pm.Model() as model:
    # specify glm and pass in data. The resulting linear model, its likelihood and
    # and all its parameters are automatically added to our model.
    pm.glm.glm('y ~ x', data)
    step = pm.NUTS() # Instantiate MCMC sampling algorithm
    trace = pm.sample(2000, step)

##fig = pm.traceplot(trace, lines={'alpha': 1, 'beta': 2, 'sigma': .5});## traces
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(x, y, label='data')
glm.plot_posterior_predictive(trace, samples=50, eval=x,
                              label='posterior predictive regression lines')

rawDescription: Estimating the Posterior Predictive in Regression


code:
DEBUG=False
TEMPLATE_DEBUG=False
from _base import *

rawDescription: Managing multiple settings.py files

description: Managing multiple settings.py files


code:
def parentIsAlive(self):
    try:
        # try to call Parent
        os.kill(self.parentPID, 0)
    except OSError:
        # *beeep* oh no! The phone's disconnected!
        return False
    else:
        # *ring* Hi mom!
        return True

rawDescription: Python-daemon doesn't kill its kids

description: Python-daemon doesn't kill its kids


rawDescription: How to read aloud Python List Comprehensions?

description: Read aloud Python List Comprehensions


code: df['uids'] = df.apply(lambda row: set(row['uids']), axis=1)

rawDescription: How to convert list into set in pandas?

description: Convert list into set in pandas


code:
testNum = 0xa1b2c3
hex(testNum)
test = hex(testNum)
isinstance(test, str)

rawDescription: Python - convert from hex integer to hex string


code:
def function1(a, b, c):
    s = sorted((a, b, c), reverse=True)
    return s[0] + s[1]

rawDescription: Getting two largest numbers from three numbers without using conditional statement or loop in python 3.5


rawDescription: Regular Expressions in data parsing Python


code:
log_listener = lambda event, params: log_event(context, event, params)
notifier.add_listener(log_listener)

rawDescription: How does the functools partial work in Python?


rawDescription: np.where() not returning expected indices in numpy python

description: Np.where() not returning expected indices in numpy python


code:
def my_func(a,b):
    result = [b[i] for i in range(len(b)) if a[i] == 5]
    return np.asarray(result)

rawDescription: Function that extracts value from one array depending on the value of another array


code:
b
c = b.reshape(2,3,order='F')
c

rawDescription: numpy array row major and column major

description: Numpy array row major and column major


rawDescription: How to sort a Series or DataFrame by a given index order?

description: Sort a Series or DataFrame by a given index order


rawDescription: Parsing integers from an alphanumeric string in Python


code: any(x is True or x is False for x in [True, 2])

rawDescription: Python - Enforce non-occurence of bool in list


code:
chars_to_remove = ['.', '!', '?']
subj = 'A.B!C?'
subj.translate(None, ''.join(chars_to_remove))

rawDescription: Removing a list of characters in string

description: Removing a list of characters in string


code:
body=[]
for item in parsed:
    body.append(item['resource']['caseNumber'], \
        item['resource']['subject'], \
        item['resource']['status'], \
        item['resource']['severity'] )

rawDescription: Encompass the output of a for loop into a variable in python


code: np.broadcast_arrays(i, [1,2])

rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
import subprocess
subprocess.Popen([r'C:\test\sample.exe', '-color'])

rawDescription: Pass arguments to executable in Python

description: Pass arguments to executable in Python


code:
sigma1 = sigma.copy()
sigma2 = sigma.copy()
sigma3 = sigma.copy()
r1 = r.copy()
r2 = r.copy()
r3 = r.copy()

initial(n, a, b, c, eps, sigma1, r1)
normal(n, a, b, c, eps, sigma2, r2)
function(n, a, b, c, eps, sigma3, r3)
np.testing.assert_array_almost_equal(sigma1, sigma2)
np.testing.assert_array_almost_equal(sigma1, sigma3)
np.testing.assert_array_almost_equal(r1, r2)
np.testing.assert_array_almost_equal(r1, r3)

rawDescription: Optimize this loop with numpy

description: Optimize this loop with numpy


code:
from lib.settings import Values
from lib import Helper

rawDescription: How to import classes defined in __init__.py

description: Import classes defined in __init__.py


code:
import os

# Project root is intended to be used when building paths,
# e.g. ``os.path.join(PROJECT_ROOT, 'relative/path')``.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))

# Absolute path to the directory that will hold uploaded files.
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'uploads/')

rawDescription: Django remove image based on id

description: Django remove image based on id


code:
import facs
dir (facs)

rawDescription: Python C-ext namespace mixed with regular python submodules?


code: df_input['Color'] = resultless

rawDescription: Not getting the proper output with re.findall


rawDescription: Split array byte string in Python

description: Split array byte string in Python


code:
for date_row in soup.select('table tbody.body tr.date'):
    print('Found a date row', date_row)
    for elem in date_row.next_siblings:
        if not elem.name:
            # NavigableString (text) element between rows
            continue
        if 'right' not in elem.get('class', []):
            # all done, found a row that doesn't have class="right"
            break
        print('Right row grouped with the date', elem)
    print()

rawDescription: beautiful soup extracting parent/sibling tr table class

description: Beautiful soup extracting parent/sibling tr table class


code:
L=[1, 2, 3]
def fgen():
    local_n = global_n
    def f():
        return local_n * local_n
    return f
a, b, c = [fgen() for global_n in L]
a()
b()
c()

rawDescription: Confused by lexical closure in list comprehension


code: options = {"today": dt.today_, "yesterday": dt.yesterday} # etc

rawDescription: How to pass function as parameter to another function?

description: Pass function as parameter to another function


code: MY_APP_LOG_DIRECTORY = "path/to/logs"

rawDescription: Django: get the path to the current django app


code:
sorted(sampleObjects, key=lambda obj: obj.value1)
sorted(sampleObjects, key=lambda obj: obj.value2)

rawDescription: How to sort a list of objects based on different object values in python?

description: Sort a list of objects based on different object values in python


code: "they're bill's friends from the UK".title()

rawDescription: How to capitalize the first letter of each word in a string (Python)?

description: Capitalize the first letter of each word in a string (Python)


code:
import sys
sys.stdout.write('stdout line 1')
sys.stderr.write('stderr line 2')

rawDescription: Python subprocess arbitrarily split output between files


code:
for choice in self.choices:
    value, label = choice[:2]
    try:
        other = choice[2]
    except IndexError:
        other = None
    yield (value, label, other, selected)

rawDescription: Loop with 3 or 2 items to unpack in Python


code:
df1['Red Amber Yellow White'.split()].plot(kind='bar')
# equivalently:  df1[['Red', 'Amber', 'Yellow', 'White']].plot(kind='bar')

rawDescription: PANDAS - Plotting specific rows and changing order of columns


code:
firstRun=True
def writeFile(number):
    global firstRun
    if firstRun:
        print('number')
        firstRun=False
    print(str(number))

for i in range(10):
    writeFile(i)

rawDescription: How to tell when a method is called for first time of many

description: Tell when a method is called for first time of many


code:
import re
my_regex = re.compile(r'@\S+')

rawDescription: In Python, how would you write a regex that matches the following?


code:
def zipp (a,b):
   return [[x,y] for x, y in zip(a, b)]
zipp(a, b)

rawDescription: Function python list (zip)

description: Function python list (zip)


rawDescription: Why does recursive sequence not work correctly?


code:
lst = ['a', 'b', 'c']
cplst = []
cplst.extend(lst)
cplst == lst

rawDescription: Why doesn't [].extend(list1) create an identical list to list1?


code:
commands = (['cmd1', 'arg1'], ['cmd2', 'arg2'], ...)
for path, command in izip(paths, commands):
      os.chdir(path)
      subprocess.call(command)

rawDescription: Applying different commands at different location


code:
import numpy as np
import seaborn
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

chisq = np.random.chisquare(4, 8)
chisq -= chisq.min()
chisq /= chisq.max()

cmap = ListedColormap(seaborn.color_palette("GnBu_d"))
errorbar_colors = cmap(chisq)

heights = np.random.randn(8)
sem = .4

for i, (height, color) in enumerate(zip(heights, errorbar_colors)):
    plt.plot([i, i], [height - sem, height + sem], c=color, lw=3)
plt.plot(heights, marker="o", ms=12, color=".3")

rawDescription: cmap to rgba in Matplotlib

description: Cmap to rgba in Matplotlib


code:
import IPython

import numpy as np
import pandas as pd

# numpy
np.set_printoptions(formatter={'float_kind': lambda x: '{:,}'.format(x).replace(",", "'"),
                          'int_kind': lambda x: '{:,}'.format(x).replace(",", "'")})

# pandas
class IntFormatter(pd.core.format.GenericArrayFormatter):
    pd.set_option("display.float_format", lambda x: "{:,}".format(x).replace(",", "'"))

    def _format_strings(self):
        formatter = self.formatter or (lambda x: ' {:,}'.format(x).replace(",", "'"))
        fmt_values = [formatter(x) for x in self.values]
        return fmt_values

pd.core.format.IntArrayFormatter = IntFormatter

# general
def thousands(arg, p, cycle):
    p.text("{:,}".format(arg).replace(",","'"))

frm = get_ipython().display_formatter.formatters['text/plain']
frm.for_type(int, thousands)
frm.for_type(float, thousands)

rawDescription: set thousands separators in iPython without string formatting

description: Set thousands separators in iPython without string formatting


code: sns.tsplot(sines, time=np.linspace(-15, 15, sines.shape[1]))

rawDescription: Seaborn tsplot change labels on x-axis

description: Seaborn tsplot change labels on x-axis


code:
Module
AugAssign
Subscript
Name
Load
Index
Name
Load
Store
Add
Subscript
Name
Load
Index
Tuple
Name
Load
Name
Load
Load
Load

rawDescription: Simple example of how to use ast.NodeVisitor?


code:
char = "\n"
char == "\n"
char is "\n"
a = char
a is char
id(a)
id(char)
id("\n")

rawDescription: String comparison: Actual newline is never recognized as "\n"


code:
a = ["Hi", "Sam", "How", 1, {'x': 123}, None]
a = ['Hello{}'.format(b) for b in a]
# ['HelloHi', 'HelloSam', 'HelloHow', 'Hello1', "Hello{'x': 123}", 'HelloNone']

rawDescription: python add string to the start of each element in array

description: Python add string to the start of each element in array


code:
import itertools

file1Input = [line.strip() for line in open('file1.txt').xreadlines()];
file2Input = [line.strip() for line in open('file2.txt').xreadlines()];

output = [x[0] + x[1] for x  in itertools.product(*[file1Input, file2Input])]
print(output)

rawDescription: Python concatenate recursively strings in files


code: other_function(name, phone, some_function("abcd")[0], age)

rawDescription: Pass one element of tuple as argument along with other arguments


code:
from collections import Counter

counted=Counter(iterable)

rawDescription: Dictionary that counts occurrences of its items


rawDescription: Python: calculate value for each pair of values in list


code:
naive_datetime = dt.datetime(*naive_timetuple[:6])
print(naive_datetime)
# 1969-12-31 19:00:00

localized_datetime = eastern.localize(naive_datetime)
print(localized_datetime)
# 1969-12-31 19:00:00-05:00

rawDescription: How to add two offset in python?

description: Add two offset in python


code:
def getMessage():
    while True:
        message = input('Enter your message: ')
        if message.isalpha():
            return message
        print("Invalid input, text must contain alphabetic characters only.")

rawDescription: Caesar Cipher validation

description: Caesar Cipher validation


code:
with pd.option_context('display.max_columns', None):
    display(data)

rawDescription: ipython notebook pandas max allowable columns

description: Ipython notebook pandas max allowable columns


code:
class A:
    username = None
    @classmethod
    def get_username(cls):
        if cls.username is None:
            try:
                uname = os.environ["USER"]
            except:
                print("Couldn't find a user name")
            else:
                cls.username = uname
        return cls.username

rawDescription: Python 3 static members

description: Python 3 static members


code: a = maximum ^ ((a ^ maximum) & -(a < maximum))

rawDescription: value <= maximum

description: Value <= maximum


code:
import datetime as dt

def date_parser(date):
    if date is None or date == "":
        return dt.datetime()
    else:
        return dt.datetime.strptime(date, '%d%b%Y')
...
pd.read_csv(read_file, parse_dates=parse_dates, date_parser=date_parser)

rawDescription: Combining files even if one is missing?

description: Combining files even if one is missing