code:
levels_dict = {4 :(sale4, cost1, cost2),
               5 :(sale5, cost2, cost3)}

rawDescription: Python: how to avoid writing numerous if/elifs in a function?


code: h = logging.handlers.SysLogHandler(address='/var/run/syslog', facility='local1')

rawDescription: How can I log from Python to syslog with either SysLogHandler or syslog on Mac OS X *and* Debian (7)

description: Log from Python to syslog with either SysLogHandler or syslog on Mac OS X *and* Debian (7)


rawDescription: Python-QDateEdit event

description: Python-QDateEdit event


code:
import StringIO
import sys
new_stdin = StringIO.StringIO(input_string)
sys.stdin = new_stdin
args = ["--key", "Date"]
CSVJSON(args).main()

rawDescription: csvkit & django a.k.a. using csvkit as modules instead of from command line

description: Csvkit & django a.k.a. using csvkit as modules instead of from command line


rawDescription: sorting list of objects in Python

description: Sorting list of objects in Python


rawDescription: Extract longest strings from sublist within list . Python


code: df = df.sort('Age')

rawDescription: Pandas - Create new dataframes based on ranked values in select columns


code:
import inspect
import ast

original_f = f

source = inspect.getsource(f)
tree = ast.parse(source)
# tree is a Module, with body consisting of 1 FunctionDef
# tree.body[0] is a FunctionDef, with body consisting of Exprs
tree.body[0].body.reverse()
# top level expressions will be reversed

# compile the modified syntax tree to a code object as a module and execute it
exec(compile(tree, '<unknown>', 'exec'))
# f will be overwritten because the function name stays the same

# now f will be equivalent to:
#   def f():
#       call_some_function_D()
#       if test:
#           call_some_function_B()
#           call_some_function_C()
#       call_some_function_A()

f_ = f
f = original_f

rawDescription: Executing a function in reverse in Python


code: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

rawDescription: python: convert year/month/day/hour/min/second to # seconds since Jan 1 1970

description: Python: convert year/month/day/hour/min/second to # seconds since Jan 1 1970


code: rectangles = (rect1, rect2, ...)

rawDescription: Creating a rect grid in Pygame

description: Creating a rect grid in Pygame


code:
MIDDLEWARE_CLASSES = (
    # whatever middleware you're already loading
    # note: your middleware MUST exist in a package that's part of the INSTALLED_APPS
    'yourproject.someapp.DomainCheckMiddleware'
)

rawDescription: Achieve different behaviour when accessing from other domain


code: "hello, %s.  Where is %s?" % ["John", "Mary"]

rawDescription: What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`


code:
source = dict()
output = []
for mapping in yourlist:
    if 'X' in mapping:
        source = mapping
    else:
        mapping.update(source)
        output.append(mapping)

rawDescription: Concatenating list of dictionaries

description: Concatenating list of dictionaries


code:
import foo
import baz
l = [1,2,3,4]

rawDescription: run python command line interpreter with imports loaded automatically

description: Run python command line interpreter with imports loaded automatically


rawDescription: Python : Reverse Order Of List

description: Python : Reverse Order Of List


code:
idx0s = np.concatenate(([0], np.searchsorted(idx1s, idx_1s[:-1])))
idx0s = idx1s[idx0s]

rawDescription: Python/Numpy - Fill gaps between non-consecutive points?


rawDescription: python: write input to file and save it

description: Python: write input to file and save it


rawDescription: Fastest way to sort list of dates when adding to the list


code:
cell = gtk.CellRendererText()
column = gtk.TreeViewColumn('column0', cell, text=0)
column.set_cell_data_func(cell, self.load_data)
self.list.append_column(column)

rawDescription: PyGTK how to "load-on-demand" data to TreeView


code:
import concurrent.futures

urls = ['http://example.com/foo',
        'http://example.com/bar']

with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
    result = b''.join(executor.map(download, urls))

with open('output_file', 'wb') as f:
    f.write(result)

rawDescription: how to download multiple file simultaneously and join them in python?

description: Download multiple file simultaneously and join them in python


code: from lyricCheck import help, check

rawDescription: Python Module Package with no methods

description: Python Module Package with no methods


code:
return [round(ride_time * cpm + ride_distance * cpmile, 1)
        for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]

rawDescription: How to get the result in single List?

description: Get the result in single List


code:
map(abs, entry[1][0])
map(abs, entry[1][1])

rawDescription: Exporting a modified list to CSV

description: Exporting a modified list to CSV


code:
from subprocess import check_output

out = check_output(["echo", "Test"], shell=True)

rawDescription: getting output of command in subprocess

description: Getting output of command in subprocess


code:
import hashlib
data = {'user': hashlib.sha256('Roland').hexdigest(), 'password' : hashlib.sha256('mysecretpassword').hexdigest(), 'amount': 273}
data

rawDescription: How do I store account information in python so that it can be accessed later?

description: Store account information in python so that it can be accessed later


code:
import numpy
numpy.linspace(10, 20, 5) # Start, stop (included), length
numpy.linspace(10, 20, 5, endpoint=False) # Makes stop not included
line(5, 10, 20).take(inf) # Length, start, stop (range-like)
line(5, 10, 20, finish=True).take(inf) # Include the "stop"

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
L = sch.linkage(d, method='complete')
sch.fcluster(L, 0.5*d.max(), 'distance')
L = sch.linkage(d, method='single')
sch.fcluster(L, 0.5*d.max(), 'distance')

rawDescription: How to get flat clustering corresponding to color clusters in the dendrogram created by scipy

description: Get flat clustering corresponding to color clusters in the dendrogram created by scipy


code:
import csv
from collections import defaultdict
reader = csv.DictReader(open('test.csv', newline=''))
cities = defaultdict(int)
for row in reader:
    cities[row["CITY"]] += int(row["AMOUNT"])

writer = csv.writer(open('out.csv', 'w', newline = ''))
writer.writerow(["CITY", "AMOUNT"])
writer.writerows([city, cities[city]] for city in cities)

rawDescription: Parse CSV file and aggregate the values

description: Parse CSV file and aggregate the values


code:
for i, lst in enumerate(lsts, 1):
    if lst:
        with open(os.path.join(dirpath,"newfile{}.txt".format(i)), 'w') as f:
            for elem in lst:
                f.write(elem)

rawDescription: dealing with multiple lists

description: Dealing with multiple lists


rawDescription: Custom arrangement of NumPy array elements


code:
def getline():
    """This is a docstring"""
    return sys.stdin.readline()

rawDescription: How do I add text describing the code into a Python source file?

description: Add text describing the code into a Python source file


code: df1 = df1.pivot_table(index=['Date','PersonID'], values='CustomerID', aggfunc=len)

rawDescription: Avoiding double counting in pandas merge


code:
import netifaces as ni
ni.interfaces()
ni.ifaddresses('eth0')

ni.ifaddresses.__doc__
# for the IPv4 address of eth0
ni.ifaddresses('eth0')[2][0]['addr']

rawDescription: get MAC address for mobile broadband modem in python

description: Get MAC address for mobile broadband modem in python


code:
if not sheets.has_key(data['ATR']):
    sheets[data['ATR']] = wb.add_worksheet(data['ATR'])
ws = sheets[data['ATR']]

rawDescription: Switching between worksheets

description: Switching between worksheets


code: output = sorted(input, key=lambda l: len(l.split(None, 1)[0]), reverse=True)

rawDescription: List ordering in Python. Very simple

description: List ordering in Python. Very simple


rawDescription: parse special json format with python

description: Parse special json format with python


code:
from collections import Counter

before = Counter()
after = Counter()

for line in open("log"):
    x, key, y = line.split()
    if key == "xyz":
        # increment counts of x and y in their positions
        before[x] += 1
        after[y] += 1

# print some statistics
print("Before xyz we found:")
for key, val in before.iteritems():
    print("    %s %s" % (key, val))
# do the same for after

rawDescription: Python - Extracting Text From a File

description: Python - Extracting Text From a File


code:
def add_contact():
   name = raw_input("Please enter a name:")
   number = raw_input("Please enter a number:")
   phonebook[name].append(number)

rawDescription: How to add a another value to a key in python

description: Add a another value to a key in python


code:
@gen.coroutine
def get_all_users(self):
    users = yield User.objects.find_all()
    raise gen.Return(users)

rawDescription: Get result from MotorEngine async query

description: Get result from MotorEngine async query


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

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


code:
def xgroup(items):
    L = len(items)
    for i in range(L-1):
        for j in range(1, L):
            temp = list(items)
            a = temp.pop(j)
            b = temp.pop(i)
            temp.insert(0, a*b)
            yield temp
            for x in xgroup(temp):
                yield x

def product_combos(max_entry, n_boxes, items):
    r = set()
    if len(items)<=n_boxes:
        r.add(tuple(items))
    for i in xgroup(items):
        x = i[:]
        x.sort()
        if x[-1]<=max_entry and len(x)<=n_boxes:
            r.add(tuple(x))
    r = [list(i) for i in r]
    r.sort()
    for i in r:
        while len(i)<n_boxes:
            i.insert(0, 1)
    return r

rawDescription: Find all possible factors in KenKen puzzle 'multiply' domain


code:
df2.columns = ['panel_mm_id']

df = (pd.merge(df1, df2, on='panel_mm_id'))
print (df)

rawDescription: Find some value in column

description: Find some value in column


code:
frac = appr.apply( lambda x: x / total_appr ).shift( 1 ).fillna( 0 ).cumsum( )
df[ 'frac' ] = [ frac[ row[ 'name' ] ][ row[ 'date' ] ] for idx, row in df.iterrows( ) ]

rawDescription: Calculating previous chance figure for use in chi square test


code:
import pprint
filename='/tmp/image.jpg'
metadata = pyexiv2.ImageMetadata(filename)
metadata.read()
userdata=json.loads(metadata['Exif.Photo.UserComment'].value)
pprint.pprint(userdata)

rawDescription: Writing complex custom metadata on images through python


code:
...
result = gevent.joinall(threads)
return (t.value for t in threads if t.u).next()

rawDescription: Comparing results of Gevent threads

description: Comparing results of Gevent threads


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

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


code: self.data_source.ix[:, indices[first_n:cur_n + 1], :]

rawDescription: Pandas Panel Slicing - Improving Performance


code: x = range(10+1)  # gives a generator that will make a list

rawDescription: Python Sequence of Numbers

description: Python Sequence of Numbers


code:
def barInitial():
    first_name, last_name = 'Bob', 'Jones'
    return first_name, last_name

def fooInitial():
    return barInitial()[0]

rawDescription: Python Function Return

description: Python Function Return


code:
zipped = zip(J48, useAllAttributes7nn)
x = (sum( a < b for (a, b) in zipped ), sum( a > b for (a, b) in zipped ))

rawDescription: what is a pythonic way to get the number of times list1[i] < list2[i] and vise versa

description: What is a pythonic way to get the number of times list1[i] < list2[i] and vise versa


rawDescription: Pandas column values to columns?

description: Pandas column values to columns


code:
satisfiable(x & y)
satisfiable(~(x | y))
satisfiable(x & y & z)

rawDescription: Solving Symbolic Boolean variables in Python


code:
from datetime import datetime
strs = "2012-08-22"
datetime.strptime(strs,'%Y-%m-%d')

rawDescription: Refactor Python Code

description: Refactor Python Code


code:
import numpy as np
Rip = np.array( [ i if j != 0 else 0 for i,j in zip(Ri,Rj) ] )
Rjp = np.array( [ j if i != 0 else 0 for i,j in zip(Ri,Rj) ] )

rawDescription: Special cosine between scipy sparse matrices


code:
from sqlalchemy import event

class Table(Model):
    id = Column(Integer, primary_key=True)
    revenue = Column(Integer)
    loss = Column(Integer)
    profit = Column(Integer)

@event.listens_for(Table.revenue, 'set')
def revenue_listener(target, value, oldvalue, initiator):
    # update profit when revenue change
    target.profit = value - (target.loss or 0)

@event.listens_for(Table.loss, 'set')
def loss_listener(target, value, oldvalue, initiator):
    # update profit when loss change
    target.profit = (target.revenue or 0) - value

rawDescription: Compare difference between two columns in SQLAlchemy ORM


code:
def main():
    if condition:
        raise StopIteration
    else:
        return value

while True:
    main()

rawDescription: High-level function returning low-level function in python?


code: lambda x: op(x, n)

rawDescription: How to transform a arithmetic expression to a Python arithmetic function?

description: Transform a arithmetic expression to a Python arithmetic function


code:
foo="This 23 is not a string with 32 numbers"
[x for x in foo.split() if x.isdigit()]

rawDescription: Regex to get digits in a certain format

description: Regex to get digits in a certain format


rawDescription: Scrape text after every <br> - BeautifulSoap


rawDescription: PIL and numpy

description: PIL and numpy


code:
import os, shutil

def move_drm_files(music_folder):
    all_songs = []
    good_filetypes = ['mp3', 'm4a', 'ogg', 'flv', 'wma']
    for root, dirs, files in os.walk(music_folder):
        for name in files:
    	    full_name = os.path.join(root, name)
    	    all_songs.append(full_name)
    os.mkdir('/drm_music')
    for song in all_songs:
    	if song[-3:] not in good_filetypes:
    		shutil.move(song, '/drm_music')

rawDescription: Sorting music

description: Sorting music


code: print("You can get ", wrong, "% back with text corrections", sep='')

rawDescription: Invalid syntax with if

description: Invalid syntax with if


code:
df['ids'] = df['ids'].apply(lambda x: np.unique(x))
df

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

description: Merge two list columns when merging DataFrames


code:
td = datetime.timedelta(hours=1)
pd.DateOffset(seconds=td.total_seconds())
to_offset(pd.DateOffset(seconds=td.total_seconds()))

rawDescription: Build a Pandas pd.tseries.offsets from timedelta


code:
import numpy as np
# split it in to a list of values and get rid of the newline
a = open('k.txt','r').read().replace('\n','').split(',')
np.unique(a) # returns unique values and sorts it for you :)

rawDescription: not all duplicates being removed

description: Not all duplicates being removed


rawDescription: How to view all elements of a Python Dictionary for Just One Value of one of the Elements in a Tuple Key

description: View all elements of a Python Dictionary for Just One Value of one of the Elements in a Tuple Key


code:
import api.debug
api.debug.DEBUG = False
import conf

rawDescription: How to divide Python code to modules with shared code?

description: Divide Python code to modules with shared code


rawDescription: python pandas time series select day of year

description: Python pandas time series select day of year


code:
s = sympy.solve(n*9**5 - 10**n-1, n)
import sympy.mpmath
# Replace -1 with any integer. -1 gives the other real solution, the one you want
lambdify([], s, [{'LambertW': lambda x: sympy.mpmath.lambertw(x, -1)}, "mpmath"])()

rawDescription: Why is SymPy's solver returning only one, trivial solution?


rawDescription: pandas get last value of column x when column y is equal to z

description: Pandas get last value of column x when column y is equal to z


code:
test = {"x":"y"}
test2 = test
test["x"] = "foo"
test2

rawDescription: Dictionaries: added value to one key also gets added to other keys


code:
a
a_unq, a_inv = np.unique(a, return_inverse=True)
a_cnt = np.bincount(a_inv)
np.cumsum(a_unq * a_cnt)[a_inv]

rawDescription: Conditional numpy.cumsum?

description: Conditional numpy.cumsum


code: sorted(a, key=lambda word: [alphabet.index(c) for c in word[0]])

rawDescription: Sorting string values according to a custom alphabet in Python


code: np.delete(X, i, axis=1)

rawDescription: How can get a part of a 2D array?

description: How can get a part of a 2D array


rawDescription: Matplotlib Image fit to equation?

description: Matplotlib Image fit to equation


code:
from multiprocessing import *
import time

def main():
    processes = 10
    array, loops = list(range(1000)), 1000
    shared = Array('I', processes)
    p_array = []
    for index in range(processes):
        p = Process(target=sample, args=(array, loops, shared, index))
        p.start()
        p_array.append(p)
    while True:
        less_than_1000 = [p for p in enumerate(shared[:]) if p[1] < 1000]
        if less_than_1000:
            print(less_than_1000)
            time.sleep(0.001)
        else:
            break
    print('No process in less than 1000')
    for p in p_array:
        p.join()
    print(shared[:])

def sample(array, loops, p_array, index):
    time.sleep(1)
    for number in range(loops):
        time.sleep(0.001)
        p_array[index] = number * 10
    print('Sample is done')

if __name__ == '__main__':
    main()

rawDescription: Return value while executing paralel processes with python


code: df.replace({True: "X", False: ""})

rawDescription: Not able to use 'if x in list' using pandas


code:
import csv
import functools
import io
import tempfile
import os
import sys

filename = 'RawDataeDataTest.csv'

if sys.version_info >= (3, 0):
    open_args = lambda mode: {'encoding': 'utf-8', 'mode': mode}
else:
    open_args = lambda mode: {'mode': mode + 'b'}

with io.open(filename, **open_args('r')) as csvf:
    data = list(csv.reader(csvf))
data.sort(key=lambda row: (row[3], row[7]))

with tempfile.NamedTemporaryFile(dir=os.path.dirname(filename), delete=False,
                                 **open_args('w')) as of:
    try:
        csv.writer(of).writerows(data)
        of.flush()
    except:
        os.unlink(of.name)
        raise

    try:
        os.replace(of.name, filename)
    except AttributeError:  # Python < 3.3
        if os.name == 'nt':
            os.remove(filename)
        os.rename(of.name, filename)

rawDescription: Sorting data by class for each date

description: Sorting data by class for each date


rawDescription: Pandas - Groupby and create new DataFrame?


rawDescription: Scraping DATA from Javascript using SCRAPY and PYTHON


code:
s = set(range(0, 100))
last5 = []
def get_next_number():
    reduced_list = list(s - set(last5))
    i = randint(0, len(reduced_list) - 1)
    last5.append(reduced_list[i])
    if len(last5) > 5:
        last5.pop(0)
    return reduced_list[i]

rawDescription: Generate random numbers without using the last n values in Python


code:
import re
m = re.search(r'"objectId":"([^"]+)"', datastring, re.IGNORECASE)
if m:
    objid = m.group(1)

rawDescription: search string in text file and capture following n characters

description: Search string in text file and capture following n characters


code:
def viable(self, north_south, east_west):
    i = north_south.index(self)
    j = east_west.index(self)

    south = north_south[(i - 1) % len(north_south)]
    north = north_south[(i + 1) % len(north_south)]
    west = east_west[(j - 1) % len(east_west)]
    east = east_west[(j + 1) % len(east_west)]

    return east, west, north, south

rawDescription: Binding list indices with modulus, want to make a circular list


code:
x = ElmentTree(file='testdata.xml')
allcases = x12.findall(".//testcase")
cases = [c for c in allcases if c.get('classname') == 'TestOne' and c.get('name') == 'VHDL_BUILD_Passthrough']

rawDescription: Find occurrence using multiple attributes in ElementTree/Python


code: mask = ' '.join(('_' for i in range(len(secretWord)))) + '\n' + ' '.join((str(i) for i in range(len(secretWord))))

rawDescription: displaying numbers underneath a mask in python

description: Displaying numbers underneath a mask in python


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--vhdr", dest="vhdr_file")
parser.add_argument("--bin", dest="bin_file")
args = parser.parse_args()
print(args)

rawDescription: Command line argument processing

description: Command line argument processing


rawDescription: Selecting some elements based on conditions


code: handle2file = {}

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code:
from setuptools import setup, find_packages
setup(name='nstest.foo', packages=find_packages())

rawDescription: Import local testing version of a Python namespace package


code:
def readFromFile(fileName):
    f = open(fileName, "r")
    data = f.read()
    f.close()
    return data

print(readFromFile("test.txt"))

rawDescription: Save variable a user input

description: Save variable a user input


code: {k:dict(v) for k,v in d.iteritems()}

rawDescription: Building a directed multigraph (Python)

description: Building a directed multigraph (Python)


code:
lst = [[5, 44, 73, 23] , [7, 21, 99], [1, 32, 100]]
list(filter(lambda p: p is not None, reduce(lambda x, y: x + y, map(None, *lst))))

rawDescription: How do do this list manipulation in Python? This is tricky


code:
final = []
for key in sorted(image_dict.keys()):
    final.append(image_dict[key])

rawDescription: Bin photos by time taken

description: Bin photos by time taken


code:
name = "Python 2.7.6 Shell" #just an example of a window I had open at the time
w = win32ui.FindWindow( None, name )
t1 = time.time()
count = 0
while count < 1000:
    dc = w.GetWindowDC()
    dc.GetPixel (60,20)
    dc.DeleteDC()
    count +=1
t2 = time.time()
tf = t2-t1
it_per_sec = int(count/tf)
print (str(it_per_sec) + " iterations per second")

rawDescription: Most efficient/quickest way to parse pixel data with Python?


code: flat_list = list({'d': d, 'o': o} for d in list1 for o in d['list2'])

rawDescription: How can i use the forloop counter in django without resetting

description: Use the forloop counter in django without resetting


code:
def maximum(x, y, z):
    return max([x, y, z])

rawDescription: Finding the middle of three numbers

description: Finding the middle of three numbers


code:
import numpy as np
from scipy.spatial.distance import cdist

A = np.random.random((1000, 2))
B = np.random.random((100, 2))

D = cdist(A, B, metric='euclidean')
print(D.shape) # (1000, 100)

weights = D.sum(1)
print(weights.shape)  # (1000,)

rawDescription: Numpy - Speed up iteration comparison?

description: Numpy - Speed up iteration comparison


code: dispatch("meth2", 1, 3)

rawDescription: python: dispatch method with string input

description: Python: dispatch method with string input


code:
def make_statfunc(f):
    return lambda: os.stat(f)

for f in files:
    # pass the current f to another function
    funcs.append(make_statfunc(f))

rawDescription: Python closure not working as expected

description: Python closure not working as expected


code:
graph = GraphAPI(oauth_access_token)
graph.post(
    path = 'me/photos',
    source = open('parrot.jpg')
)

rawDescription: Accessing Facebook API Data with Python

description: Accessing Facebook API Data with Python


rawDescription: Convert one dimension list to two diminsions with specific delimiters


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

description: Split string from column to create long format dataframe


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Outputting list to a "matrix" type format in python


code:
t = np.array([datetime.strptime(d.split(None)[0], "%d/%m/%Y")
for d in t],dtype='datetime64[us]').astype('datetime64[D]')

rawDescription: converting text to datetime64 in numpy

description: Converting text to datetime64 in numpy


code:
Example(int, int,
    doSomething=lambda a, b: (a + b * 2) > 5,
    doSomethingElse=lambda a, b: a - b * 4
)

rawDescription: From Haskell to functional Python

description: From Haskell to functional Python


code:
def change_graph_representation(graph):
    reverse_graph = {}
    for node, links in graph.items():
        for link in links:
            if link not in reverse_graph:
                reverse_graph[link] = set()
            reverse_graph[link].add(node)

    result = {}
    for node,links in graph.items():
        adj = set()
        for link in links:
            adj |= reverse_graph[link]
        adj -= {node}
        result[node] = adj
    return result

rawDescription: Python: How to find more than one pathway in a recursive loop when multiple child nodes refers back to the parent?


code: scheme, netloc, path, _, _, _ = parsed_url

rawDescription: Expand only some tuple elements to variable list


code:
import mod1
z = mod1.my_generator()
z.__doc__
z.gi_frame.f_globals[z.__name__]
z.gi_frame.f_globals[z.__name__] is mod1.my_generator
z.gi_frame.f_globals[z.__name__].__doc__

rawDescription: how to get a reference to the function generator that created an iterator?

description: Get a reference to the function generator that created an iterator


code:
result_list = [(False, True, False), (True, False, False), (False, False, False), (True, True, False)]
zip(*result_list)
tuple(any(grouped) for grouped in zip(*result_list))

rawDescription: Most pythonic way to 'or' tuples?

description: Most pythonic way to 'or' tuples


code:
for length in xrange(len(args)):
    temp = temp.replace("%length","arg[length]")

rawDescription: Replace % followed by a number in a string


code:
class Building(Base):
    __tablename__ = 'building'
    id = Column(Integer, primary_key=True)
    building_type = Column(String(32), nullable=False)
    x = Column(Float, nullable=False)
    y = Column(Float, nullable=False)
    __mapper_args__ = {'polymorphic_on': building_type}

class Commercial(Building):
    __mapper_args__ = {'polymorphic_identity': 'commercial'}
    business = Column(String(50))

class Residential(Building):
    __mapper_args__ = {'polymorphic_identity': 'residential'}
    num_residents = Column(Integer)

rawDescription: SQLAlchemy Inheritance

description: SQLAlchemy Inheritance


code: value = [ ",".join(map(str,i)) for i in value ]

rawDescription: Best way to convert value in nested list to string

description: Convert value in nested list to string


rawDescription: Python, simultaneous pseudo-inversion of many 3x3, singular, symmetric, matrices


code:
prop = prop.deleter(deleter)
prop.fget is getter
prop.fset is setter
prop.fdel is deleter

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


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


code: denormalise(df1, 'wares')

rawDescription: Denormalise the data using Pandas

description: Denormalise the data using Pandas


code:
M
n
out

rawDescription: Count occurences of elements of a matrix fast


code: second_max = sorted(set(L))[-2]

rawDescription: Find second maximum number in a list

description: Find second maximum number in a list


code:
lst = range(10)
all( type(i) is int for i in lst )
lst.append('steve')
all( type(i) is int for i in lst )

rawDescription: if all in list == something

description: If all in list == something


code: finallist = [item.replace("\\n", "\n").strip() for item in newlist]

rawDescription: lists and sublists

description: Lists and sublists


code:
with sqlite3.connect(':memory:') as conn:
    curs = conn.cursor()
    curs.row_factory = sqlite3.Row
    try:
        results = curs.execute( """SELECT mycol
                                     FROM mytable
                                    WHERE somecol = ?;""",
                               (some_var,) ).fetchall()
    # you would put your exception-handling code here
    finally:
        curs.close()

rawDescription: Loading SQLite3 values into Python variables


code:
def count_vowels(string):
    return sum(1 for c in string if c.lower() in "aeiou")

rawDescription: Python While loops with tuples

description: Python While loops with tuples


rawDescription: Graphing values generated from loop

description: Graphing values generated from loop


code:
def do_all(iterable, func):
    for i in iter(iterable):
       func(i)

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


code:
NAMES = 'foo bar baz bat'.split()

def get_query_results(*filters):
    res = models.Item.query
    for name, filt in zip(NAMES, filters):
        if filt is not None:
            d = {name: filt}
            res = res.filter(**d)
    return res.all()

rawDescription: sqlalchemy - elegant way to deal with several optional filters?

description: Sqlalchemy - elegant way to deal with several optional filters


code:
import timeit
setup = """
import numpy as np
#PARTS is my dictionary
#the .partposit is the attribute that is an array of shape (50000, 12)

class A:
    def __init__(self, values):
        self.partposit = values

PARTS = dict((index, A(np.zeros((50000, 12)))) for index in xrange(163))
ks = sorted(PARTS.keys())
"""
stack = """
p1 = PARTS[ks[0]].partposit
for k in ks[1:]:
    p1 = np.dstack((p1, PARTS[k].partposit))
"""
timeit.Timer(stack, setup).timeit(number = 1)

rawDescription: efficiently dstack arrays from dictionary python

description: Efficiently dstack arrays from dictionary python


code: dfs

rawDescription: How to split a dataframe column into multiple columns

description: Split a dataframe column into multiple columns


code: issubclass(type(obj2), Item)

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


code: drugInfo.rename(columns = {list(drugInfo)[1]: 'col_1_new_name'}, inplace = True)

rawDescription: Pandas: Rename single DataFrame column without knowing column name


code:
if itemnum == -1:
    break

rawDescription: Nested while loop with trailer values

description: Nested while loop with trailer values


code:
def residuals(params, B, C, H):
    UV = params
    diff = model(B, C, UV) - H.view(float)
    return diff.flatten()

rawDescription: Constraining the least squares fitting in python


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
np.random.seed(2015)

N = 16
df = pd.DataFrame({'Opportunities': np.random.randint(0, 30, size=N),
               'Percentage': np.random.randint(0, 100, size=N)},
index=pd.date_range('2015-3-15', periods=N, freq='B').date)
fig, ax = plt.subplots()
ax2 = ax.twinx()
df[['Opportunities']].plot(kind='bar', stacked=False, title='get_title',
                           color='grey', ax=ax2, grid=False)

ax.plot(ax.get_xticks(), df[['Percentage']].values, linestyle='-', marker='o',
        color='k', linewidth=1.0, label='percentage')

lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='best')

ax.set_zorder(ax2.get_zorder()+1) # put ax in front of ax2
ax.patch.set_visible(False) # hide the 'canvas'
ax2.patch.set_visible(True) # show the 'canvas'

fig.autofmt_xdate()
plt.show()

rawDescription: Multi-Axis Graph with Line on top. Matplotlib


rawDescription: Emulating Excel's "scatter with smooth curve" spline function in Matplotlib for 3 points


rawDescription: Can someone explain to me what python is doing here?


code: colors = plt.cm.Spectral(np.linspace(0, 1, 10))

rawDescription: pyplot equivalent for pl.cm.Spectral in matplotlib

description: Pyplot equivalent for pl.cm.Spectral in matplotlib


code:
dic = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi", "phoenix":"arizona"}
{dic[k]:k for k in sorted(dic)}

rawDescription: Swapping contents of the dictionary

description: Swapping contents of the dictionary


code:
lname = 'Doe'
Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])

rawDescription: Is it possible to use raw SQL with python's django web framework?


code: pattern = re.compile(regex_1, re.DOTALL)

rawDescription: Regex to capture the c langage comment use python


code:
def aligned_array(alignment, dtype, n):
    mask = alignment - 1
    if alignment == 0 or alignment & mask != 0:
        raise ValueError('alignment is not a power of 2')
    size = n * ctypes.sizeof(dtype) + mask
    buf = (ctypes.c_char * size)()
    misalignment = ctypes.addressof(buf) & mask
    if misalignment:
        offset = alignment - misalignment
    else:
        offset = 0
    return (dtype * n).from_buffer(buf, offset)

rawDescription: Python ctypes align data structure

description: Python ctypes align data structure


rawDescription: Parse directory path to a variable in python


code: new_a = make_subtract(a, a(100))

rawDescription: Adding a constant to a closure expression


code:
import Tkinter as tk

def analyze(event=None):
    content = entry_contents.get()
    if content == "":
        entry_contents.set("default")

lord = tk.Tk()

entry_contents = tk.StringVar()
aEntry = tk.Entry(lord, textvariable=entry_contents)
aEntry.grid()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aEntry.bind("<FocusOut>", analyze)

lord.mainloop()

rawDescription: Inserting a default value into tkinter Entry stops validation


code:
class MyClass:
  def GET(self, arg1, arg2):
    ...

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

description: Call a class's method in python


code:
program_top = str(315 + 37.5 * idx)
program_top = program_top[:-2] if program_top.endswith(".0") else program_top

rawDescription: Replace the string

description: Replace the string


code: self.listCtrl = EditableListCtrl(my_panel1, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_VRULES, size=(1145,285))

rawDescription: WxPython ListCtrl index 0 item non editable


code:
# custom StaticBox class
class MyStaticBox(wx.StaticBox):
  def __init__(self, *args, **kwargs):
    super(MyStaticBox, self).__init__(*args, **kwargs)
    self.Bind(wx.EVT_PAINT, self.OnPaint)

  def OnPaint(self, event):
    # do what you want here
    width, height = self.GetSize()
    dc = wx.PaintDC(self)
    dc.Clear()
    dc.SetPen(wx.Pen('#4285F4'))
    dc.DrawLine(0, 0, width, height)
    dc.DrawLine(width, 0, 0, height)
    # after you finished, call the StaticBox OnPaint
    super(MyStaticBox, self).OnPaint(event)

rawDescription: wx.Python: How can I draw some lines into wx.staticbox

description: Wx.Python: How can I draw some lines into wx.staticbox


code:
#someutils.py

class NullHandler(logging.Handler):
    def emit(self, record):
        pass

null_handler = NullHandler()

rawDescription: Elegant setup of Python logging in Django


code:
stocks = {}
stocks['AIG.Status'] = 'Active'
stocks['AIG.Historical Price'] = '30,31,35'
stocks['AIG.Rank'] = '3'
stocks['AIG.Symbol N'] = 'AIG'
stocks['AIG.Price'] = '$30.5'

rawDescription: What is the correct way to store data N with associated properties if I've 100s of N to track?


code:
def xinput(callback):
    text = ''

    for c in uinput():
        if   is_printable(c): text += c
        elif is_backspace(c): text = text[:-1]
        elif is_interrupt(c): break

        callback(text)

    return text

rawDescription: Python, "filtered" line editing, read stdin by char with no echo


code:
labeled_lines = {label: [] for label in SHEETS}
with open('userdata.log','r',encoding = 'utf-8') as my_file:
    for line in my_file:
        for label in SHEETS:
            if label in line:
                labeled_lines[label].append(line)
                break
        else:
            # else on a loop means "if the loop didn't end with a break."
            raise SomeAppropriateException
for label in SHEETS:
    for lines in labeled_lines[label]:
        print(line)

rawDescription: Fixing Nested For Loops

description: Fixing Nested For Loops


code:
import random
import string

def generate_key(length):
    ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

rawDescription: Whats the simplest and safest method to generate a API KEY and SECRET in Python


code:
import csv

SEARCH_PHRASES = "keywords.csv"
SEARCH_INTO    = "descriptions.csv"
RESULTS        = "results.txt"

# get search phrases, build WordTree
with open(SEARCH_PHRASES) as inf:
    wt = WordTree(*(phrase for _,phrase in csv.reader(inf)))

with open(SEARCH_INTO) as inf, open(RESULTS, "w") as outf:
    # bound methods (save some look-ups)
    find_phrases = wt.parallel_search
    fmt          = "{}${}${}\n".format
    write        = outf.write
    # sentences to search
    for id,sentence in csv.reader(inf):
        # search phrases found
        for found in find_phrases(sentence):
            # store each result
            write(fmt(id, found, sentence))

rawDescription: Suggestion required - Python code performance improvement


code:
class Player(object):
     MAX_HEALTH = 100

     def __init__(self):
         # players start out with maximum health
         self.health = self.MAX_HEALTH

     # other things players track and can do

     @property
     def health(self):
         return self._health

     @health.setter
     def health(self, new_health):
         # limit health to MAX_HEALTH at most
         self._health = min(new_health, self.MAX_HEALTH)

rawDescription: Stuck on a simple if statement Python 3

description: Stuck on a simple if statement Python 3


code: np.vstack((a, newrow1, newrow2))

rawDescription: Reshaping Arrays in Numpy with variables


rawDescription: Python list of (node_id, parent_node_id) to JSON


code:
def foo():
    """This function does absolutely nothing"""
    pass

rawDescription: String literal with triple quotes in function definitions


code:
B = [0] * len(A)
for i, v in enumerate(A):
    B[v] = i

rawDescription: Swapping indices with values in a Python list?


code:
import csv

myfile = open('result.csv', 'w', newline='')
writer = csv.writer(myfile)
writer.writerow(lines_you_want)

rawDescription: Python filtering text

description: Python filtering text


rawDescription: How to enumerate a range of numbers starting at 1

description: Enumerate a range of numbers starting at 1


code:
angle_var = T.dscalar('angle_var')
a    = T.deg2rad(angle_var)
cosa = T.cos(a)
sina = T.sin(a)

R = theano.shared(np.identity(4))
R = T.set_subtensor(R[1,1],  cosa)
R = T.set_subtensor(R[1,2], -sina)
R = T.set_subtensor(R[2,1],  sina)
R = T.set_subtensor(R[2,2],  cosa)

rotate_x_axis_theano = theano.function([angle_var], R)

rawDescription: How to assign values elementwise to theano matrix ? Difference between Numpy and Theano?

description: Assign values elementwise to theano matrix ? Difference between Numpy and Theano


code: values = {field: value for field, value in information.items()}

rawDescription: Sqlite thinks I lack bindings

description: Sqlite thinks I lack bindings


code:
import scipy.sparse as sp
vect = CountVectorizer(ngram_range=(1, 3))
train = sp.hstack(sample.apply(lambda col: vect.fit_transform(col)))

rawDescription: How to vectorize a data frame with several text columns in scikit learn without losing track of the origin columns

description: Vectorize a data frame with several text columns in scikit learn without losing track of the origin columns


code:
a = ['Android',
'Android.Browser',
'Android.Browser.Url',
'Android.Messaging',
'Futureshop',
'Futureshop.Filter',
'Futureshop.Filter.Hello',
'Futureshop.Test',
'Test',
'Test.Hello']

rawDescription: How to find strings and put them in a list only once in python?

description: Find strings and put them in a list only once in python


code:
line
line.split()

rawDescription: Dividing a string by type of data inside each line of file in python


rawDescription: Python 2.6.1 (OS X 10.6.8) re.sub() underscore behavior in groups?


code:
# build initial structure with English labels
fields = [f.copy() for f in per_language['english']]
for field in fields:
    field['label'] = {'english': field['label']}
    if field['choices'] is not None:
        field['choices'] = [[id, {'english': label}] for id, label in field['choices']]

# copy in the translated labels
for language, language_fields in per_language.iteritems():
    if language == 'english': continue
    # assumption: fields are always listed in the same order
    for field, language_field in zip(fields, language_fields):
        field['label'][language] = language_field['label']
        if field['choices'] is not None:
            for (id, choice_labels), (_, language_label) in zip(field['choices'], language_field['choices']):
                choice_labels[language] = language_label

rawDescription: Merging dictionary values inPython

description: Merging dictionary values inPython


code:
c = Contact()
c.contactName = 'xxx'
c.channel = [ '1', '2' ]
c.channelCode = [ChannelCodeType.TELEPHONE, ChannelCodeType.FAX]

rawDescription: XmlAttribute for an unbounded primitive type


code:
l = ['string1', 'string2', ]
dictified_list = dict(zip(l, range(0, len(l))))
redirect.returnkeys(dictified_list)

rawDescription: Assign array to key dictionary in python


code:
# Modify this as needed
country_matchers = {
    'Norway': ['Nor', 'Norv'],
    'Sweden': ['S', 'Swed'],
}

def get_country(s):
    """
    Run the passed string s against "matchers" for each country
    Return the first matched country
    """
    for country, matchers in country_matchers.items():
        for matcher in matchers:
            if matcher in s:
                return country

rawDescription: Find key from value for Pandas Series

description: Find key from value for Pandas Series


code:
tree = "I"
for i in range(12):
    print((tree*(2*i)).rjust(12 + i))

rawDescription: Mirroring something to another side in Python


code:
from django.conf import settings

@register.filter
def default_image(image, default_file):
    if image.storage.exists(image.name):
        return image.url
    return settings.STATIC_URL + default_file

rawDescription: django templates upload file - how to handle a non-existant physical file

description: Django templates upload file - how to handle a non-existant physical file


rawDescription: Unzipp recursively even when the zip file has no folders


code:
from collections import Counter

Deca_dict = {
    "1": "2_506",
    "2": "2_506",
    "3": "2_506",
    "4": "2_600",
    "5": "1_650",
    "6": "2_600"
}

decaAdd_occurrences = {k: (int(k.split('_')[0]), v) for k,v in
                                Counter(Deca_dict.values()).items()}

for key, value in Deca_dict.items():
    num, cnt = decaAdd_occurrences[value]
    if cnt > 1:
        route = value.split('_')[1]
        next_num = num + 1
        Deca_dict[key] = '{}_{}'.format(next_num, route)
        decaAdd_occurrences[value] = next_num, cnt-1  # update values

rawDescription: Incrementing Python Dictionary Value based on a Counter


code: filter(lambda x: x not in l2, l1)

rawDescription: Subtract and add two lists without changing their order in Python


code:
def double(filename):
    seen = set()
    with open(filename, 'r') as infile:
        for line in l:
            for word in line.split():
                if word in seen:
                     return True
                seen.add(word)
    return False

rawDescription: How to determine if word in string is a double word?

description: Determine if word in string is a double word


code:
html = requests.get('http://example.com/').text
html_q = PyQuery(html)
image_url = html_q('img.my_image_class').attr('src')

rawDescription: how to grab a web image which has a dynamic src ID in python

description: Grab a web image which has a dynamic src ID in python


code:
l = [3, 30, 34, 5, 9]
sorted(l, cmp=cmp_values)

rawDescription: python string compare issue in a list

description: Python string compare issue in a list


code: value = info.findNext("b") or "Oompa Loompa"

rawDescription: Compressing `x if x else y` statement in Python


code:
from collections import defaultdict

dct = defaultdict(list)

dct['word1'].append(23)
dct['word2'].append(12)
dct['word1'].append(7)
dct['word2'].append(2)

rawDescription: How to insert duplicated values in dictionary?

description: Insert duplicated values in dictionary


code:
raw_data, _, _ = line.partition("#")
data= raw_data.strip()
if len(data) == 0:
    continue # or whatever, the data part of the line is empty
# you have data

rawDescription: In Python: how do I say: if line.partition('#' or 'tab') ... do something


code: lfunction = make_proxy(item[0])

rawDescription: Can I restore a function whose closure contains cycles in Python?

description: Restore a function whose closure contains cycles in Python


code: ondelete='CASCADE'

rawDescription: How to do a paged query with empty collections in SQLAlchemy?

description: Do a paged query with empty collections in SQLAlchemy


code:
import requests, re, math, pprint

def scrape_results(root):
    links = []
    r = requests.get(root)

    mat = re.search(r'We have (\d+) apartments for rent', r.text)
    num_results = int(mat.group(1))                     # 182 at the moment
    num_pages = int(math.ceil(num_results/20.0))        # ceil(182/20) => 10

    # Construct links for pages 1-10
    for i in range(num_pages):
        links.append("%s?page=%d" % (root, (i+1)))

    return links

pprint.pprint(scrape_results(root))

rawDescription: Get list of all paginated URL's from links in txt file in python requests


code:
timeit.timeit("reduce(add, myList[0])", 'from __main__ import myList; from operator import add')
timeit.timeit("reduce(iadd, myList[0], [])", 'from __main__ import myList; from operator import iadd')
timeit.timeit("reduce(add, myListDoubled)", 'from __main__ import myList; myListDoubled = myList[0] + myList[0]; from operator import add')
timeit.timeit("reduce(iadd, myListDoubled, [])", 'from __main__ import myList; myListDoubled = myList[0] + myList[0]; from operator import iadd')

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


code: "Enter ... worked on {0} : ".format(day)

rawDescription: How can I reference a list element in this function?

description: Reference a list element in this function


code:
pos = res.text.find(': ')
res.text[pos+2:]

rawDescription: Obtain span title using beautifulsoup

description: Obtain span title using beautifulsoup


code:
def my_view(request):
    obj = MyClass(ip_address = request.META['REMOTE_ADDR'])

rawDescription: How to access REMOTE_ADDR in a model's save() method

description: Access REMOTE_ADDR in a model's save() method


code:
x = '''Wal-Mart Stores, Inc.	 Sinopec Group	'''
tmp = [y.find('a') for y in soup(x).find_all('td')]
lst = [x['title'].strip() for x in tmp if x.has_attr('title')]
print(lst)

rawDescription: Python Regex expression for parsing HTML document


code:
def test_timing():
    import time
    a = np.random.randn(100, 2500)

    def timing(func, *args, **kwargs):
        t0 = time.time()
        loops = 10
        for _ in range(loops):
            func(*args, **kwargs)
        print('{} takes {} seconds loops={}'.format(
            func.__name__, time.time() - t0, loops))

    timing(corrcoef, a)
    timing(corrcoef_loop, a)

if __name__ == '__main__':
    test_corrcoef()
    test_timing()

rawDescription: Correlation coefficients and p values for all pairs of rows of a matrix


rawDescription: How do you join all items in a list in python

description: Join all items in a list in python


code:
def release_main_menu_bar(self):
    main_frame = wx.GetApp().GetTopWindow()

    # Unbind the menu event handlers from the main frame.
    main_frame.Unbind(wx.EVT_MENU, handler=self.on_menu)
    main_frame.Unbind(wx.EVT_UPDATE_UI, handler=self.on_menu_update)

    # Remove the edit and tools menu from the main menu bar.
    self.main_menu_bar.Remove(1)
    self.main_menu_bar.Remove(1)

    # Reset the fields used for the menu.
    self.edit_menu = None
    self.tools_menu = None
    self.main_menu_bar = None

rawDescription: How do I manage a dynamic, changing main menu in wxPython?

description: Manage a dynamic, changing main menu in wxPython


rawDescription: Unable to remove additional double quotes in json string added by python


code:
def decompress_gen(compressed):
    number_digits = ''
    for char in compressed:
        if char in string.digits:
            number_digits += char
        else:
            number = int(number_digits) if number_digits else 1
            yield "".join(char * number)
            number_digits = ''

rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


rawDescription: Find Rare Characters with Python

description: Find Rare Characters with Python


rawDescription: Decide when to refresh OAUTH2 token with Python Social Auth


code:
cells = {}
enzymes = {}
biochemicals = {}

with open(filename) as fh:
    out.write(fh.readline()) #ticker
    for line in fh:
        cols = line.split(',')
        row_id = cols[3]
        row_category = cols[17]

        if row_category == ' Cell ':
            cells[row_id] = line
        elif row_category == ' Biochemical ':
            biochemicals[row_id] = line
        elif row_category == ' Enzyme ':
            enzymes[row_id] = line

        if row_id in cells and row_id in biochemicals:
            out.write(cells[row_id])
            out.write(biochemicals[row_id])
            if row_id in enzymes:
                out.write(enzymes[row_id])
        elif row_id in cells and row_id in enzymes:
            out.write(cells[row_id])
            out.write(enzymes[row_id])

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
import random
name = input('Type in your name\n')
score = 0

for _ in range(10):
    number1 = random.randrange(1,13)
    number2 = random.randrange(1,13)
    sign = random.choice(["*", "+", "-"])
    expression = "{0} {1} {2}".format(number1,sign,number2)
    print(expression)
    answer = int(input('What is the answer?\n'))
    print("-------------")
    if answer == eval(expression):
        score += 1

print('{}, you got {} right answers!'.format(name, score))

rawDescription: Python v3.3.5 maths questions program

description: Python v3.3.5 maths questions program


code:
import csv
import tempfile
import os

out = tempfile.mkdtemp()
data = [
    ("1870", [("Jane Doe", "F", 3)]),
    ("1890", [("John Doe", "M", 1)]),
]

for year, rows in data:
    with open(os.path.join(out, "t-{0}.txt".format(year)), "w") as fw:
        csv.writer(fw).writerows(rows)

rawDescription: Exporting text files to PostgreSQL using Spark - Automation


code:
def save_state(a):
    with open('saveit', 'w') as f:
        f.write(str(a))

rawDescription: Python counter between running code

description: Python counter between running code


code:
myhostname = mybox.example.com
mydestination = localhost.server.com, localhost, example.com

rawDescription: Django + Postfix

description: Django + Postfix


url_app: /docspro

rawDescription: Python filter nested dict given list of key names


code:
from numpy import meshgrid, vectorize

def position(edges, value):
    return int((value - edges[0])/diff(edges[:2]))

@vectorize
def pdf2(x, y):
    return H[position(yedges, y), position(xedges, x)]

# test - note we need the meshgrid here to get the right shapes
xx, yy = meshgrid(xcenters, ycenters)
plt.pcolor(xedges, yedges, pdf2(xx, yy))

rawDescription: Return the value of a 2D PDF given x and y in Python?


code:
def set_value(self, member, value):
    setattr(self, member, value)

rawDescription: Passing an Python Class Attribute Given a String


code:
class UserInput: # capitals! Look at PEP 8.
    users = [] # rearranged to the top for better readability

    def __init__(self, name, lista, listb, listc, listd):
        self.name = ""
        self.lista = lista
        self.listb = listb
        self.listc = listc
        self.listd = listd

    @classmethod
    def create_new_user(cls): # no need for x if you overwrite it immediately
        x = cls("x", "", "", "", "")
        cls.users.append(x) # easier access to this static attribute
        return x # for the caller having access to it as well.

rawDescription: Applying the @staticmethod, python3

description: Applying the @staticmethod, python3


code:
from sqlalchemy.orm.query import Query

class AnnotateQuery(Query):
    _annotations = ()

    def annotate(self, key, expr):
        q = self.add_column(expr)
        q._annotations = self._annotations + (key, )
        return q

    def __iter__(self):
        if not self._annotations:
            return super(AnnotateQuery, self).__iter__()
        else:
            for row in super(AnnotateQuery, self):
                item, remaining = row[0], row[1:]
                for i, key in enumerate(self._annotations):
                    setattr(item, key, remaining[i])
                yield item

# session usage:

Session = sessionmaker(query_cls=AnnotateQuery)

# query usage:
q = Session.query(Item).outerjoin(...).annotate('count', Item.count)

rawDescription: SQLAlchemy equivalent to Django's annotate() method


code:
import subprocess

txt_inp = 'some text as input'
process = subprocess.Popen('command', stdin=subprocess.PIPE, stdout=\
        subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
t_arr, t_err = process.communicate(input=txt_inp)

rawDescription: How to replace command line argument of filename with python string of the equivalent file content

description: Replace command line argument of filename with python string of the equivalent file content


rawDescription: Using Jmeter OS Process Sampler to collect script data


code:
import gzip, zlib
f = gzip.open('foo.gz', 'wb')
f.write(b"hello world")
f.close()
c = open('foo.gz', 'rb').read()
c
ba = bytearray(c)
ba
zlib.decompress(ba, 15+32)
zlib.decompress(bytes(ba), 15+32)

rawDescription: howto uncompress gzipped data in a byte array?

description: Howto uncompress gzipped data in a byte array


code:
import numpy as np
import pandas as pd
from datetime import datetime
dates = [datetime(2011, 1, 2), datetime(2011, 1, 5), datetime(2011, 1, 7), datetime(2011, 1, 8), datetime(2011, 1, 10), datetime(2011, 1, 12)]
ts = pd.Series(np.random.randn(6), index=dates)
ts

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


code:
bad_values = [value_tuple for value_tuple in
                  [(myvalue, why_bad(myvalue)) for myvalue in all_values]
              if value_tuple[1]] # value_tuple[1] == why_bad(myvalue)

rawDescription: python list_comprehension to get multiple values

description: Python list_comprehension to get multiple values


code:
def original_approach(a,b):
    c = []
    d = 0
    for i, val in enumerate(a):
        d = d+val
        c.append(d)
        d = d*b[i]
    return c

def vectorized_approach(a,b):
    b_rev_cumprod = b[::-1].cumprod()[::-1]
    B = np.hstack((b_rev_cumprod,1))

    K = a*b
    K_ext = np.hstack((0,K))
    sums = (B*K_ext).cumsum()
    return sums[1:]/b_rev_cumprod

rawDescription: Cumulative addition/multiplication in NumPy


code:
if useText:
    print_square = lambda x: print("The square is" + str(x**2))
else:
    print_square = lambda x: print(x**2)

for i in range(20):
    print_square(i)

rawDescription: Check statement for a loop only once

description: Check statement for a loop only once


code:
'Fantasy'
'Comedy'
'Supernatural'
'Mystery'
'Comedy'
'Super'
'Power'
'Romance'
'Fantasy'
'School'

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


code: # No example because I don't have acces to Python 2.7

rawDescription: Sort nodes after using getElementsByTagName by the nodes attributes


code:
import tempfile
import pandas as pd
import numpy as np

outdir = tempfile.mkdtemp()

for i in range(5):
    pd.DataFrame(
        np.random.randn(10, 2), columns=['foo', 'bar']
    ).to_pickle(tempfile.mkstemp(dir=outdir)[1])

rawDescription: Spark reading python3 pickle as input

description: Spark reading python3 pickle as input


code:
filedata=np.genfromtxt('monthlydata1970to2010.txt',dtype='str') # this will creae 980 * 7 matrix
my_list = (np.float(1) + filedata.astype(np.float)).tolist() # np.float is converted to Python float
nboot=5000
results=np.zeros((11,nboot))   #this will create 11*5000 matrix
results[0,:]=600
horizon=360
balance=200
bootsam=np.random.randint(5, size=(984, nboot)) # this will create 984*5000 matrix
for bs in xrange(0,nboot):
   for mn in xrange(1,horizon+1):
        row = int(bootsam[mn-1,bs]-1)
        if (mn % 12) == 1:
            bondbal = 24*balance
            sp500bal=34*balance
            russbal = 44*balance
            eafebal=55*balance
            cashbal =66*balance

            bondbal=bondbal*(my_list[row][2])
            sp500bal=sp500bal*(my_list[row][3])
            russbal=russbal*(my_list[row][4])
            eafebal=eafebal*(my_list[row][5])
            cashbal=cashbal*(my_list[row][6])
            balance=bondbal + sp500bal + russbal + eafebal + cashbal
        else:
            bondbal=bondbal*(my_list[row][2])
            sp500bal=sp500bal*(my_list[row][3])
            russbal=russbal*(my_list[row][4])
            eafebal=eafebal*(my_list[row][5])
            cashbal=cashbal*(my_list[row][6])
            balance=bondbal + sp500bal + russbal + eafebal + cashbal

rawDescription: Python: how to optimize this code

description: Python: how to optimize this code


code:
'abcddcbaabcd'.replace('abcd', '')
'abcddcbaabcd'.replace('abcd', '', 1)

rawDescription: Python: strip a wildcard word

description: Python: strip a wildcard word


code:
result = {
    div.find("a")["id"]: {
        cells[0].text : cells[1].text
        for row in table.find_all("tr", {"class":None})
        for cells in [row.find_all("td")]
    }
    for div in soup.find_all("div", {"class":"info"})
    for table in [div.find_next("table", {"class":"properties"})]
}

pprint(result)

rawDescription: How to create structured array out of unstructured HTML using python

description: Create structured array out of unstructured HTML using python


code:
program = 'C:/Python27/Scripts/lizard.bat'
...
command = [program, path1]

rawDescription: Unable to get output of shell script run from python


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

rawDescription: Drop Duplicate in market data

description: Drop Duplicate in market data


code:
emails = defaultdict(list)
for email,email_date in list_of_tuples:
    emails[email].append(email_date)

rawDescription: How to efficiently select entries by date in python?

description: Efficiently select entries by date in python


code: value = data[target]

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


rawDescription: Proper/most efficient way to handle Django models and relational data


code:
def __init__(self, x=[]):
    self._x = x

rawDescription: Python __init__ finding variable from nowhere


code:
def cumsum2_reverse_alt(arr):
    out = np.zeros_like(arr)
    out[:-1, :-1] = np.cumsum(np.cumsum(arr[:0:-1, :0:-1], 0), 1)[::-1, ::-1]
    return out

rawDescription: Inverse cumsum for numpy

description: Inverse cumsum for numpy


code:
#add sheet name
result.to_excel(writer, sheet_name=sheetname)
workbook = writer.book

#add sheet name
worksheet = writer.sheets[sheetname]
worksheet.set_zoom(80)

rawDescription: Loop through a pandas dataframe with multiple groupby functions and write to excel


code:
#!/usr/bin/env python

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'taco_login.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
     _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
         return QtGui.QApplication.translate(context, text, disambig)

class Ui_login_window(QtGui.QDialog):
    def setupUi(self):
        self.setObjectName(_fromUtf8("login_window"))
        self.resize(255, 150)
        self.setMinimumSize(QtCore.QSize(255, 150))
        self.setMaximumSize(QtCore.QSize(255, 150))
        self.setStyleSheet(_fromUtf8("QDialog#login_window {\n"
"    background-color: qlineargradient(spread:pad, x1:0.559, y1:0, x2:0.555, y2:1, stop:0.445455 rgba(48, 48, 48, 255), stop:0.859091 rgba(61, 61, 61, 255), stop:1 rgba(79, 79, 79, 255));\n"
"}"))
        self.verticalLayout_2 = QtGui.QVBoxLayout(self)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.widget = QtGui.QWidget(self)
        self.widget.setObjectName(_fromUtf8("widget"))
        self.password_lineEdit = QtGui.QLineEdit(self.widget)
        self.password_lineEdit.setGeometry(QtCore.QRect(10, 60, 221, 22))
        self.password_lineEdit.setStyleSheet(_fromUtf8("QWidget {border:none;}"))
        self.password_lineEdit.setInputMask(_fromUtf8(""))
        self.password_lineEdit.setEchoMode(QtGui.QLineEdit.Password)
        self.password_lineEdit.setObjectName(_fromUtf8("password_lineEdit"))
        self.login_btn = QtGui.QPushButton(self.widget)
        self.login_btn.setGeometry(QtCore.QRect(10, 100, 91, 17))
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
        self.login_btn.setPalette(palette)
        self.login_btn.setAutoFillBackground(False)
        self.login_btn.setStyleSheet(_fromUtf8("QPushButton#login_btn {\n"
"    background-color: rgb(255, 255, 255);\n"
"    border:none;\n"
"}"))
        self.login_btn.setObjectName(_fromUtf8("login_btn"))
        self.username_lineEdit = QtGui.QLineEdit(self.widget)
        self.username_lineEdit.setGeometry(QtCore.QRect(10, 30, 221, 22))
        self.username_lineEdit.setStyleSheet(_fromUtf8("QWidget {border:none;}"))
        self.username_lineEdit.setInputMask(_fromUtf8(""))
        self.username_lineEdit.setObjectName(_fromUtf8("username_lineEdit"))
        self.text_1 = QtGui.QTextEdit(self.widget)
        self.text_1.setGeometry(QtCore.QRect(6, 0, 141, 25))
        self.text_1.setStyleSheet(_fromUtf8("QTextEdit#text_1{\n"
"border: none;\n"
"    background-color: transparent;\n"
"}\n"
""))
        self.text_1.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.text_1.setObjectName(_fromUtf8("text_1"))
        self.cancel_btn = QtGui.QPushButton(self.widget)
        self.cancel_btn.setGeometry(QtCore.QRect(140, 100, 91, 17))
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
        self.cancel_btn.setPalette(palette)
        self.cancel_btn.setAutoFillBackground(False)
        self.cancel_btn.setStyleSheet(_fromUtf8("QPushButton#cancel_btn {\n"
"    background-color: rgb(255, 255, 255);\n"
"    border:none;\n"
"}"))
        self.cancel_btn.setObjectName(_fromUtf8("cancel_btn"))
        self.verticalLayout_2.addWidget(self.widget)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        self.setWindowTitle(_translate("login_window", "TACO", None))
        self.password_lineEdit.setText(_translate("login_window", "Password", None))
        self.login_btn.setText(_translate("login_window", "Login", None))
        self.username_lineEdit.setText(_translate("login_window", "Username", None))
        self.text_1.setHtml(_translate("login_window", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Welcome to TACO!
", None))
        self.cancel_btn.setText(_translate("login_window", "Cancel", None))

    @QtCore.pyqtSignature("on_cancel_btn_clicked()")
    def Cancel_btn(self):
        self.close()

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    ui = Ui_login_window()
    ui.setupUi()
    ui.show()
    sys.exit(app.exec_())

rawDescription: Trying to close and open a new window using PyQT(Closed)


code:
# Also from root/django/trunk/django/contrib/auth/models.py
def check_password(raw_password, enc_password):
    """
    Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.
    """
    algo, salt, hsh = enc_password.split('$')
    return hsh == get_hexdigest(algo, salt, raw_password)

rawDescription: What is the format in which Django passwords are stored in the database?


code:
@pytest.mark.skipif("pytest.param == 'value'")
class TestSmth(object):
    ...

rawDescription: Skip test depending on parameter in py.test


code:
from selenium import webdriver
url = "http://jassa.fr/"
browser = webdriver.Firefox()
browser.get(url)
form = browser.find_element_by_tag_name("form")
sequence = form.find_element_by_name("sequence")
sequence.clear()
sequence.send_keys("ATTTAATTTA")
form.submit()

rawDescription: Python: scraping results of webpage of which results are generated server-side


code:
for row in csvreader:
    myDict[row[6]] = myDict.get(row[6], 0) + 1

rawDescription: Read inputfile as csv in python

description: Read inputfile as csv in python


code:
date1, date2 = options[text]() # Get the correct function and call it
result, data = ga.get_sessions_today_data(user_id, date1, date2)
result, data, caption = get_final_caption(result, data, date1, date2, 'hour', 'sessions')
handle_result(chat_id, result, data, caption)

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

description: Pass function as parameter to another function


code:
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://localhost:1111/')
browser.find_element_by_css_selector('[id*="OpenLayers.Layer.Vector"]').click()

rawDescription: Finding a element with a generated Id in selenium?


code: class User(object): ...

rawDescription: How do I call a property setter from __init__

description: Call a property setter from __init__


code:
def command_adddeath():
    global counter
    counter += 1
    print(counter)
    send_message(CHAN, 'Death counter has been updated!')

rawDescription: Using Python to keep track of deaths (Twitch bot)


code:
import json

list_of_ee = [["a","m",15],["w","p",34]]

with open("test.json", "wt") as f:
    f.write(json.dumps(list_of_ee))

with open("test.json", "rt") as f:
    s = f.read()
    lst = json.loads(s)

print(lst)
assert list_of_ee == lst

rawDescription: Import csv as list of list in python 3.3


code:
def foo(param, flag):
    if flag == 'foo':
        do_this()
    elif flag == 'bar':
        do_that()
    else:
        raise ValueError()

rawDescription: Optional but conditional argument python


code:
def f(x):
    print(x)

if __name__ == "__main__":
    # Create two lists of tuples, like your use-case
    x = zip(range(3), range(3,6))
    y = zip(range(6, 9), range(9, 12))

    pool = multiprocessing.Pool()
    pool.map(f, itertools.product(x, y))

rawDescription: parallelize recursion python

description: Parallelize recursion python


code:
#s3config.py
passwd = 'BLABALBALABALA'
secret = 'xvdwv3efefefefefef'
bucket = 'name-of-your-bucket'

rawDescription: How can I store URLs from Amazon S3 bucket in Django sqlite db to display & comment on?

description: Store URLs from Amazon S3 bucket in Django sqlite db to display & comment on


code:
def gL(gridList, values):
    return gridlist[values[0]][values[1]]

rawDescription: Turning a list of coordinates into a set of list/grid references


code:
{
    "_id" : 1,
    "entry_date" : ISODate("2011-01-01T05:00:00Z"),
    "title" : "A love supreme",
    "category" : "music",
    "tags" : [
        "jazz",
        "American"
    ]
}

rawDescription: How to convert this RDBMS schema to a MongoDB "schema" (and how to query against it)

description: Convert this RDBMS schema to a MongoDB "schema" (and how to query against it)


code:
class EventNotifier(object):
    def __init__(self):
        self._listeners = []

    def add_listener(self, callback):
        ''' callback should accept two positional arguments, event and params '''
        self._listeners.append(callback)
        # ...

    def notify(self, event, *params):
        for f in self._listeners:
            f(event, params)

rawDescription: How does the functools partial work in Python?


rawDescription: Making a raw dictionary sane

description: Making a raw dictionary sane


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

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


code:
def find_key(dic):
 keys=[]
 if isinstance(dic,dict):
  for key,value in dic.items():
     if isinstance(value,dict):
        keys.append(key)
        keys.append(find_key(value))
     elif isinstance(value,list):
         keys.append(key)
         keys.append(find_key(value[0]))
     else:
        keys.append(key)
  return keys

rawDescription: Parse an entire JSON object looking for a key in python


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

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


code:
from itertools import groupby
mylist = [x for x in mylist if x[-2] != '00:00' ]

rawDescription: How to find a min value of a row in a specified column in a tuple - Python 2.6?

description: Find a min value of a row in a specified column in a tuple - Python 2.6


code: (a, b), c = someseq[:2], someseq[2:]

rawDescription: Multiple Unpacking Assignment in Python when you don't know the sequence length


rawDescription: moving average of 3 elements by C or Python

description: Moving average of 3 elements by C or Python


code:
#!/usr/bin/python
import json
import cgi
import cgitb
import sys
reload(sys)
sys.setdefaultencoding('utf8')
form = cgi.FieldStorage()
cityRu = form.getvalue('city')
print ("Content-type: text/html")
print ("")
cities = json.loads(open('json/cities.json').read())
ourResult = cities
for rs in ourResult:
    try:
        print (rs['name_translations']['en']+' - '+rs['name_translations']['ru'])
    except KeyError:
        print ("ERROR WITH KEYS")
        # do something else...

rawDescription: enumeration values in json

description: Enumeration values in json


code:
import numpy as np
import StringIO

s = """1 10 1.2345 5.4321 10.5647
       2 14 434.35 345.34 1000000
       3 8  253.235 2.53 .002345"""
f = StringIO.StringIO(s)

data = np.genfromtxt(f, names = 'id, count, x, y, z', dtype=[int,int,float,float,float])

rawDescription: parsing a python string with floats and ints

description: Parsing a python string with floats and ints


code:
SITE_ROOT = '/home/user/repo'
conf = {
    '/': {
        'tools.staticdir.root': os.path.join(SITE_ROOT, 'static')
    },
    '/test': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': 'test'
    },
    '/static/test': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': 'test'
    },
}

rawDescription: Static URL in cherrypy

description: Static URL in cherrypy


code:
a = datetime.datetime(2010, 1, 12) + datetime.timedelta(days = 3)
b = datetime.datetime.now()

a < b
a > b
a == b

rawDescription: How to convert date to timestamp using Python?

description: Convert date to timestamp using Python


code: LOG_FILE_MAIN = '{LOG_DIR}/main.log'

rawDescription: Calculate string values dynamically

description: Calculate string values dynamically


code:
L=[1, 2, 3]
def fgen(param_n):
    local_n = param_n
    def f():
        return local_n * local_n
    return f

a, b, c = [fgen(n) for n in L]
a()
b()
c()

rawDescription: Confused by lexical closure in list comprehension


rawDescription: Get element inside current element using xpath


code:
num_seq = 2910
ArrSequence = [0]*num_seq

for i in range(num_seq):
    name = []
    Arr_Seq = get_arrow_seq(6)
    for i in range(len(Arr_Seq)):
        if (Arr_Seq[i] == L.array).all():
            name.append('L')
        elif (Arr_Seq[i] == R.array).all():
            name.append('R')
        elif (Arr_Seq[i] == U.array).all():
            name.append('U')
        elif (Arr_Seq[i] == D.array).all():
            name.append('D')
        else:
            name.append(0)
    if i<2:
        ArrSequence[i] = np.hstack(Arr_Seq)

    elif np.hstack(Arr_Seq) not in [ArrSequence]:
        ArrSequence[i] = np.hstack(Arr_Seq)

    else:
        i = i-1

    cv2.imwrite(''.join(name) + '.png', ArrSequence[i])

rawDescription: Extracting class attribute from objects in non class array in python


code:
def findWord(w):
    return re.compile(r'\b({0})\b'.format(re.escape(w)), flags=re.IGNORECASE).search

rawDescription: Search patern to include square brackets


code:
def split_list(L, n):
  """split successive n-sized groups from L as a list
  """
  from math import ceil
  parts = int(ceil(len(L)/float(n))) # ceilng division 5/2 ==> 3
  return [int(''.join(str(_) for _ in L[i*n: i*n + n])) for i in range(parts)]

rawDescription: Parse simple array and save it on a file


code:
flag = [False]
def purchase_possibilities(amounts, goal, current=[], highest=0, curr_sum=0, index=0):
    # See if we are done.
    if curr_sum == goal:
        flag[0] = True
        return self.display(current, amounts)

    if curr_sum > goal:
        return []

    for value in amounts:
        if value >= highest:
            copy = current[:]
            copy.append(value)
            # Copy the current list, then add the current value.
            # Recursively add more current.
            self.purchase_possibilities(amounts, goal, copy, value, curr_sum + value, index=index)
    return flag[0]

rawDescription: Determining if a recursion call has no solution


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


code:
a
b
c
d
e
...
y
z
aa
ab
ac
...
ay
az
ba
bb

rawDescription: How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)

description: Make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)


code:
W_est = np.linalg.pinv(X.T).dot(Z.T).T

from numpy.testing import assert_array_almost_equal
assert_array_almost_equal(W, W_est, decimal=3)

rawDescription: Fit a linear transformation in python

description: Fit a linear transformation in python


code:
@app.route("/idea/<idea_id>", methods=["POST","GET"])
def get_idea(idea_id):
    db = get_db()
    cur = db.execute("select id, title, description, image from ideas where id=?", (idea_id,))
    ideas = cur.fetchall()
    args = request.path
    return render_template("idea.html", ideas=ideas, idea_id=idea_id)

rawDescription: Get value from URL in another app.route

description: Get value from URL in another app.route


code: help(MyZipFile)

rawDescription: where is the __enter__ and __exit__ defined for zipfile?

description: Where is the __enter__ and __exit__ defined for zipfile


code:
import unittest
import numpy as np

class ListView(list):
  def __init__(self, raw_list, raw2new, new2raw):
    self._data = raw_list
    self.converters = {'raw2new': raw2new,
        'new2raw': new2raw}

  def __repr__(self):
    repr_list = [self.converters['raw2new'](item) for item in self._data]
    repr_str = "["
    for element in repr_list:
      repr_str += element.__repr__() + ",\n "
    repr_str = repr_str[:-3] + "]"
    return repr_str

  def append(self, item):
    self._data.append(self.converters['new2raw'](item))

  def pop(self, index):
    self._data.pop(index)

  def __getitem__(self, index):
    return self.converters['raw2new'](self._data[index])

  def __setitem__(self, key, value):
    self._data.__setitem__(key, self.converters['new2raw'](value))

  def __delitem__(self, key):
    return self._data.__delitem__(key)

  def __getslice__(self, i, j):
    return ListView(self._data.__getslice__(i,j), **self.converters)

  def __contains__(self, item):
    return self._data.__contains__(self.converters['new2raw'](item))

  def __add__(self, other_list_view):
    assert self.converters == other_list_view.converters
    return ListView(
        self._data + other_list_view._data,
        **self.converters
        )

  def __len__(self):
    return len(self._data)

  def __iter__(self):
    return iter([self.converters['raw2new'](item) for item in self._data])

  def __eq__(self, other):
    return self._data == other._data

class One(object):
  """
  Data Transfere Object (DTO)
  """
  def __init__(self, name, data):
    assert type(name) == str
    assert type(data) == str
    self.name = name
    self.data = data

  def __repr__(self):
    return "%s(%r, %r)" %(self.__class__.__name__, self.name, self.data)

class Two(np.ndarray):
  _DTO = One
  def __new__(cls, name, data):
    dto = cls._DTO(name, data)
    return cls.newByDTO(dto)

  @classmethod
  def newByDTO(cls, dto):
    obj = np.fromstring(dto.data, dtype="float", sep=',').view(cls)
    obj.setflags(write=False) # Immutable
    obj._dto = dto
    return obj

  @property
  def name(self):
    return self._dto.name

  def getDTO(self):
    return self._dto

class DataUI(object):
  def __init__(self, list_of_ones):
    for one in list_of_ones:
      assert type(one) == One
    self.list_of_ones = list_of_ones
    self.list_of_twos = ListView(
        self.list_of_ones,
        Two.newByDTO,
        Two.getDTO
        )

class TestListView(unittest.TestCase):
  def testProperties(self):
    o1 = One('first object', "1, 3.0, 7, 8,1")
    o2 = One('second object', "3.7, 8, 10")
    my_data = DataUI ([o1, o2])

    t1 = Two('third object', "4.8, 8.2, 10.3")
    t2 = Two('forth object', "33, 1.8, 1.0")
    # append:
    my_data.list_of_twos.append(t1)
    # __getitem__:
    np.testing.assert_array_equal(my_data.list_of_twos[2], t1)
    # __add__:
    np.testing.assert_array_equal(
        (my_data.list_of_twos + my_data.list_of_twos)[5], t1)
    # __getslice__:
    np.testing.assert_array_equal(
        my_data.list_of_twos[1:],
        my_data.list_of_twos[1:2] + my_data.list_of_twos[2:]
        )
    # __contains__:
    self.assertEqual(my_data.list_of_twos.__contains__(t1), True)
    # __setitem__:
    my_data.list_of_twos.__setitem__(1, t1),
    np.testing.assert_array_equal(my_data.list_of_twos[1], t1)
    # __delitem__:
    l1 = len(my_data.list_of_twos)
    my_data.list_of_twos.__delitem__(1)
    l2 = len(my_data.list_of_twos)
    self.assertEqual(l1 - 1, l2)
    # __iter__:
    my_data_2 = DataUI ([])
    for two in my_data.list_of_twos:
      my_data_2.list_of_twos.append(two)

if __name__ == '__main__':
  unittest.main()

rawDescription: How can I change in Python the return/input type of a list that is implemented as an class attribute?

description: Change in Python the return/input type of a list that is implemented as an class attribute


code: node_connected_component(G, n)

rawDescription: Fetch connected nodes in a NetworkX graph


code:
QShortcut(Qt.Key_Enter, self.Begin, self.handleBegin)
QShortcut(Qt.Key_Return, self.Begin, self.handleBegin)

rawDescription: QT Designer how to assign 2 hotkeys to a QPushButton (python3)


code: out = f(arr[:, :, None, None], arr)

rawDescription: Iterate over all pairwise combinations of numpy array columns


rawDescription: Append a list to the value for matching key values


code:
from functools import partial
myprint = partial(print, end='', flush=True)
myprint('Fishing')
for i in range(5):
    time.sleep(1)
    myprint('.')

rawDescription: Strange print behavior with time.sleep in python


code:
from itertools import chain
list(chain.from_iterable(x[0]))

rawDescription: How to conver this list/tuple in the following list in Python?

description: Conver this list/tuple in the following list in Python


code:
import sys
from PySide import QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # Setup the window
        self.resize(750, 550)
        self.myGUI()

    def myGUI(self):
        # create tab widget
        self.mytabs_widget = QtGui.QTabWidget(self)
        self.mytabs_widget.addTab(SampleTab1(self.mytabs_widget), "Tab 1")

        # create the layout area for tab widget
        self.mylayout = QtGui.QHBoxLayout()
        self.mylayout.addWidget(self.mytabs_widget)

        # create content area widget for padding
        self.mycontent_widget = QtGui.QWidget()
        self.mycontent_widget.setContentsMargins(5, 5, 5, 0)
        self.mycontent_widget.setLayout(self.mylayout)

        # set the central widget
        self.setCentralWidget(self.mycontent_widget)
        self.setWindowTitle("Tab Example")

        # Create a status bar with the progress information.
        self.statusText = QtGui.QLabel("Ready")
        self.statusBar().addWidget(self.statusText, 1)

class SampleTab1(QtGui.QWidget):
    def __init__(self, parent=None):
        super(SampleTab1, self).__init__(parent)
        label = QtGui.QLabel('Sample tab 1', self)
        label.move(15, 10)
        self.show()
        self.process()

    def process(self):
        self.parent().parent().statusBar().showMessage("Processing")

def main():
    try:
        app = QtGui.QApplication(sys.argv)
    except:
        app = QtGui.QApplication.instance()
    app.aboutToQuit.connect(app.deleteLater)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PySide: How to change the status bar text from another class?


code:
class Test(object):
    def method1(self, arg):
        "docstring1"
        print(arg)

    method2 = my_partial_method(method1, "foo")
    method2.__name__ = "method2"
    method2.__doc__ = "docstring2"

    method3 = my_partial_method(method1, arg="bar")
    method3.__name__ = "method3"
    method3.__doc__ = "docstring3"

rawDescription: Documentation of functions defined with functools partialmethod


code:
def run_once(f):
    def wrapper(*args, **kwargs):
        if not wrapper.has_run:
            wrapper.has_run = True
            return f(*args, **kwargs)
    wrapper.has_run = False
    return wrapper

@run_once
def my_function(foo, bar):
    return foo+bar

rawDescription: Efficient way of having a function only execute once in a loop


code:
class PiecePoly():
    """
    A class to mimick the MATLAB struct piecewise polynomial (pp)
    """
    def __init__(self):
        form = 'pp'
        breaks = []
        coefs = []
        pieces = 0
        order = 0
        dim = 0

rawDescription: Converting matlabs mkpp to python

description: Converting matlabs mkpp to python


code:
@pytest.mark.parametrize("arg,expected", [
    ({'h':4}, 54),
    ({'g':20}, 102),
    ])

def test_f2(arg, expected):
    assert f(**arg) == expected

rawDescription: Using parametrize for keyword arguments in pytest


code:
import io
def insert(s,where,what):
    whatlen=len(what)
    s.seek(0)
    cur=len(s.read())
    if cur < where:
        raise IndexError("Can't insert at position {}: Index out of bounds"
                .format(where))
    s.seek(where)
    r=s.read()
    s.seek(where+whatlen)
    s.write(r)
    s.seek(where)
    s.write(what)

s = io.StringIO("This is a test")

insert(s,5,"hello")
s.seek(0)
print(s.read()) #prints "This hellois a test"

rawDescription: Why is there no insert() method for strings in Python?


code:
with open('data.txt') as f:
    next(f)
    d=dict()
    for x in f:
        if x.split()[0] not in d:
            d[x.split()[0]]=float(x.split()[2])
        else:
            d[x.split()[0]]+=float(x.split()[2])

rawDescription: To sum column with condition

description: To sum column with condition


code:
import numpy as np
import scipy.sparse

def intersection_counts(x,y):
    # find the size of the input arrays
    n_x, n_d = x.shape
    n_y, n_d = y.shape

    # get a list of the unique values appearing in x and y, as well
    # as a list of inverse indices (see docs for np.unique)
    values, ix = np.unique(np.vstack((x,y)), return_inverse=True)
    n_unique = len(values)

    # reshape the inverse array. ix_x_hat will be an array the same size
    # as x, where ix_x_hat[i,j] gives the index of x[i,j] in values. That
    # is to say, values[ix_x_hat[i,j]] == x[i,j]
    ix_hat = ix.reshape(-1, n_d)
    ix_x_hat = ix_hat[:n_x]
    ix_y_hat = ix_hat[n_x:]

    # create a sparse matrix where entry [i,j] is 1 if and only if
    # row i of x contains values[j]
    x_hat = scipy.sparse.lil_matrix((n_x, n_unique), dtype=int)
    x_hat[np.arange(n_x)[:,None], ix_x_hat] = 1

    # create a sparse matrix where entry [i,j] is 1 if and only if
    # row i of y contains values[j]
    y_hat = scipy.sparse.lil_matrix((len(y), len(values)), dtype=int)
    y_hat[np.arange(n_y)[:,None], ix_y_hat] = 1

    # the dot product gives the solution
    return x_hat.dot(y_hat.T)

rawDescription: NumPy: counting sizes of row-wise intersections between two arrays


code:
active = False # A variable `flag` is not very precisely named,
               # better call it `active`, make it boolean
               # and flip the values
for line in data:
    if " innings " in line:
        active = True    # now we want to do things
        print('')
        continue         # but not in this loop
    if line.startswith("Extras   "):
        print('')
        break             # now we're done!
        # alternative Method:
        # active = False
    if active:
        print(line)

rawDescription: Python3 Extracting lines between first instance of two markers


code:
try:
    text_file = open("list_number.txt", "r") #File contain your 5 line data, with header removed

    try:
        count = 0
        for row in text_file:
            col = row.split() # switch to row.split(',') if you're using coma delimiter
            count+=1
            if abs(float(col[1]) - float(col[2])) <= 10: # Change to 1
                #print('The values in row %s are %s and %s, are within 10.0 of each other.' % (count, col[1], col[2]))
                print('The values in row {0} are {1} and {2}, are within 10.0 of each other.'.format(count, col[1], col[2]))
    finally:
        text_file.close()

except IOError as e:
    print("Unable to open file : ", e)

rawDescription: Find and display rows with approximately close entries


code:
from random import random

MAX_X_COORD = 1000.0
MAX_Y_COORD = 1000.0
MAX_R = 1.0
CIRCLE_COUNT = 10000000

def dxf_circle(x, y, r):
    return "0\nCIRCLE\n8\n0\n10\n{x:.3f}\n20\n{y:.3f}\n40\n{r:.2f}\n".format(x=x, y=y, r=r)

with open("circles.dxf", 'wt') as f:
    f.write("0\nSECTION\n2\nENTITIES\n")
    for i in range(CIRCLE_COUNT):
        f.write(dxf_circle(MAX_X_COORD*random(), MAX_Y_COORD*random(), MAX_R*random()))
    f.write("0\nENDSEC\n0\nEOF\n")

rawDescription: how to quickly create large dxf from geometrical shapes

description: Quickly create large dxf from geometrical shapes


code:
class A:
    @memoize
    @staticmethod
    def get_username():
        try:
            return os.environ["USER"]
        except:
            print("Couldn't find a user name")
            return None

rawDescription: Python 3 static members

description: Python 3 static members


code:
#import tkinter as TK
import newTkinter as TK

rawDescription: Tkinter importing without *?

description: Tkinter importing without *


code:
from unittest.mock import Mock
def actual_fu(foo, bar):
    pass
m = Mock()
m('foo', bar='baz')
m.assert_called_once_with(foo='foo', bar='baz')

rawDescription: check unittest.mock call arguments agnostically w.r.t. whether they have been passed as positional arguments or keyword arguments

description: Check unittest.mock call arguments agnostically w.r.t. whether they have been passed as positional arguments or keyword arguments


rawDescription: Check for multiple maximum dictionary values and output the keys accordingly


rawDescription: Django count number of times each ForeignKeyField value appears in table & retain __unicode__()


code:
words = 'the horse and the rider'.split(' ')
look_for = 'the'
indices = [i for i, word in enumerate(words) if word == look_for]
print(indices)

rawDescription: Python find which order element is in in a list


rawDescription: Pandas: Convert time interval integers to times


code:
# works for python 3.4 and PyQt4.11
def data(self,index,role):
    if not index.isValid():
        return(None)
    # for all roles you're not interested in, do nothing: i.e. return python's None which is interpreted as an invalid QVariant value
    elif role != QtCore.Qt.DisplayRole:
        return(None)
    else:
        return(self.data[index.row()][index.column()])

rawDescription: How to hide checkboxes in a QTableView using python?

description: Hide checkboxes in a QTableView using python


code: result = dict([(k,v) for k,v in theDict.items() if len(v)>0])

rawDescription: How to avoid using tuples and what will this look like without list comprehension

description: Avoid using tuples and what will this look like without list comprehension


code:
obtype = simulation_objects[confvar] #get the class/type from the dict
ob = obtype() #instansiates (is e.g. bird.Bird())
simulation.add(ob)

rawDescription: Is there an easy way instantiate many different objects on the fly based on an input without if statements?


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

description: Call a distant shell script from a python file


rawDescription: numpy genfromtxt issues in Python3

description: Numpy genfromtxt issues in Python3


code: q = { (i,j):0 for i in range(5) for j in range(4) }

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


rawDescription: Python, concise way to test membership in collection using partial match


rawDescription: Remove duplicate dict in list in Python

description: Remove duplicate dict in list in Python


code:
da = np.where(np.abs(np.diff(a)) > 100)
da

rawDescription: Measure distance between objects in picture with python


code:
# Reshape input array to a 2D array with rows being kept as with original array.
# Then, get idnices of max values along the columns.
max_idx = A.reshape(A.shape[0],-1).argmax(1)

# Get unravel indices corresponding to original shape of A
maxpos_vect = np.column_stack(np.unravel_index(max_idx, A[0,:,:].shape))

rawDescription: Numpy: argmax over multiple axes without loop


code: joined_index = df1.index+df2.index

rawDescription: Matrix addition using triples representation in Python


code: protocol.ClientCreator(reactor, OA, SN, PASS, icq=icqMode).connectTCP(*hostport)

rawDescription: Sending ICQ messages from outside event handlers in Twisted, Oscar


code:
irow
iradius
itheta

rawDescription: Is there any python (numpy) synonym to i-variables (e.g., irow, iradius, itheta, etc.) in DM scripting?


code:
try:
    num_points = nparray.shape[1]
except IndexError:
    num_points = 1

rawDescription: Check number of columns numpy array that returns 1 if is a 1-dimensional array


code:
df = pd.DataFrame([['a_link', 'dofollow'], ['a_link', 'dofollow'], ['a_link', 'nofollow'], ['b_link', 'javascript']], columns=['link', 'type'])
df
df.groupby(['link', 'type']).size()

rawDescription: python: Working with pandas. Getting counts

description: Python: Working with pandas. Getting counts


code:
import sys
import pickle
import urllib2

request = urllib2.Request('http://www.iana.org/domains/example/')
response = urllib2.urlopen(request) # Make the request
htmlString = response.read()

try:
    file = pickle.load( open( 'D:\\Download\\htmlString.p', 'rb'))
    if pickle.load( open( 'D:\\Download\\htmlString.p', 'rb')) == htmlString:
        print("Values haven't changed!")
        sys.exit(0)
    else:
        pickle.dump( htmlString, open( 'D:\\Download\\htmlString.p', "wb" ) )
        print('Saving')
except IOError:
    pickle.dump( htmlString, open( 'D:\\Download\\htmlString.p', "wb" ) )
    print('Created new file.')

rawDescription: How to check if the value on a website has changed

description: Check if the value on a website has changed


code: text_width, text_height = d.textsize('Hello')

rawDescription: Convert string to image in python

description: Convert string to image in python


code:
fieldnames = ["one", "three", "ten"]
dictlist = [{"one": "bob", "two": "bill", "three":"cat"},
            {"one": "john", "two": "jack", "ten":"dog"}]

res = [[item.get(key, '') for key in fieldnames] for item in dictlist]
res.insert(0, fieldnames)
print(res)

rawDescription: Convert array of dictionaries into 2 dimensional array with potentially non-matching fieldnames


rawDescription: Looping through a list of hosts and commands in Paramiko and store the result in excel with column headers


code: res = requests.post(url, data=form_data, headers=headers)

rawDescription: Python Requests Not Returning Same Header as Browser Request/cURL


code:
b = [1,3,5]
a[:,b][b]
a[b][:,b]  #I think the same thing, but depending on data layout, one may be faster than the other

rawDescription: Return rows and columns from a 2d array using values from a 1d array in Numpy


code: import x; help(x)

rawDescription: What to put in a python module docstring?


code:
def foo(a, b):
    import inspect # 'inspect' is a local name
    x = 3          # 'x' is another local name
    args = inspect.getfullargspec(foo).args
    return {k:v for k,v in locals().items() if k in args}
foo(1, 2) # Only the argument names are returned

rawDescription: packing named arguments into a dict

description: Packing named arguments into a dict


code:
merged.dropna(subset=['indicator'], inplace=True)
merged['indicator'] = merged.indicator.copy().astype(bool)
merged

rawDescription: Pandas MultiIndex Operations on Sub-Index


code:
class QuestionForm(forms.ModelForm):

    page = PageModelChoiceField(
        queryset=Page.objects.select_related('test').all()
    )

    class Meta:
        model = Page

class QuestionAdmin(ModelAdmin):
    class Meta:
        model: Question
        form: QuestionForm

rawDescription: Django admin foreign key dropdown with custom value