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

import logging
from multiprocessing import Process, Queue
from threading import Thread
from time import sleep

logger = logging.getLogger("mepy-client")

class SocketClientProtocol(object):

    def __init__(self, q_in, q_out, q_binary):
        self.q_in = q_in
        self.q_out = q_out
        self.q_binary = q_binary
        t = Thread(target=self._loop)
        t.start()
        t = Thread(target=self._loop_binary)
        t.start()

    def _loop(self):
        print("start of loop 2")
        for res in iter(self.q_in.get, None):
            self._handle_msg(res)
        print("end of loop 2")

    def _loop_binary(self):
        print("start of loop 3")
        for res in iter(self.q_binary.get, None):
            self._handle_binary(res)
        print("end of loop 3")

    def _handle_msg(self, msg):
        msg_type = msg[0]
        if msg_type == "stop2":
            self.q_in.put(None)
            self.q_binary.put(None)

    def _put_msg(self, msg):
        self.q_out.put(msg)

    def stop(self):
        print("STOP RECEIVED")
        self.q_in.put(None)
        self.q_binary.put(None)

    def _handle_binary(self, data):
        pass

    def handle_element(self):
        self._put_msg(["something"])

def run_twisted(q_in, q_out, q_binary):
    s = SocketClientProtocol(q_in, q_out, q_binary)
    try:
        while True:
            sleep(2)
            s.handle_element()
    except KeyboardInterrupt:
        s.stop()

class MediatorSender(object):

    def __init__(self):
        self.q_in = None
        self.q_out = None
        self.q_binary = None
        self.p = None
        self.running = False

    def start(self):
        if self.running:
            return
        self.running = True
        self.q_in = Queue()
        self.q_out = Queue()
        self.q_binary = Queue()
        print("!!!!START")
        self.p = Process(target=run_twisted,
                         args=(self.q_in, self.q_out, self.q_binary))
        self.p.start()
        self.loop = Thread(target=self._loop)
        self.loop.start()

    def stop(self):
        print("!!!!STOP")
        if not self.running:
            return
        print("STOP2")
        self.running = False
        self.q_out.put(None)

    def _loop(self):
        print("start of loop 1")
        for res in iter(self.q_out.get, None):
            self._handle_msg(res)
        print("end of loop 1")

    def _handle_msg(self, msg):
        self._put_msg(msg)

    def _put_msg(self, msg):
        self.q_in.put(msg)

    def _put_binary(self, msg):
        self.q_binary.put(msg)

    def send_chunk(self, chunk):
        self._put_binary(chunk)

if __name__ == "__main__":
    ms = MediatorSender()
    try:
        ms.start()
        for i in range(100):
            ms.send_chunk("some chunk of data")
        # You actually have to join w/ a timeout in a loop on
        # Python 2.7. If you just call join(), SIGINT won't be
        # received by the main process, and the program will
        # hang. This is a bug, and is fixed in Python 3.x.
        while True:
            ms.loop.join()
    except KeyboardInterrupt:
        ms.stop()

description: Python multiprocessing/threading cleanup


code: np.linalg.lstsq(X, y)

rawDescription: Analytical solution for Linear Regression using Python vs. Julia


code: res = [(x, my_dictionary[x]) for x in my_list]

rawDescription: Is it possible to take an ordered "slice" of a dictionary in Python based on a list of keys?


code: root.find('maxspeed').find('unit') #returns the unit Element

rawDescription: Get attribute of complex element using lxml


code:
ciphertext = b'SplitsEvenly'

blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext), keylength)]
# [b'Spl', b'its', b'Eve', b'nly']

transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)]
# [b'SiEn', b'ptvl', b'lsey']

rawDescription: Break bytes object into n equally sized blocks based on index


code: a + b

rawDescription: numpy array that is (n,1) and (n,)

description: Numpy array that is (n,1) and (n,)


rawDescription: using Python reduce over a list of pairs

description: Using Python reduce over a list of pairs


code: foo

rawDescription: How in Python check if two files ( String and file ) have same content?


rawDescription: Finding the local name of a module from within that module


code:
import pandas as pd
d = {'x': np.array([1,2,3,4,5]), 'h': np.array([4,5,6,7,8])}

a = pd.DataFrame(d)
a.to_csv("testfile.txt", sep="\t", index=False)

rawDescription: python dictionary to file

description: Python dictionary to file


code: result = [(a.split('-', 1)[0], b) for a, b in sorted_x]

rawDescription: Remove specific characters from list python


code:
import ipaddress
i = ipaddress.ip_address('10.9.8.7')
int(i)

rawDescription: Standard way to serialize and plot IP addresses?


code:
import lxml.html as LH
text = """
(999.1) Air embolism as
a complication of medical care not elsewhere classified
"""

doc = LH.fromstring(text)
for tag in doc.xpath('//li/a[2]'):
    print(tag.tail)

rawDescription: In Python BeautifulSoup4, How to extract the special text like this


code:
import sys

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

rawDescription: python/cgi - serves distorted images

description: Python/cgi - serves distorted images


code:
fields = {'option': 'ajax',
          'nologin': '1',
          'a': 'vmware_migrate_2',
          'original_server_ip': self.ip,
          'target_server_ip': dest_node.ip,
          'vmware_name': machine.name}

params = '&'.join(['{}={}'.format(k, v) for k, v in fields.items()])
self.class_logg('http://example.com/api/?{}'.format(params))

rawDescription: python log unexpectedly prints the indentation

description: Python log unexpectedly prints the indentation


code: 'Aadhirai' 'A special star' '6' 'Boy' '' " " 'Aadhiren' 'Dark' '6' 'Boy' '' 'Aadhish' 'King Commanded Counselled' '5' 'Boy' '' 'Aadhyatm' 'Dhyan' '1' 'Boy' '' 'Aadi' 'First Most important Beginning Ornament Adornment' '6' 'Boy' '' 'Aadia' 'Being a gift' '7' 'Boy' '' 'Aadidev' 'The first God' '1' 'Boy' '' 'Aadijay' 'The first victory' '6' 'Boy' '' 'Aadim' 'Entire universe' '1' 'Boy' '' 'Aadinath' 'The first Lord Lord Vishnu' '4' 'Boy' '' 'Aadipta' 'Bright' '7' 'Boy' '' 'Aadish' 'Full of wisdom Intelligent' '6' 'Boy' '' 'Aadishankar' 'Sri shankaracharya Founder of Adwaitha philosophy' '6' 'Boy' '' 'Aadit' 'Peak Lord of Sun' '8' 'Boy' '' 'Aaditey' 'Son of Aditi' '11' 'Boy' '' '     '

rawDescription: How to remove text in between \r's including \r from a text file?? And if any text contains \r in between ' ' that also should be removed

description: Remove text in between \r's including \r from a text file?? And if any text contains \r in between ' ' that also should be removed


code:
u'good'
b"also good"

rawDescription: whitespace is not allowed between stringprefix and bytesprefix?

description: Whitespace is not allowed between stringprefix and bytesprefix


code: np.apply_along_axis(sum, -1, A)

rawDescription: NumPy Vectorize a function, unknown shape


rawDescription: How to check if value is logically integer?

description: Check if value is logically integer


rawDescription: Getting the monthly maximum of a daily dataframe with the corresponding index value


code:
# still allow requests to hit just get/post/etc without invoking anything else
api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/')
api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/<task>/<path:args>/')

rawDescription: Flask-RESTful custom routes other than GET,PUT,POST,DELETE


code:
import matplotlib.pyplot as plt
import matplotlib as mpl
from prettyplotlib import brewer2mpl
import numpy as np
import prettyplotlib as ppl
np.random.seed(12)
fig, ax = plt.subplots(1)
fig.suptitle('fig title', size = 80)
ax.set_title('axes title', size = 50)
for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(60)
ax.set_ylabel("test y", size = 35)
for i in range(8):
    y = np.random.normal(size=1000).cumsum()
    x = np.arange(1000)
    ppl.plot(ax, x, y, label=str(i), linewidth=0.75)
ppl.legend(prop={'size':30})
fig.savefig('plot_prettyplotlib_default.png')

rawDescription: how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger

description: Make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger


rawDescription: Parsing a specific element from XML using Python/ET


rawDescription: Changing dtype of structured array zeros out string data


code:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands',
                                   description='valid subcommands',
                                   help='additional help')
subparsers.add_parser('foo')
subparsers.add_parser('bar')
parser.parse_args(['-h'])

rawDescription: How to conditionally make python's argparse module require additional arguments

description: Conditionally make python's argparse module require additional arguments


code:
parent_parser.add_argument('--verbose', '-v', action='store_true',
        help="Verbosity on")

child_parser = parent_parser.add_subparsers(title="subcommand",
        help="Subcommand help")
new_file_command = child_parser.add_parser('new', help="New text file")
edit_file_command = child_parser.add_parser('edit', help="Edit existing text file")

rawDescription: Create parser with subcommands in argparse, customize positional argument(s)


rawDescription: basic panda questions related to slicing and aggregating tables

description: Basic panda questions related to slicing and aggregating tables


code:
from multiprocessing import Pool
from cat import Cat
from dog import Dog
from rabbit import Rabbit

cat = Cat()
dog = Dog()
rabbit = Rabbit()

def run(animal):
    animal.worker_run()

pool = Pool(2)
pool.map(run, [cat, dog, rabbit])

rawDescription: How to control the maximum concurrently running processes?

description: Control the maximum concurrently running processes


code:
def combination(n, k):
    if k == 0 or k == n:
        return 1
    return combination(n - 1, k - 1) + combination(n - 1, k)

def pascals_triangle(rows):
    for row in range( rows):
        answer = ""
        for column in range( row + 1):
            answer = answer + str(combination(row, column)) + "\t"
        print(answer)

pascals_triangle(5)

rawDescription: Creating Pascal's Triangle using Python Recursion


code: lst1 = [[k] + v for k, v in dct1.iteritems()]

rawDescription: Function to convert List to Dictionary and viceversa using Python


code:
found_because_longer_than_two_chars = list()
found_because_shorter_than_two_chars = list()

for grp in s.split():
    if len(grp) > 2:
        found_because_longer_than_two_chars.append(grp[2:])
        print(grp[2:])
    elif len(grp) < 2:
        found_because_shorter_than_two_chars.append(grp)
        print(grp)

print(found_because_longer_than_two_chars)
print(found_because_shorter_than_two_chars)

rawDescription: How to parse this string?

description: Parse this string


code:
import numpy as np
import scipy.ndimage as ndimage
from PIL import Image

filename = '/tmp/PerformErosionUsingA2by2NeighborhoodExample_01.png'
img = Image.open(filename).convert('L')
arr = np.array(img)
def func(x):
    return (x==255).all()*255
arr2 = ndimage.generic_filter(arr, func, size=(2,2))
new_img = Image.fromarray(arr2.astype('uint8'), 'L')
new_img.save('/tmp/out.png')

rawDescription: Is there a Python equivalent to Matlab's makelut, applylut?


code:
data = np.array([1, 359, 1, 60, 359, 177, 2])  # mock-data
jumps = np.diff(data)<0  # assumptions: angle increases stricly monotonously CCW
np.hstack((data[0], data[1:] + np.cumsum(np.sign(d)<0)*360))

rawDescription: bounded circular interpolation in python

description: Bounded circular interpolation in python


rawDescription: Complicated referencing with dictionaries, python


code:
'''
    >>> py_to_pg([1,2,3])
    "'{1,2,3}'::int[]"
    >>> py_to_pg('Jack Johnson')
    "'Jack Johnson'::text"
    >>> py_to_pg([decimal.Decimal(0.3),decimal.Decimal(0.3),decimal.Decimal(0.4)])
    "'{0.3,0.3,0.4}'::numeric(5,4)[];"
    >>> py_to_pg(datetime.datetime(2013,7,7,13,0,0))
    "'2013-07-07T13:00:00'::timestamp"
    >>> py_to_pg(float(0.5))
    "0.5::numeric"
    >>> py_to_pg(5)
    "5::int"
    >>> py_to_pg(['a','b','c'])
    "'{a,b,c}'::text[]"
    >>> py_to_pg(None)
    "'NULL'"
    >>> py_to_pg(33.00)
    "'33.0000'::numeric(5,4)"
    >>> py_to_pg(True)
    "'T'"
'''
def py_to_pg(pyval):
    # set precision to 4 decimals out
    getcontext().prec = 4
    t2t = {int: "'%s'::int",
        str: "'%s'::text",
        Decimal: '%s::numeric(5,4)',
        float: '%s::numeric(5,4)'}
    if type(pyval) in t2t:
        return t2t[type(pyval)] % (str(pyval),)
    elif type(pyval) == datetime.datetime:
        return "'%s'::timestamp" % (pyval.isoformat(),)
    elif type(pyval) == list:
        if len(pyval) > 0 and type(pyval[0]) in t2t:
            # grab appropriate type
            beginning = "'{"
            for a in pyval:
                beginning += str(a) + ','
            return beginning[0:-1] + "}'::" + re.sub(r'.+::(.+)',r'\1[]',t2t[type(pyval[0])])
        elif type(pyval[0]) == datetime.datetime:
            converted = [a.isoformat() for a in pyval]
            return re.sub(r'\[([^\]]+)\]',r"'{\1}'::timestamp[]", converted)
        elif not type(pyval[0]) in t2t:
            raise TypeError('py_to_pg not yet supports ARRAY type %s' % (str(type(pyval[0])),))
        else: # return an empty array
            return '{}'
    elif type(pyval) == type(None):
        return 'NULL'
    elif type(pyval) == bool:
        return "'%s'" % (str(pyval)[0],)
    else:
        raise TypeError('py_to_pg not yet supports type ' + str(type(pyval)))

rawDescription: Python value conversion to string representation of postgres procedure parameter including type casting


code: data = data[(data.a1 < 5) & (data.b1 < 5) & (data.c1 < 5)]

rawDescription: Pandas filter and combine

description: Pandas filter and combine


code:
from subprocess import Popen, PIPE
IP = "1.2.3.4"
# do_ping(IP)
# The time between ping and arp check must be small, as ARP may not cache long
pid = Popen(["arp", "-n", IP], stdout=PIPE)
s = pid.communicate()[0]
mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
mac

rawDescription: Obtain MAC Address from Devices using Python


code: runningSum += 3.25 * np.nansum(rs) +  .75 * np.nansum(rs * rs)

rawDescription: Masked Numpy arrays much slower than normal numpy arrays


code:
class Navbar(tk.Frame): ...
class Toolbar(tk.Frame): ...
class Statusbar(tk.Frame): ...
class Main(tk.Frame): ...

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.statusbar = Statusbar(self, ...)
        self.toolbar = Toolbar(self, ...)
        self.navbar = Navbar(self, ...)
        self.main = Main(self, ...)

        self.statusbar.pack(side="bottom", fill="x")
        self.toolbar.pack(side="top", fill="x")
        self.navbar.pack(side="left", fill="y")
        self.main.pack(side="right", fill="both", expand=True)

rawDescription: Best way to structure a tkinter application

description: Structure a tkinter application


code:
function(1,2,3)
function(x=1, y=2, z=3)

rawDescription: python: is it possible to require that arguments to the functions are all keyword?

description: Python: is it possible to require that arguments to the functions are all keyword


code:
import csv

def getUniqueValues(seq):
    "Return sorted list of unique values in sequence"
    values = list(set(seq))
    values.sort()
    return values

def dataArray(data2d, rowIterField=0, rowLabel='', defaultVal=''):
    # get all unique unit and test labels
    rowLabels = getUniqueValues(key[rowIterField] for key in data2d)
    colLabels = getUniqueValues(key[1-rowIterField] for key in data2d)

    # create key-tuple maker
    if rowIterField==0:
        key = lambda row,col: (row, col)
    else:
        key = lambda row,col: (col, row)

    # header row
    yield [rowLabel] + colLabels
    for row in rowLabels:
        # data rows
        yield [row] + [data2d.get(key(row,col), defaultVal) for col in colLabels]

def main():
    with open('output.csv', 'wb') as outf:
        outcsv = csv.writer(outf)
        outcsv.writerows(dataArray(data, 0, 'unitnames'))

if __name__=="__main__":
    main()

rawDescription: Python: Writing to a csv file from a 'list' of {(tuples): value} dicts


code:
mock = unittest.mock.Mock()
print(mock.method())
print(mock.attribute.method(10, x=53))
mock.method_calls
mock.mock_calls

rawDescription: Mock: Tracking all Calls. Shell vs. program inconsistency


rawDescription: How to add names to a numpy array without changing its dimension?

description: Add names to a numpy array without changing its dimension


code:
def head(A) :
    for i in xrange(1,len(A)+1) :
        yield A[:i]

rawDescription: Elegant way to iterate over heads of lists in Python


code:
from types import ModuleType

class MyClass(ModuleType):
    ...

rawDescription: Use alias for a property in Python at module level


rawDescription: Python SQLITE3 SELECT query with datetime calculated string not working


code: checksum = sum(map(ord, data))

rawDescription: calculate hex checksum in python

description: Calculate hex checksum in python


rawDescription: UnicodeDecodeError: 'ascii' codec can't decode


code:
p2 = re.compile(r'[.-]\d{3,4}')
f = 'test.2014.712.x264.mp4'
matches = list(p2.finditer(f))
matches[-1].group(0)

rawDescription: Finding the index of the second match of a regular expression in python


code:
class A:
    def __delitem__(self, key):
        print(key)

rawDescription: Python slice with del statement

description: Python slice with del statement


rawDescription: Splitting using regex is giving unwanted empty strings


code:
import pandas as pd
df = pd.DataFrame(n,columns=['left','right'])
df

rawDescription: Convert numpy array to numpy record array


rawDescription: Python: trying to lower a string and remove non-alphanumeric characters aside from space


code:
#!/bin/env python

import os
import argparse

class MyParser(argparse.ArgumentParser):
    def format_help(self):
        help = super(MyParser, self).format_help()
        helplines = help.splitlines()
        helplines[0] += ' [FOO]'
        helplines.append('  FOO         some description of FOO')
        helplines.append('')    # Just a trick to force a linesep at the end
        return os.linesep.join(helplines)

parser = MyParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder
if opts[1]: print('You passed the strings %s' % opts[1])

rawDescription: python - Using argparse, pass an arbitrary string as an argument to be used in the script

description: Python - Using argparse, pass an arbitrary string as an argument to be used in the script


code:
pairs = [(p1[2], p2[2]) for p1, p2 in zip(list_of_tuples[:-1], list_of_tuples[1:])]

for v1, v2 in pairs:
    calc_gcd(v1, v2)

rawDescription: How to compare values in tuples in a list

description: Compare values in tuples in a list


code:
import random
for index in random.sample(xrange(len(vector)), y): # len(vector) is "x"
    vector[index] = 1

rawDescription: Picking subset in python and changing values of subset


code:
sql = 'SELECT ...'
data = { 'user_id' : 3 }
results = _sql_to_data(sql, data)

rawDescription: Python, SQLAlchemy pass parameters in connection.execute


code:
with open('customers.txt') as customers:
    sorted_no = {line.split(";")[0]:ind for ind, line in enumerate(customers,1)}

rawDescription: Assign values to dictionary by order they were added


rawDescription: convert a list of delimited strings to a tree/nested dict, using python

description: Convert a list of delimited strings to a tree/nested dict, using python


code:
from collections import namedtuple
RecordLayout = namedtuple('RecordLayout',['field1','field2','field3',...])
def process( aLine ):
    record = RecordLayout( aLine.split('\t') )
    ...

rawDescription: What is the best file parsing solution for converting files?


code: return myList2

rawDescription: Absolute value and adding to a list

description: Absolute value and adding to a list


code:
import re
Field= "In Field 'fieldname':(Value1) has changed from (1) to (2)"
OldValue, NewValue = map(int, re.findall(r'\((\d+)\)', Field))
OldValue
NewValue

rawDescription: Storing selected portion from the string in Variables in Python


code:
radio = driver.find_element_by_id("ContentPlaceHolder1_HitterRadioButton")
driver.execute_script("arguments[0].click();", radio)

rawDescription: How to select radio button with Selenium and Python

description: Select radio button with Selenium and Python


code:
regex = re.compile(r'\b[ABC]+\b')
regex.match('AACCD')  #No match
regex.match('AACC')   #match
regex.match('A')      #match

rawDescription: Python regex - Match words only containing A, B, or C


code:
new_listt = []
elem_0 = listt[0][0]

for i in range(len(listt)-1):
    if listt[i+1][0] != elem_0:
        new_listt.append(listt[i])
        elem_0 = listt[i+1][0]

#We have to also account for the last element
new_listt.append(listt[i+1])

rawDescription: List of tuples deletion

description: List of tuples deletion


code:
def newfunction(input1, input2):
    input1_map = {i: dict.fromkeys("ABCDE", 0) for i in input1}

    for row in input2:
        for i1 in set(row[0]):
            try:
                input1_map[i1][row[1]] += 1
            except KeyError:
                pass

    return [[i] + list(input1_map[i].values()) for i in input1]

rawDescription: Python nested loop comparing two lists and updating a dictionary


rawDescription: How to retrieve the list of models for model A which contains a foreign key to B?

description: Retrieve the list of models for model A which contains a foreign key to B


rawDescription: Range with floating point numbers and negative steps


rawDescription: Python- Function not accepting number as 2 numbers, despite it having a comma


code:
for game in tree.games[0].game[0:4]:
    print(lxml.objectify.dump(game))

rawDescription: How to print an Objectified Element?

description: Print an Objectified Element


rawDescription: Interpreting bytes received through serial port


code:
import pandas as p

df = p.read_csv("All_Links.csv")

i = 0
for i in df.index:
    try:
        url= df.ix[i]['MatchLink']
        #code process the data in the link
        #made sure that processing has finished
    except:
        # something broke, this row isn't processed decrease i
        i -= 1
        break

# Now write the rest of unprocessed lines to a csv file
df.iloc[i:].to_csv('All_links.csv', index=False)

rawDescription: Deleting row from CSV using python

description: Deleting row from CSV using python


code:
# select is sqlalchemy.sql.expression.select()
# each selected column was derived as column = table.c[reference].label(label_with_dot)

labels = [c.name for c in select.columns]
...
record = dict(zip(labels, row))

rawDescription: sqlalchemy+sqlite stripping column names with dots?

description: Sqlalchemy+sqlite stripping column names with dots


code:
from math import pi, hypot, sqrt
'''
Circle class using __getattr__, and __setattr__ (rename circle2)
'''

# __getattr__(self, name): Automatically called when the attribute name
#       is accessed and the object has no such attribute.
# __setattr__(self, name, value): Automatically called when an attempt is made to bind the attribute name to value.

class Circle:
    def __init__(self, x, y, r):
        self._intialized = False
        self.x = x
        self.y = y
        self.r = r
        self.area = pi * self.r * self.r
        self.circumference = 2 * pi * self.r
        self.distance_to_origin = abs(sqrt(self.x * self.x + self.y * self.y) - self.r)
        self._intialized = True

    def __setattr__(self, name, value):
        if name in ['_intialized']:
            self.__dict__[name] = value
            return
        if name in ['x', 'y']:
            if isinstance(value, int):
                print('we can set x,y')
                self.__dict__[name] = value
            else:  # value isn't an int
                raise TypeError('Expected an int for: {}'.format(name))
        elif not self._intialized:
            self.__dict__[name] = value

        elif name in ['area', 'circumference', 'distance_to_origin']:
            raise AttributeError('Cannot set attribute: {}'.format(name))

if __name__ == '__main__':

    circle = Circle(x=3, y=4, r=5)
    print('x:', circle.x)
    print('y:', circle.y)
    print('r:', circle.r)
    print('area:', circle.area)
    print('circumference:', circle.circumference)
    print('distance_to_origin:', circle.distance_to_origin)
    tests = [('circle.x = 12.3', "print('Setting circle.x to non-integer fails')"),
             ('circle.y = 23.4', "print('Setting circle.y to non-integer fails')"),
             ('circle.area = 23.4', "print('Setting circle.area fails')"),
             ('circle.circumference = 23.4', "print('Setting circle.circumference fails')"),
             ('circle.distance_to_origin = 23.4', "print('Setting circle.distance_to_origin fails')"),
             ('circle.z = 5.6', "print('Setting circle.z fails')"),
             ('print(circle.z)', "print('Printing circle.z fails')")]
    for test in tests:
        try:
            exec(test[0])
        except:
            exec(test[1])

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


rawDescription: Using for loop for downloading results from blast


code:
from itertools import chain
for line in chain(file1, file2):
   pass

rawDescription: In Python, how do I iterate over one iterator and then another?


code: open(config_path, encoding='utf-8')

rawDescription: I am losing unicode characters somewhere (Python3)


code: if health > 20: health = 20

rawDescription: Python: How to stop a variable from exceeding a value?


code:
def clear_a(x):
  x = []

def clear_b(x):
  while x: x.pop()

z = [1,2,3]
clear_a(z) # z will not be changed
clear_b(z) # z will be emptied

rawDescription: Python functions call by reference

description: Python functions call by reference


code:
import os
open_files = [open(f) for f in os.listdir(some_path) if os.path.isfile(f)]

rawDescription: Python - Opening successive Files without physically opening every one


code:
#!/usr/bin/env python3

json_dict = {
    "dict1": {
        "data1": "a",
        "data2": "b",
        "data3": "c",
        "data4": "d",
        "data5": "e"
    },
    "dict2": {
        "data1": "f",
        "data2": "g",
        "data3": "h",
        "data4": "i",
        "data5": "j"
    },
    "dict3": {
        "data42": "c",
        "data43": "g"
    }
}

def which_dict_key(value, dicts):
    '''
    Return a list of keys for a dictionary where the
    value dictionary for that key includes the value
    provided.
    '''

    return [key for key in dicts if value in dicts[key].values()]

if __name__ == '__main__':
    print(which_dict_key("j", json_dict))
    print(which_dict_key("c", json_dict))
    print(which_dict_key("q", json_dict))
    print(which_dict_key("g", json_dict))

rawDescription: Return dictionary name based on values

description: Return dictionary name based on values


code: where='A in {}'.format(vals)

rawDescription: read HDF5 file to pandas DataFrame with conditions

description: Read HDF5 file to pandas DataFrame with conditions


code: [item for item in iterable if condition]

rawDescription: What is an expression such as [d[k] for k in d] called?


code:
# test if this goes even faster once saving the vectorised overhead on matrix DIV
arr[:,:,0] = color[:,:,0] * ambient[:,:,0] / 255  # MUL remains INT, shall precede DIV
arr[:,:,1] = color[:,:,1] * ambient[:,:,0] / 255  #
arr[:,:,2] = color[:,:,2] * ambient[:,:,0] / 255  #
arr[:,:,3] = shine[:,:,0]                         # STO alpha

rawDescription: Python - Quick batch modification of PNGs


code:
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'Machine': pd.Series([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]),
                   'Date': pd.Series([datetime(2014, 8, 12),
                                      datetime(2014, 8, 13),
                                      datetime(2014, 8, 14),
                                      datetime(2014, 8, 15),
                                      datetime(2014, 8, 16),
                                      datetime(2014, 8, 12),
                                      datetime(2014, 8, 13),
                                      datetime(2014, 8, 14),
                                      datetime(2014, 8, 15),
                                      datetime(2014, 8, 16)]),
                   'TotalData': pd.Series([500, 600, 750, 150, 300,
                                           100, 200, 300, 100, 200])
                   })
df = df.reset_index(drop=True)
df = df.set_index(['Machine', 'Date'])
grouped_by_machine = df.groupby(level=[0])
df['PrevTotalData'] = grouped_by_machine['TotalData'].shift(1)
df['PrevTotalData'] = df['PrevTotalData'].fillna(value=0)

# Assuming here that the amount of data day after reboot is always less then
# the total amount of data in previous day
rebooted = df['PrevTotalData'] > df['TotalData']
df['DataBeforeLastReboot'] = 0
df.ix[rebooted, 'DataBeforeLastReboot'] = df['PrevTotalData']
df['DataBeforeLastReboot'] = grouped_by_machine['DataBeforeLastReboot'].cumsum()
df['TotalDataFixed'] = df['TotalData'] + df['DataBeforeLastReboot']
print(df)

rawDescription: Correcting cumulatives in Pandas

description: Correcting cumulatives in Pandas


code:
def checkIndividualButton(button_pin, led_pin):
    is_pressed = GPIO.input(button_pin)
    if is_pressed:
        GPIO.output(led_pin, not GPIO.input(led_pin))

def checkMasterButton(master_button_pin, monitor_led_pin, all_led_pins):
    is_pressed = GPIO.input(master_button_pin)
    if is_pressed:
        GPIO.output(monitor_led_pin, not GPIO.input(monitor_led_pin))
        time.sleep(0.1)
        GPIO.output(all_led_pins, GPIO.input(monitor_led_pin))
        time.sleep(0.4)

def updateMonitorLed(all_leds_pins, monitor_led_pin):
    is_any_led_on = False
    for led_pin in all_leds_pins:
        if GPIO.input(led_pin):
            is_any_led_on = True
    GPIO.output(monitor_led_pin, is_any_led_on)
    time.sleep(0.1)

rawDescription: LED control on Raspberry Pi by GPIO with Python


code: df['unique'] = df[['x','y','z']].T.apply(lambda x: x.nunique())

rawDescription: Getting stats about each row and putting them into a new column. Pandas


code: chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

rawDescription: Split a python list into other "sublists" i.e smaller lists


code: 'The produced output, in binary, is: {:#010b}'.format(14)

rawDescription: python convert to binary and keep leading zeros

description: Python convert to binary and keep leading zeros


code: child.logfile = open(path, "w")

rawDescription: I Wish to Save Configuration With System IP Address


code: import app.testingA

rawDescription: Python creating a module

description: Python creating a module


code:
import pandas as pd

df = pd.DataFrame(
    {'Component': ['Air conditioner', 'Air conditioner', 'airbag', 'engine with 150 H/P', 'airbag',
                   '1-year concierge assistance', 'ABS breaks', 'ABS breaks', 'airbag',
                   'air conditioner', 'engine with 250 H/P'],
     'Vehicle': ['Ford', 'Ford', 'Ford', 'Ford', 'Toyota', 'Toyota', 'Toyota',
                 'Chrysler', 'Chrysler', 'Chrysler', 'Chrysler']})

result = pd.crosstab(index=[df['Vehicle']], columns=[df['Component']]).clip(upper=1)
print(result)

rawDescription: vectorized implementation for pseudo pivot table in python

description: Vectorized implementation for pseudo pivot table in python


code:
list_of_lists = [['how to apply'],['a function'],['to each list?']]
map(len, list_of_lists)

rawDescription: How to apply a function to each sublist of a list in python?

description: Apply a function to each sublist of a list in python


code:
import yaml
from collections import OrderedDict

class literal(str): pass

def literal_presenter(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)

def ordered_dict_presenter(dumper, data):
    return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)

d_temp = OrderedDict(l=literal('hi\nif x = y:\n print z\n'))
d = OrderedDict(yaml=literal(yaml.dump(d_temp)))
print(yaml.dump(d))

rawDescription: Set format of string in PyYaml output file?


rawDescription: Pandas Dataframe GroupBy - Displaying Group Statistics


code:
class DummyLoggingPaymentProcessor (AbstractPaymentProcessor):
    """ Payment processor that does nothing, just logs """
    def __init__(self):
        self._logger = logging.getLogger(__name__)
        self._logger.setLevel(logging.INFO)
    def execute_payment(self, destination_address, amount):
        """ Execute a payment to one receiving single address

        return the transaction id or None """
        raise NotImplementedError("Not implemented yet")
    def execute_multi_payment(self, destination_addresses, amounts):
        """ Execute a payment to multiple receiving addresses

        return the transaction id or None """
        raise NotImplementedError("Not implemented yet")
    def get_transaction_status(self):
        """ Get the status of the transaction

        Indicate if transaction is already confirmed. Return
         - True if confirmed
         - False if unconfirmed
         - None if transaction doesn't exist """
        raise NotImplementedError("Not implemented yet")

c = DummyLoggingPaymentProcessor()

rawDescription: Python Abstract Base Classes: Why doesn't abc prevent instantiation?


code:
from collections import deque

class fringe(object):
    def __init__(self, kind= 'stack'):
        f= deque()
        self._p= f.append if kind is 'stack' else f.appendleft
        self._f= f

    def __call__(self, item):
        self._p(item)
        return self

    def __iter__(self):
        while len(self._f):
            item= self._f.pop()
            yield item

    def __repr__(self):
        return self._f.__repr__().replace('deque', 'fringe')

def paths(G, start, terminal, F= fringe()):
    for node, path in F((start, [start])):
        for node in G[node]:
            if node is terminal:
                yield path+ [terminal]
            elif node not in path:
                F((node, path+ [node]))

rawDescription: Python - Graph Data Structure - How Do I Implement Breadth-First Search to Find Reachable Vertices Correctly


code:
def both_ends(list):
    finalList = []
    for s in list:
        if len(s) > 4:
            finalList.append(s[:2] + s[-2:])
        else:
            finalList.append(s)
    return finalList

rawDescription: How do I loop through each string in my list?

description: Loop through each string in my list


code:
def extend(self, rs):
    curr = rs.front
    while curr is not None:
        self.insert(-1, curr._value)

def intersection(self, rs):
    if rs.front is None: return List()
    answer = self.intersection(rs.front._next)
    if rs.front._value in self: answer.insert(-1, rs.front._value)
    return answer

rawDescription: python-Linked list implemention

description: Python-Linked list implemention


code:
[k for k, v in child_parent.items() if v == 0]
[k for k, v in child_parent.items() if v == 2]

rawDescription: Create a list of keys given a value in a dictionary


rawDescription: Python 3.1- Grid Simulation Conceptual issue


code:
import json
fp = open('/tmp/mydict', 'w+')
json.dump(fp, myDict)

rawDescription: Converting a Python Dictionary into Associative Array for PHP


rawDescription: Spark: Use same OneHotEncoder on multiple dataframes


code:
for fname in os.listdir(path):
    print("\<description>Test. <![CDATA[<img src='./files/{}'>]]>=</description>\n".format(fname))

rawDescription: String formatting in a loop

description: String formatting in a loop


rawDescription: Writing numerical values on the plot with Matplotlib


code:
def make_key(my_tuple):
    return my_tuple[1], -my_tuple[0]

rawDescription: Sort a list of tuples with two tuple entries in opposite order


rawDescription: Code review - Simple Mnemonic generator in python


code:
from collections import defaultdict, Counter
d = defaultdict(Counter)

d[key][somestring] += 1

rawDescription: Pythonic way for checking if value exists in dictionary of dictionaries and taking corresponding actions


code:
from operator import mul
map(mul, list1, list2)

rawDescription: Python multiply 2 arrays

description: Python multiply 2 arrays


rawDescription: How to calc percentage of interval in array

description: Calc percentage of interval in array


code:
matches = re.findall(r'<VirtualHost>.*?</Virtualhost>', d, re.I|re.DOTALL)

#['<VirtualHost>\n  ServerName blah.com\n  DocumentRoot /var/www/blah.com\n</Virtualhost>',
# '<VirtualHost>\n  ServerName blah2.com\n  DocumentRoot /var/www/blah2.com\n</Virtualhost>']

rawDescription: Pull out content between two strings including strings


code:
import StringIO
template = StringIO.StringIO('''employee.id
employee.manager.first_name
employee.user.last_login
employee.contact.phone_number''')

rawDescription: Django/Jinja2 : Generate (data for) CSV via template syntax


rawDescription: replace URLs in text with links to URLs

description: Replace URLs in text with links to URLs


code:
d = {}
for i in range(5):
    user = input('Enter city followed by temperature')
    # use raw_input(prompt) if using Python 2.x
    data = user.split()
    d[data[0]] = int(data[1])

rawDescription: Adding entered items separated by spaces into a dictionary. Python


rawDescription: Python nested loop working with data file


code:
def parseTags(str):
    return filter(None, map(sanitizeTag, str.split(',')))

def sanitizeTag(str):
    words    = ''.join(c if c.isalnum() else ' ' for c in str).split()
    numWords = len(words)
    if numWords == 0:
        return None
    elif numWords == 1:
        return words[0]
    else:
        return words[0].lower() + ''.join(w.capitalize() for w in words[1:])

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code:
source = open("PALTemplateData.csv","rb")
reader = csv.reader(source , dialect)

target = open("AnotherFile.csv","wb")
writer = csv.writer(target , dialect)

rawDescription: Writing with Python's built-in .csv module


code:
import multiprocessing as mp

def worker(inq,outq):
    obj = inq.get()
    obj = obj[::-1]
    outq.put(obj)

if __name__=='__main__':
    inq = mp.Queue()
    outq = mp.Queue()

    p = mp.Process(target=worker, args=(inq,outq))
    p.start()

    inq.put('Fancy Dan')

    # Wait for the worker to finish
    p.join()
    result = outq.get()
    print(result)

rawDescription: python3 multiprocessing example crashed my pc :(

description: Python3 multiprocessing example crashed my pc :(


code:
from functools import reduce
reduce(lambda x,y:(x<<8)+y,list(b"Hello World"))
bin(_)

rawDescription: Working with bit streams

description: Working with bit streams


rawDescription: Detect and extract changing numbers in list of strings


code:
from operator import add
from collections import Counter

a = [('Blue', 1), ('Green', 1), ('Blue', 1), ('Blue', 1)]
b = reduce(add, [Counter(**{x[0]: x[1]}) for x in a])
# b contains:
# Counter({'Blue': 3, 'Green': 1})

rawDescription: From a dictionary with repeated values, how to create a new one excluding the repeats and incrementing a couter inside the dictionary?


rawDescription: Python Tkinter - get selection on Radiobutton


rawDescription: calling python method has no affect on client side with jinja2

description: Calling python method has no affect on client side with jinja2


code:
from django import forms

class RegisterForm(forms.Form):

    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    mobile = forms.CharField()
    company = forms.CharField(max_length=100)
    email = forms.EmailField()

    def clean_mobile(self):
        mobile = self.cleaned_data['mobile']
        rep = ['+', '-', ' ', '.']
        for i in rep:
            mobile = mobile.replace(i, '')
        return mobile

rawDescription: How to change this regular html form into django form?

description: Change this regular html form into django form


code: list(set([m2.model1 for m2 in Model2.objects.filter(user=user).all()]))

rawDescription: Django queryset: All Model1 objects where a Model2 exists with a model1 AND the given user


rawDescription: Plotting oceans in maps using basemap and python


rawDescription: Subclass' __getitem__ returns unexpected slice


code:
ADDRESS
STREET
STREET1
CITY
ZIP
PHONE
COUNTRY

rawDescription: Using lxml to extract data where all elements are not known in advance


code:
a.name, b.name = 'a', 'b'
xb = b.reset_index(level=-1).filter('b')
xa = a.reset_index()

rawDescription: pandas: vectorize counting rows in time interval

description: Pandas: vectorize counting rows in time interval


code:
from Tkinter import *
from PIL import Image, ImageTk, ImageDraw, ImageOps, ImageEnhance

class ImageButcher(Tk):
    def __init__(self):
        Tk.__init__(self)

        #create ui
        f = Frame(self, bd=2)

        self.colour = StringVar(self)
        self.colourMenu = OptionMenu(f, self.colour,
                                     *('red','green','blue','white'))
        self.colourMenu.config(width=5)
        self.colour.set('red')
        self.colourMenu.pack(side='left')

        self.rectangleButton = Button(f, text='Rectangle',
                                    command=self.draw_rectangle)
        self.rectangleButton.pack(side='left')

        self.brightenButton = Button(f, text='Brighten',
                                    command=self.on_brighten)
        self.brightenButton.pack(side='left')

        self.mirrorButton = Button(f, text='Mirror',
                                    command=self.on_mirror)
        self.mirrorButton.pack(side='left')
        f.pack(fill='x')

        self.c = Canvas(self, bd=0, highlightthickness=0,
                        width=100, height=100)
        self.c.pack(fill='both', expand=1)

        #load image
        im = Image.open('IMG_1584.JPG')
        im.thumbnail((512,512))

        self.tkphoto = ImageTk.PhotoImage(im)
        self.canvasItem = self.c.create_image(0,0,anchor='nw',image=self.tkphoto)
        self.c.config(width=im.size[0], height=im.size[1])

        self.img = im
        self.temp = im.copy() # 'working' image

    def display_image(self, aImage):
        self.tkphoto = pic = ImageTk.PhotoImage(aImage)
        self.c.itemconfigure(self.canvasItem, image=pic)

    def on_mirror(self):
        im = ImageOps.mirror(self.temp)
        self.display_image(im)
        self.temp = im

    def on_brighten(self):
        brightener = ImageEnhance.Brightness(self.temp)
        self.temp = brightener.enhance(1.1) # +10%
        self.display_image(self.temp)

    def draw_rectangle(self):
        bbox = 9, 9, self.temp.size[0] - 11, self.temp.size[1] - 11
        draw = ImageDraw.Draw(self.temp)
        draw.rectangle(bbox, outline=self.colour.get())
        self.display_image(self.temp)

app = ImageButcher()
app.mainloop()

rawDescription: Pixel Manipulation via GUI in Python (poss PIL, Tkinter)


code:
class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    children = relationship("Child", cascade="all", backref="parent")

class Child(Base):
    __tablename__ = 'child'

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

rawDescription: SQLAlchemy: Test if a relationship exists without actually loading it


code:
def minutes(string):
    pattern = re.findall(r'\d+', string)
    minutes_mul =  [a*int(b) for a,b in zip([60., 1., 1./60], pattern)]
    return sum(minutes_mul)

rawDescription: Python: converting Trip duration of h min sec and leave only minute count


code: ['Lorem Ipsum is simply dummy text.', "Lorem Ipsum has been the industry's standard"]

rawDescription: Regex returns text of every line with match, when text is inside variable


code:
alphabet =  range(10)
base = 10
dict((x*base**2+y*base+z,(x,y,z)) for x in alphabet
                                  for y in alphabet
                                  for z in alphabet )

description: Python construct a dictionary {0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 0, 2], 3: [0, 0, 3], ...,999: [9, 9, 9]}


code:
def withHandler(iterable):
    for x in iterable:
        yield x,get_handler(x)

rawDescription: Combine variable and for each loop python


rawDescription: Python NLTK - counting occurrence of word in brown corpora based on returning top results by tag


code:
def _secret():
    for ind, val in enumerate(infinite_counter()):
        if ind < start:
            continue

        if ind > end:
            break

        yield val

list(_secret())

rawDescription: Get list of subset from infinite generator in Python


rawDescription: pandas dataframe create new columns and fill with calculated values from same df

description: Pandas dataframe create new columns and fill with calculated values from same df


code:
from sympy import S, lambdify # I'm assuming "S" comes from sympy
import numpy as np

CreateMagneticFieldsList = None # stops a compile error about CreateMagneticFieldsList being undefined

exec("""def CreateMagneticFieldsList(dataToSave,equationString,DSList):

    expression  = S(equationString)
    numOfElements = len(dataToSave["MagneticFields"])

    #initialize the magnetic field output array
    magFieldsArray    = np.empty(numOfElements)
    magFieldsArray[:] = np.NaN

    lam_f = lambdify(tuple(DSList),expression,modules='numpy')
    try:
        # pass
        for i in range(numOfElements):
            replacementList = np.zeros(len(DSList))

            for j in range(len(DSList)):
                replacementList[j] = dataToSave[DSList[j]][i]

            try:
                val = np.double(lam_f(*replacementList))

            except:
                val = np.nan
            magFieldsArray[i] = val
    except:
        print("Error while evaluating the magnetic field expression")
    return magFieldsArray""")

list={"MagneticFields":[1,2,3,4,5]}

out=CreateMagneticFieldsList(list,"MagneticFields*5.1",["MagneticFields"])
print(out)

rawDescription: Lambdify works with Python, but throws an exception with Cython


code:
import statsmodels.api as sm
n = 1000
x = np.linspace( 0, 1, n )
y = np.random.randn( n ).cumsum( )
z = sm.nonparametric.lowess( y, x, return_sorted=False, frac=.05)

ax.plot( x, y, 'Blue', linestyle='--' )
ax.plot( x, z, color='DarkRed' )

rawDescription: Subtracting two interleaved, differently based time-series arrays with numpy?


code:
getStr = 'GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n'
request = IP(dst='www.google.com') / TCP(dport=80, sport=syn_ack[TCP].dport,
             seq=syn_ack[TCP].ack, ack=syn_ack[TCP].seq + 1, flags='A') / getStr
reply = sr1(request)

rawDescription: Python-Scapy or the like-How can I create an HTTP GET request at the packet level


code:
def alt(s, t):
    if not s:
        return t
    elif not t:
        return s
    else:
        return s[0] + t[0] + alt(s[1:], t[1:])

rawDescription: Return Alternating Letters in Two Strings of Different Lengths


code:
import ctypes

lib = ctypes.CDLL('imgtest.dll')

class ImageInfo(ctypes.Structure):
    _fields_ = (
        ('width', ctypes.c_int),
        ('height', ctypes.c_int),
        ('depth', ctypes.c_int),
    )

pImageInfo = ctypes.POINTER(ImageInfo)
pImage = ctypes.POINTER(ctypes.c_ubyte)

lib.get_image_info.argtypes = [pImageInfo]
lib.get_image_info.restype = ctypes.c_int

lib.get_image.argtypes = [pImage]
lib.get_image.restype = ctypes.c_int

imgnfo = ImageInfo()
lib.get_image_info(ctypes.byref(imgnfo))
w, h, d = imgnfo.width, imgnfo.height, imgnfo.depth

imgdata = (w * h * d * ctypes.c_ubyte)()
lib.get_image(imgdata)

from PIL import Image
img = Image.frombuffer('RGBA', (w, h), imgdata, 'raw', 'RGBA', 0, 1)

rawDescription: PIL's Image.frombuffer expected data length when using ctypes array


code:
class MyOwnReporter(TerminalReporter):
    ...

def pytest_configure(config):
    reporter = MyOwnReporter(config, sys.stdout)
    config.pluginmanager.register(reporter, 'terminalreporter')

rawDescription: Change the name of py.test tests

description: Change the name of py.test tests


code:
s = 'A,B,C'
['hello' + x for x in s.split(',')]

rawDescription: Best way to split a string into elements and concat each element with a common value?

description: Split a string into elements and concat each element with a common value


code:
def __unicode__(self):
    return self.mycolumnname

rawDescription: How to map values of a Django model column to a list?

description: Map values of a Django model column to a list


rawDescription: How to force genfromtxt read csv as record array?

description: Force genfromtxt read csv as record array


code:
def apply_mask(a, indices, axis):
    magic_index = [np.arange(i) for i in indices.shape]
    magic_index = np.ix_(*magic_index)
    magic_index = magic_index[:axis] + (indices,) + magic_index[axis:]
    return a[magic_index]

rawDescription: numpy 3d to 2d transformation based on 2d mask array

description: Numpy 3d to 2d transformation based on 2d mask array


code:
s = pd.Series("want want want dtype object".split())
s.value_counts()

rawDescription: How to plot a bar chart if the input data is of type list?

description: Plot a bar chart if the input data is of type list


code:
s = range(3)
s
from itertools import cycle
c = cycle(s)
c
[next(c) for i in range(10)]
c = cycle(['pS', 'mS'])
[next(c) for i in range(10)]

rawDescription: make a side_effect iterator loop over from "beginning to end" "over and over again"

description: Make a side_effect iterator loop over from "beginning to end" "over and over again"


code:
class Connector(TCPConnector):
    def _makeTransport(self):
        return Client(self.host, self.port, self.bindAddress, self,
                      self.reactor)

rawDescription: How do Twisted python Factory and Protocol interfaces work?


code:
viewed = aliased(Event, name='viewed')
mobile = aliased(Event, name='mobile')
qry = (session.query(viewed)
       .filter(viewed.Type == 'Viewed Tab')
       .outerjoin(mobile, and_(
           viewed.Session == mobile.Session,
           mobile.Type == 'Mobile View')
       )
       .filter(mobile.Session == None)
       )

rawDescription: SQLAlchemy - Select rows with the same column values, excluding those with values from different column


code:
from contextlib import contextmanager
from mock import Mock
import os

import django
from django.apps import apps
from django.db import connections
from django.conf import settings

if not apps.ready:
    # Do the Django set up when running as a stand-alone unit test.
    # That's why this module has to be imported before any Django models.
    if 'DJANGO_SETTINGS_MODULE' not in os.environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = 'kive.settings'
    settings.LOGGING['handlers']['console']['level'] = 'CRITICAL'
    django.setup()

    # Disable database access, these are pure unit tests.
    db = connections.databases['default']
    db['PASSWORD'] = '****'
    db['USER'] = '**Database disabled for unit tests**'

@contextmanager
def mock_relations(*models):
    """ Mock all related field managers to make pure unit tests possible.

    with mock_relations(Dataset):
        dataset = Dataset()
        check = dataset.content_checks.create()  # returns mock object
    """
    try:
        for model in models:
            model_name = model._meta.object_name
            model.old_relations = {}
            model.old_objects = model.objects
            for related_object in model._meta.related_objects:
                name = related_object.name
                model.old_relations[name] = getattr(model, name)
                setattr(model, name, Mock(name='{}.{}'.format(model_name, name)))
            model.objects = Mock(name=model_name + '.objects')

        yield

    finally:
        for model in models:
            old_objects = getattr(model, 'old_objects', None)
            if old_objects is not None:
                model.objects = old_objects
                del model.old_objects
            old_relations = getattr(model, 'old_relations', None)
            if old_relations is not None:
                for name, relation in old_relations.iteritems():
                    setattr(model, name, relation)
                del model.old_relations

rawDescription: Simplify Django test set up with mock objects


code:
df['new column'] = 0
mask = df['data column'] >= 3
df.loc[mask, 'new column'] = 1

rawDescription: Spreadsheet Manipulation Tricks w/ Python's Pandas


code:
class ContextTest(object):
    def __enter__(self):
        print('Enter')

    def __exit__(self, type, value, traceback):
        print('Exit')

def test():
    with ContextTest() as foo:
        print('Inside')
        return

rawDescription: Open file and with statement in Python

description: Open file and with statement in Python


code:
def valve_control(valve, use_value=False):
  if use_value:
    return ContextManagerOpenedValve(valve)
  else:
    return SomeFakeContextManager()

rawDescription: Tips on using the with statement in Python


code:
df['FF'] = np.where(df.any(axis=1), df.idxmax(axis=1), 'P')
df

rawDescription: Python - Pandas - create "first fail" column from other column data


code:
diff = X[np.newaxis, :, :] - U[:, np.newaxis, :]
D = np.einsum('jik,jkl,jil->ij', diff, T, diff)

rawDescription: Vectorizing code to calculate (squared) Mahalanobis Distiance


code: df = reduce(lambda left,right: pd.merge(left,right,on='Land_Use',how='outer'),dfs)

rawDescription: Merging DataFrames within a loop

description: Merging DataFrames within a loop


code: regexp = re.compile(r'\[(\d+)\] SERVICE NOTIFICATION: (.+)')

rawDescription: Return All Matching Lines in a Logfile

description: Return All Matching Lines in a Logfile


code:
class CSVLogger:
    def __init__(self, rec_queue, filename, f):
        self.rec_queue = rec_queue
        ## Filename specifications
        self.__file_string__ = filename
        self.csv_writer = csv.writer(f,  newline='', lineterminator='\n', dialect='excel')
    def write_something(self, msg):
        self.csv_writer(msg)

rawDescription: Accessing class file from multiple methods in Python


code:
item.description = unicode(variation.product)
item.options = variation.options_text()

rawDescription: How to break the item name and size in Django Cartridge cart page?

description: Break the item name and size in Django Cartridge cart page


code:
def rec_fac(n):
    if n == 1:
        return 1
    else:
        return sum([n for i in range(rec_fac(n-1))])

rawDescription: How can I make a "Recursive Factorial" without using multiplication?

description: Make a "Recursive Factorial" without using multiplication


code:
for ob_dict_obj in ob_dict_list:
    print(ob_dict)    # wrong!

rawDescription: how to create a new dictionary in for loop?

description: Create a new dictionary in for loop


code:
dist = (arr2.T.reshape((2, 2, 3)) - arr1.T).reshape((4, 3))
dist

rawDescription: Distance between numpy arrays, columnwise


code:
import re
# Windows supports both / and \
if os.path.altsep:
    sep=os.path.sep + os.path.altsep
else:
    sep=os.path.sep
pseps = re.compile('[%s]' % re.escape(sep))
pseps.split(os.path.relpath(path,base), 1)[0]

rawDescription: calling the indexed position of a string

description: Calling the indexed position of a string


code:
print (b.flags['OWNDATA'])  #False -- apparently this is a view
e = np.ravel(b[:, 2])
print (e.flags['OWNDATA'])  #True -- Apparently this is a new numpy object.

rawDescription: How can I tell if NumPy creates a view or a copy?

description: Tell if NumPy creates a view or a copy


code: si.imgdata = im.tostring()

rawDescription: Marshaling a Python PIL Image using SWIG


code:
p = Point(1, 2)
s = {p}
p.x = 3
assert p not in s
# ... even though ...
assert list(s)[0] == p

rawDescription: How to override operator "in" in set of objects of my own class(Point)?

description: Override operator "in" in set of objects of my own class(Point)


code:
mymod
mydir.mymod

rawDescription: how do python module variables work?

description: How do python module variables work


code:
import pandas as pd

data = {'Country': ['DE', 'DE', 'DE', 'DE', 'DE', 'US', 'US', 'US', 'US','US'],
    'Product': ['Blue', 'Blue', 'Blue', 'Blue','Blue','Green', 'Green', 'Green', 'Green','Green'],
    'Period': [1, 2, 3,5,6, 1, 2, 4, 5, 6]}

df = pd.DataFrame(data, columns= ['Country','Product', 'Period'])
print(df)
grouped = df.groupby(['Country','Product'])
result = grouped['Period'].apply(
    lambda x: x.loc[(x.diff() > 1).cumsum() == 0])
result.name = 'Period'
result = result.reset_index(['Country', 'Product'])
print(result)

rawDescription: How to filter a Dataframe based on a criteria using .shift()

description: Filter a Dataframe based on a criteria using .shift()


code:
docs_new = ['God is love', 'OpenGL on the GPU is fast']
X_new = count_vect.transform(docs_new)
predicted = clf.predict(X_new)

rawDescription: Text Categorization Python with pre-trained data


code:
(lambda s: 'cat' in s and 'dog' not in s)("CatBlablablaDog".lower())
(lambda s: 'cat' in s and 'dog' not in s)("blablaCatBlabla".lower())
(lambda s: 'cat' in s and 'dog' not in s)("Dog_blabla_Cat".lower())

rawDescription: RegExp Look for part but exclude If

description: RegExp Look for part but exclude If


code:
def sort_key(row):
    return row[2]

c2.sort(key = sort_key)

rawDescription: Sorting a list of lists in Python

description: Sorting a list of lists in Python


code: dist = lambda t1, t2: abs(complex(*t1) - complex(*t2))

rawDescription: python - filter minimum element for given condition

description: Python - filter minimum element for given condition


code:
def func(a):
    print("Hello")
foo = func
foo(1)

rawDescription: Dynamically name a function as the script, Python


rawDescription: Python apply grid on 2D data, save non empty grid cells in tree


code:
[[("id",20,"integer")],
 [("companyname",50,"text")],
 getproducts(),
 ...]

rawDescription: Partially flattening a list

description: Partially flattening a list


code:
class my_configuration(osv.osv_memory):
    _inherit = ['res.confi.settings']
    _columns = {
       'default_deadline' : fields.integer('Days per default', help="""Help field"""),
    }
    ...
    def set_default_deadline(self, cr, uid, ids, context=None):
        config = self.browse(cr, uid, ids)
        config = config and config[0]
        val = '%s' %(config.default_deadline) or '10'
        self.pool.geet('ir.config_parameter').set_param(cr,uid, 'key_value', val)
        return True

rawDescription: Set default duration in res_config

description: Set default duration in res_config


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

    def __html__(self):
        return self.value

rawDescription: Python short-hand for HTML insertion

description: Python short-hand for HTML insertion


code:
import hashlib
combined = hashlib.sha256()
combined.update(hashlib.md5('test1').digest())
combined.update(hashlib.md5('test2').digest())
combined.update(hashlib.md5('test3').digest())

rawDescription: Combine (3) 32-char hex hashes into a single unique 32-char hash?


code:
list(incremental_window([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))
list(incremental_window([1, 2, 3, 4]))
list(incremental_window([1, 2, 3, 4, 5, 6]))

rawDescription: Python grouping elements in a list in increasing size


code:
from scipy.optimize import curve_fit

# define function to fit
ffunc = lambda x, a, x0, s: a*exp(-0.5*(x-x0)**2/s**2)

# fit with initial guess a=100, x0=5, s=2
p, _ = curve_fit(ffunc, x, intList, p0=[100,5,2])

x0 = p[1] # location of the mean

# plot
plot(x, intList)
plot(x, ffunc(x, *p))
axvline(x0, color='r', ls='--')

rawDescription: Python : fit a curve to a list of integers


code: mylist[:] = [0 if x is None else 1 for x in mylist]

rawDescription: How to convert a list of elements into a list with 0 or 1

description: Convert a list of elements into a list with 0 or 1


code:
import Count
no_of_apples = Count.Count(1)
no_of_tennis_balls = Count.Count(5)
no_of_bananas = Count.Count(7)

rawDescription: Python references to references in python


code:
class parent(object):
    def __init__(self):
        findMe = "Here I am!"

rawDescription: How can one locate where an inherited variable comes from in Python?


code:
row = result.loc[~mask].sum()
row.name = 'Other'

rawDescription: pandas: how to aggregate a subset of groupby rows into a single row?

description: Pandas: how to aggregate a subset of groupby rows into a single row


code:
class Grouper(object):
    def __init__(self):
        self.count = 0
    def __call__(self, line):
        if is_event(line):
            self.count += 1
        return self.count

results_as_iterators = itertools.groupby(lines, Grouper())

rawDescription: How to collect data from a list into groups based on condition?

description: Collect data from a list into groups based on condition


code:
import hashlib
string_version = hashlib.md5(b'hello world').hexdigest()

rawDescription: How to translate from a hexdigest to a digest and vice-versa?

description: Translate from a hexdigest to a digest and vice-versa


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

import sys
from PyQt4 import QtCore
from PyQt4 import QtGui

class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)

        self.setIcon(QtGui.QIcon("icon.png"))

        self.iconMenu = QtGui.QMenu(parent)
        appabout = self.iconMenu.addAction("About")
        appexit = self.iconMenu.addAction("Exit")
        self.setContextMenu(self.iconMenu)

        # Remove this next line, it isn't needed
        #self.aboutdialog = QtGui.QWidget(parent)

        self.connect(appabout,QtCore.SIGNAL('triggered()'),self.showAbout)
        self.connect(appexit,QtCore.SIGNAL('triggered()'),self.appExit)

        # Remove this next line, it isn't needed
        #self.show()

    def showAbout(self):
        # Before showing the message box, disable the tray icon menu
        self.iconMenu.setEnabled(false)
        # Replace self.aboutdialog with the Python equivalent of null (0?)
        QtGui.QMessageBox.information(0, self.tr("About Tunarium"), self.tr("Your text here."))
        # Re-enable the tray icon menu
        self.iconMenu.setEnabled(true)

    def appExit(self):
        # Replace the next line with something that calls the QApplication's
        #   exit() or quit() function.
        #sys.exit()
        app.quit()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    # Tell the application not to exit when the last window is closed. This should
    # prevent the application from exiting when the message box is closed.
    app.setQuitOnLastWindowClosed(false)

    trayIcon = SystemTrayIcon()
    trayIcon.show()

    sys.exit(app.exec_())

rawDescription: PyQt application crashes after closing QMessagebox window


code:
from lxml import html
tree = html.fromstring(text)
[td.text for td in tree.xpath("//td")]

rawDescription: How can I parse HTML with html5lib, and query the parsed HTML with XPath?

description: Parse HTML with html5lib, and query the parsed HTML with XPath


code:
def f1(a, b):
    a[b] = (a.get(b) or 0) + 1
    return a

rawDescription: What is happening in this Python function?


code: m, id = your_function()

rawDescription: returning different datatypes from a function in python

description: Returning different datatypes from a function in python


rawDescription: Get the first element of each tuple in a list in Python


code: zip(listone, listtwo)

rawDescription: Average out two list Python3

description: Average out two list Python3


code:
class A:
    def f(self):
            pass
A.f.__get__(None, A)
A.f.__get__(A(), A)

rawDescription: Accessing function from class and from instance of this class


rawDescription: check for value in list of Pandas data frame columns

description: Check for value in list of Pandas data frame columns


code:
# Default dpi is 80
pyplot.savefig('matplotlib_xscale_linear.png', dpi=50, bbox_inches='tight')

rawDescription: What is the difference between 'log' and 'symlog'?


code:
class Mock(object):
    def __init__(self, mockThing, embedMock = True):
        self.abby = 30
        self.mocker = mockThing
        self.mockList = [mockThing, mockThing, 40]
        self.embeddedMock = None
        if embedMock is True:
            self.embeddedMock = Mock(mockThing, embedMock = False)

mockType = lambda x: x.__class__.__name__ == 'Mock'

subList = [100, 60, -2]
myList = [5, 20, [5, 12, 17], 30, {'hello': 10, 'goodbye': 22, 'mock': Mock(subList)}, -20, Mock(subList)]
myList.append(myList)

ty = TreeYielder(mockType)
for val in ty.run(myList):
    print(val, ty.currentLevel())

rawDescription: Recursively dir() a python object to find values of a certain type or with a certain value


code: lambda e, text=text:(handle_click(text), unshow_me(e))

rawDescription: Hide function not called

description: Hide function not called


code:
import dis
dis.dis(compile(r"sTable = sTable + '\n' + sRow", '<stdin>', 'exec'))

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code:
type(x.a)
type(x.b)
type(x.test)

rawDescription: Parse Python file to retrieve variables, values, function definitions


code:
data = np.random.rand(1000)
scipy.stats.kstest(data, lambda x: x)

rawDescription: Using Scipy's stats.kstest module for goodness-of-fit testing


code:
from google.appengine.api import mail

mail.send_mail(sender="Example.com Support <support@example.com>",
              to="Albert Johnson <Albert.Johnson@example.com>",
              subject="Your account has been approved",
              body="""
Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
""")

rawDescription: Python : send data of form to one email address


code:
{'contacted': {'ip-address': {'invocation': {'module_args': u'var=hostvars',
    'module_complex_args': {},
    'module_name': 'debug'},
   'var': {u'hostvars': {'group_names': ['group1', 'group2', 'group3'],
     'groups': {'group1': ['ip-address'],
      'all': ['ip-address'],
      'group2': ['ip-address'],
      'group3': ['ip-address'],
      'ungrouped': []},
     'inventory_hostname': 'ip/hostname',
     'inventory_hostname_short': 'hostname-short'}},
   'verbose_always': True}},
 'dark': {}}

rawDescription: How to run ansible module in python

description: Run ansible module in python


code: d = TestDict({"spam": "egg"}, custom_name="my_custom_dict")

rawDescription: Python: passing an optional named variable with *args **kwargs


code:
picklevars = {}
picklenames = ['object1', 'object2']
for picklename in picklenames:
    with open(pickle_name, 'r') as pickle_fp:
        picklevars[picklename] = cPickle.load(pickle_fp)

rawDescription: how to load pickled objects into a list of empty variables?

description: Load pickled objects into a list of empty variables


code: constant = mean(1 - arparams.sum())

rawDescription: How to get constant term in AR Model with statsmodels and Python?

description: Get constant term in AR Model with statsmodels and Python


code: department_assoc = db.relationship('UserDepartment', back_populates='user')

rawDescription: How to add value to join table with SQLAlchemy?

description: Add value to join table with SQLAlchemy


code: a = np.load('test')

rawDescription: How to save numpy masked array to file

description: Save numpy masked array to file


code:
def crawl(self,url,depthToGo):
    # call this method with depthToGo set to maxDepth
    self._listOfCrawled.add(url)
    text = crawler_util.textFromURL(url).split()
    for each in text:
        # if word not in index, create a new set, then add URL to set
        if each not in self._index:
            self._index[each] = set([])
        self._index[each].add(url)
    links = crawler_util.linksFromURL(url)
    # check if we can go deeper
    if depthToGo > 0:
        for i in links:
            if i not in self._listOfCrawled:
                # decrease depthToGo for next level of recursion
                self.crawl(i, depthToGo - 1)

rawDescription: Recursion in python web crawler

description: Recursion in python web crawler


code:
prob_sliced
totalHigh_sliced
IDs = np.unique(totalHigh_sliced)
IDs
counts

rawDescription: Group and summarize matrix by value

description: Group and summarize matrix by value


code:
class Size(Enum):

    small = 1
    medium = 2
    large = 3

    @classmethod
    def classify(cls, number):
        if number < 10:
            return cls.small
        elif number < 20:
            return cls.medium
        else:
            return cls.large

rawDescription: Python -- using function attributes as return values


code:
def walk_up(path,top):
    while True:
        yield path
        if path==top: raise StopIteration
        else: path=os.path.dirname(path)

found = None
for p in walk_up(os.path.dirname("/path/to/file.mp3"),"/"):
   p = os.path.join(p,target)
   if os.path.isfile(p):
      found = p
      break

rawDescription: Pythonic way to find the file with a given name closest to a specific directory location


rawDescription: Python and Numeric/numpy Array Slicing Behavior


code:
it = iter(x)
a = it.next()

rawDescription: Python 2: someIterator.next() vs. next(someIterator) :Python 3


code:
itemlist = ['foo', 'bar', 'baz']
{'postdata[{}]'.format(i): v for i, v in enumerate(itemlist)}
dict(('postdata[{0}]'.format(i), v) for i, v in enumerate(itemlist))

rawDescription: How to call all list items in a list based on item count

description: Call all list items in a list based on item count


code:
def process_request(self, request, client_address):
    self.finish_request(request, client_address)
    self.shutdown_request(request)

def finish_request(self, request, client_address):
    self.RequestHandlerClass(request, client_address, self)

rawDescription: Threaded BaseHTTPServer, one thread per request


code:
[section]
key = value
key2 = value2
key3 = value3

rawDescription: Python argparser. List of dict in INI

description: Python argparser. List of dict in INI


code:
if x != 0 or y == 0:
    somestuff_B

rawDescription: Python Pythonic way to organize/design if statements


rawDescription: How to partition dataframe rows into bins with calculations

description: Partition dataframe rows into bins with calculations


code:
def transform_incoming_json_item(item, things=[]):
    if isinstance(item, dict):    # <----
        item = [item]             # <----
    if isinstance(item, list):
        things.extend(process_thing(thing) for thing in item)
    return things

rawDescription: python instance-based type checking

description: Python instance-based type checking


rawDescription: Django Templates: Display a date only if it's in the future


code: {{ url_linktext|safe }}

rawDescription: I want to allow html in my own text but that text is being escaped


code:
import sublime_plugin

class ProjectVenvReplCommand(sublime_plugin.TextCommand):
    """
    Starts a SublimeREPL, attempting to use project's specified
    python interpreter.
    """

    def run(self, edit, open_file='$file'):
        """Called on project_venv_repl command"""
        cmd_list = [self.get_project_interpreter(), '-i', '-u']

        if open_file:
            cmd_list.append(open_file)

        self.repl_open(cmd_list=cmd_list)

    def get_project_interpreter(self):
        """Return the project's specified python interpreter, if any"""
        settings = self.view.settings()
        return settings.get('python_interpreter', '/usr/bin/python')

    def repl_open(self, cmd_list):
        """Open a SublimeREPL using provided commands"""
        self.view.window().run_command(
            'repl_open', {
                'encoding': 'utf8',
                'type': 'subprocess',
                'cmd': cmd_list,
                'cwd': '$file_path',
                'syntax': 'Packages/Python/Python.tmLanguage'
            }
        )

rawDescription: Sublime text3 and virtualenvs

description: Sublime text3 and virtualenvs


code:
def post(self):
    key = self.request.get('key')
    self.check_obj_property(key)
    # continue your logic

@db.transctional
def check_obj_property(key):
    obj = db.get(key)
    if obj.property:
        #it's set already continue with other logic
        return
    # Its not set so set it and increase once the counter.
    obj.property = True
    # Do something else also?
    obj.count += 1
    # Save of course
    obj.put()

rawDescription: Will this transaction method work?

description: Will this transaction method work


code:
if __name__ != '__main__':
    import sys
    import implementation
    sys.modules[__name__] = implementation

rawDescription: Creating Python Façade Package

description: Creating Python Façade Package


code:
atoms.extend(Element(group=16, valence=2, number=16, weight=32.066)
             for _ in range(50))

rawDescription: Is it possible to create unique instances that have the same input?


code:
# contrib.auth.backends.py

def get_user(self, user_id):
    try:
        return User.objects.get(pk=user_id)
    except User.DoesNotExist:
        return None

rawDescription: Get the user object from session

description: Get the user object from session


rawDescription: Python regex based split

description: Python regex based split


rawDescription: adding elements in nested lists

description: Adding elements in nested lists


code:
df["val"] = True
piv = df.pivot("name", "tag", "val").fillna(False)
piv

rawDescription: Denormalizing a column to a boolean matrix in Pandas?


code:
def natatime_no_itertools(itr, fillvalue=None, n=2):
  x = iter(itr)
  for item in x:
    yield (item,) + tuple(next(x, fillvalue) for _ in xrange(n-1))

rawDescription: reading lines 2 at a time

description: Reading lines 2 at a time


code:
titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]
match = dict(zip(key,titles))
for  d in data_file:
    for k in key:
        val = d[k]
        if isinstance(val, int):
            val = "{:,}".format(val)
        print("{}: {}".format(match[k], val))

rawDescription: how to format only the numbers of items in a loop python

description: Format only the numbers of items in a loop python


code:
l = [5, 10, 25, 33, 6, 8, 19]
zmax = 15
[l[idx-1] if (ent > zmax) and (idx > 0) else ent for idx, ent in enumerate(l)]

rawDescription: pythonic way to replace values in an array over a limit with neighbour's value

description: Pythonic way to replace values in an array over a limit with neighbour's value


code:
o=open("output.txt","w")
for line in open("file"):
    s=line.split(",")
    s[0]="1"
    o.write(','.join(s))
o.close()

rawDescription: Replace a word in a file

description: Replace a word in a file


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
def paragraphs(self):
    if self._paragraphs is not None:
        for p in  self._paragraphs:
            yield p
    else:
        raw_paras = self.raw_text.split(self.paragraph_delimiter)
        gen = (Paragraph(self, p) for p in raw_paras if p)
        self._paragraphs = []
        for p in gen:
            self._paragraphs.append(p)
            yield p

rawDescription: nltk sentence tokenizer, consider new lines as sentence boundary

description: Nltk sentence tokenizer, consider new lines as sentence boundary


code:
all(x < 10 for x in range(10))
all(x < 9 for x in range(10))
all(map(lambda x: x < 9, range(10)))
all(map(lambda x: x < 10, range(10)))

rawDescription: Functional Python with Lists

description: Functional Python with Lists


code:
df = pd.read_csv('a.csv',dtype={'Date':pd.datetime,'Name':str})
df
df.groupby(['Name']).max()

rawDescription: Pandas - min of a column for each value in other


rawDescription: Random platform generator in pygame

description: Random platform generator in pygame


code:
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = '/simplehttpwebpage_content.html'
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

Handler = MyRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)

server.serve_forever()

rawDescription: A simple website with python using SimpleHTTPServer and SocketServer, how to only display the html file and not the whole directory?


code:
from collections import Counter
lst = [1, 2, 2, 2, 3, 4, 4]
counter = Counter(lst)
counter
counter[1]
counter[2]
counter[3]
counter[4]

rawDescription: Creating a dictionary that maps an object to the amount of times it occurs in a list? In Python


code:
data = {'password': SOME_PASSWORD}
requests.post(url, data=data)

rawDescription: How to send a post request with data using python requests module?

description: Send a post request with data using python requests module


code:
d = {}
#Considering you've a list of all `gzip` files to be opened.
for readfilename in filenames:
    #populate the dictionary by collecting data from each file
    with gzip.open(readfilename, 'r') as f:
        for line in f:
            city, temp = line.split()
            d.setdefault(city, []).append(temp)

#Now write to the output file
with open(outFileName, 'w') as f:
    for city, values in d.items():
       f.write('{} {}\n'.format(city, ' '.join(values)))

rawDescription: Python: append last word from lines in input file to to end of lines of output file


code:
l = []
for r in range(10):
    def foo(r = r):
        return r
    l.append(foo)

for f in l:
    print(f())

rawDescription: Is there a Pythonic way to close over a loop variable?


code:
try:
    import foo_gui
    foo_gui.main()
except ImportError:
    import foo_cli
    foo_cli.main()

rawDescription: How can I create a GUI on top of a Python APP so it can do either GUI or CLI?

description: Create a GUI on top of a Python APP so it can do either GUI or CLI


code: imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')

rawDescription: figure of imshow() is too small

description: Figure of imshow() is too small


code:
import random
def randlists(n, start, to):
    return [[random.randint(start,to) for i in range(n)] for i in range(n)]

print(randlists(3,1,9))

rawDescription: Issue filling a list with other lists containing random numbers.


code:
import pytest

numbers = [1,2,3,4,5]
vowels = ['a','e','i','o','u']
consonants = ['x','y','z']

@pytest.fixture(params=numbers)
def number(request):
    return request.param

@pytest.fixture(params=vowels)
def vowel(request):
    return request.param

@pytest.fixture(params=consonants)
def consonant(request):
    return request.param

def test(number, vowel, consonant):
    pass

rawDescription: pytest: parameterized test with cartesian product of arguments

description: Pytest: parameterized test with cartesian product of arguments


rawDescription: Changing an input from an integer to a string back to an integer


code:
import pytz
import twitter

from datetime import  datetime
from dateutil.tz import tzoffset

USERNAME = 'ttytter'

api = twitter.Api()

# get a 'tzinfo' instance with the UTC offset for the user's local time
user = api.GetUser(USERNAME)
localtime_tz = tzoffset(user.time_zone, user.utc_offset)

statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
    # get UTC timestamp from seconds since epoch
    utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
    print('utc: {}'.format(utc_dt))
    # convert to local time in the user's timezone
    localtime_dt = utc_dt.astimezone(localtime_tz)
    print('localtime [{}]: {}'.format(localtime_dt.tzname(), localtime_dt))

rawDescription: Using python-twitter library, how to set timezone?


code:
def polyval2d(x, y, m):
    order = int(np.sqrt(len(m))) - 1
    ij = itertools.product(range(order+1), range(order+1))
    z = np.zeros_like(x)
    for a, (i,j) in zip(m, ij):
        z = z + a * x**i * y**j
    return z

rawDescription: Fitting a polynomial function for a vector field in python


code:
#!/usr/bin/env python

from functools import wraps

def retry_on_error(ntries=1):
    """
    A decorator that returns a wrapper function that calls
    the wrapped function repeatedly up to ntries if an
    exception is encountered.
    """

    def decorator(f):  # wrapping the original function
        @wraps(f)  # make the wrapped function look like the original
        def wrapper(*args, **kwargs):  # our function wrapped that calls the original
            for i in xrange(ntries):
                try:
                    return f(*args, **kwargs)
                except Exception as e:
                    print("Error executing {0:s} retrying {1:d}/{2:d}".format(f.__name__, i, ntries))
                    print("Error was {0:s}".format(e))

        return wrapper

    return decorator  # returning the new wrapped function

@retry_on_error()
def f():
    n = getattr(f, "n", 0)
    try:
        if not n:
            raise ValueError("n < 0")
    finally:
        setattr(f, "n", n + 1)

rawDescription: How to call code inside try block one more time if exception is thrown?

description: Call code inside try block one more time if exception is thrown


rawDescription: Parse a text file in an array python

description: Parse a text file in an array python


code:
earliest_by_id = DF.groupby('id')['date'].min()
def since_earliest(row):
    return row.date - earliest_by_id[row.id]

DF['days_since_earliest'] = DF.apply(since_earliest, axis=1)
print(DF)

rawDescription: split, groupby, combine in Pandas to find a difference in dates

description: Split, groupby, combine in Pandas to find a difference in dates


code:
import random
random.choice([x for x in range(5000, 5200) if not [t for t in range(2, x) if not x % t]])

rawDescription: Creating only one random prime number in provided range


code:
def foo(a, b, c='Hello', d='World'):
    print(a,b,c,d)

rawDescription: the connection between django project's urls.py and views.py

description: The connection between django project's urls.py and views.py


rawDescription: Filter not in Python

description: Filter not in Python


rawDescription: How do I append values from a row in a CSV file into a list in python?

description: Append values from a row in a CSV file into a list in python


code: rgb_int = rgb_tuple[0] << 16 | rgb_tuple[1] << 8 | rgb_tuple[2]

rawDescription: RGB Tuples to RGB Integers

description: RGB Tuples to RGB Integers


code:
def fn(N):
    result = []
    if isinstance(N, list):
        for i in N:
            G = []
            for j in range(1,i+1):
                if not i%j and i >= j:
                    G.append(j)
            result.append(G)
    return result

rawDescription: Storing a list of results in a list

description: Storing a list of results in a list


code:
name = raw_input('Whats your name?') #With = operator

for name in [raw_input('Whats your name?')]: pass  #Without = operator

rawDescription: Counting from 1 to infinity without assignment


code:
import nt
nt.environ

rawDescription: Why python uppercases all environment variables in windows


code:
def encryptMessage(secretMsg):
    secretMsg = str(secretMsg)
    u = secretMsg.upper()
    symbol = "^"
    for x in secretMsg:
        if u in secretMsg:
            return u.lower() + symbol # Your function stops here b/c return
            secretMsg += x
        return secretMsg # Use print() to display, return will stop your function.
        # Nothing below here is executed because of the return above.
        if u.lower(): # This is always True unless u is empty.
            return secretMsg # Function will then stop here.
        elif 1 in secretMsg: # This will raise an error, make that 1 a string
            return secretMsg.replace(1, "@") # Same here
        elif 2 in secretMsg: # here
            return secretMsg.replace(2, "#") # here
        elif 3 in secretMsg: # here
            return secretMsg.replace(3, "$") # and here
        num = u > 3 # This will return True if u > 3 or False if u <= 3, not any number greater than u.
        if num in secretMsg:
            return secretMsg.replace(num, "*")
    return secretMsg

rawDescription: Message "encryption" through a set of given rules returns incomplete result


code:
sentiment_analyzer.analyze('player')
Sentiment(polarity=0.0, subjectivity=0.0)

sentiment_analyzer.analyze('bad player')
Sentiment(polarity=-0.6999998, subjectivity=0.66666)

sentiment_analyzer.analyze('worst player')
Sentiment(polarity=-1.0, subjectivity=1.0)

sentiment_analyzer.analyze('best player')
Sentiment(polarity=1.0, subjectivity=0.3)

rawDescription: Why is not TextBlob using / detecting the negation?


code: Test.prop.__get__(t, Test)

rawDescription: Built-in function to read __slots__

description: Built-in function to read __slots__


code:
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(300,300),'RGB')
cam.start()

image = cam.get_image()
print = cam.get_size()
img_str = pygame.image.tostring(img,"RGB")

host='192.168.0.11'
port=8080

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))

s.sendall(img_str)
s.close

rawDescription: Sending Webcam feed via socket

description: Sending Webcam feed via socket


code:
str.ljust
str.rjust
str.center

rawDescription: python create method object for string.Method

description: Python create method object for string.Method


rawDescription: How to combine tags in pandas dataframe using str.format?

description: Combine tags in pandas dataframe using str.format


code:
class Test(ctypes.Structure):
    _fields_ = [('size',ctypes.c_int),
                ('arr',ctypes.c_byte*0)]

rawDescription: does python ctypes supports size-0 array?

description: Does python ctypes supports size-0 array


rawDescription: Installing Python JSON library onto webserver


rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


code:
import itertools
lst1 = [1,2,3,4]
lst2 = [5,6,7]
itertools.izip_longest(reversed(lst1), reversed(lst2))
list(itertools.izip_longest(reversed(lst1), reversed(lst2)))
map(list, itertools.izip_longest(reversed(lst1), reversed(lst2)))

rawDescription: Iterate through 2 lists with different length in reverse order


code:
keys = {'c', 'd', 'e'}
[{k: d[k] for k in d.viewkeys() & keys} for d in List]

rawDescription: How to iterate over particular keys in a dict to get values

description: Iterate over particular keys in a dict to get values


code:
def rare(x):
    size = x['size']
    y = x.values[:-1]
    ...

rawDescription: Pandas apply with argument that varies by row


code:
import re

s = "sdfsdsf3.657ddsfdsfdsfdsd-12dfdsfsdfsd-67.34fdsfsfss"
re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", s)

rawDescription: Grep numbers from a string

description: Grep numbers from a string


code:
import hashlib
df['survey_id'] = (df.employee_id + df.customer_id + df.timestamp).apply(
    lambda s: hashlib.md5(s).digest().encode('base64')[: 10])

rawDescription: Creating a unique value per row in pandas?


rawDescription: Storing multiple get.arguments in a dict


code:
from selenium import webdriver

"""There are actually several options here,
   choose the one you like most
   (you need the browser to be installed in your pc)"""
browser = webdriver.Firefox()  # Your browser will open, Python might ask for permission
browser.get(url)               # This might take a while

# And than you can keep working from here
cart_style = browser.find_element_by_id('add_to_cart').get_attribute('style')
oos_style = browser.find_element_by_id('oosHook').get_attribute('style')

rawDescription: Python scrape style display:none

description: Python scrape style display:none


code:
import random
myvar = random.choice("special_value", "another_value")

rawDescription: python: simple way to input python data from file

description: Python: simple way to input python data from file


rawDescription: list of branches sorting

description: List of branches sorting


code:
inputFile = open(path,'r')
head_lines = 4
for n, line in enumerate(inputFile):
    if n > head_lines:
       cols = line.split()
       if len(cols) == 9:
           variableX = cols[7]
           # do whatever you need with variableX
inputFile.close()

rawDescription: Open txt file, skip first lines and then monitor a given column of data


rawDescription: Python equivalent for MATLAB's normplot?

description: Python equivalent for MATLAB's normplot


code:
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)

rawDescription: Best way to strip punctuation from a string in Python

description: Strip punctuation from a string in Python


rawDescription: how to make a formated print of list with list within it in python

description: Make a formated print of list with list within it in python


code:
from functools import wraps
from flask import Flask

app = Flask(__name__)

def register(app, rule, **options):
    def wrapper(f):
        print('Definition time')
        endpoint = options.pop('endpoint', f.__name__)
        access_groups = options.pop('access_groups', None)
        methods = options.pop('methods', ['GET'])

        @wraps(f)
        def wrapped(*args, **kwargs):
            print('Runtime')
            return f(*args, **kwargs)

        app.add_url_rule(rule, endpoint, wrapped, **options)
        return wrapped

    return wrapper

@register(app, '/', methods=['GET', 'POST'], access_groups=['all-access'])
def index():
    return 'index'

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: Flask function decorator run at defintion time and call time?


code:
def A():
    return input('What Are Your Commands?\n=>')
def B():
    print('Error 5:Access Is Denied!')

while True:
    u = A()
    if u == 'admin_name':
        B()
    elif u == 'admin_familyname':
        B()
    elif u == 'admin_fullname':
        B()
    elif u == 'admin_age':
        B()
    elif u == 'hello':
        print('Hello, My Friend')

rawDescription: Repeating a part of code in python 3.4.4


code:
# foo.py
setting1 = 0
setting2 = 'foo'

def configure(config1, config2):
    global setting1, setting2

    setting1 = config1
    setting2 = config2

rawDescription: Python: What is the recommended way to set configuration settings for a module when you import it?


code:
alist = [(0.7897897,'this is a foo bar sentence'),
(0.653234, 'this is a foo bar sentence'),
(0.353234, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar'),
(0.323234, 'this is a foo bar sentence'),]

seen = set()
out = []
for a,b in alist:
    if b not in seen:
        out.append((a,b))
        seen.add(b)

rawDescription: How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?

description: Remove element from a list of tuple if the 2nd item in each tuple is a duplicate


code:
"""
>>> from packagename import module
>>> module.show_real_world_usage()
'Hello world!'
"""

rawDescription: Python doctest: Skip entire block?

description: Python doctest: Skip entire block


rawDescription: IPython nbconvert output pdf without In[#] words


rawDescription: How do I check what platform (OS) im running in Python 2.7?

description: Check what platform (OS) im running in Python 2.7


code:
import collections

# I used variable "input" to hold the string from your example .tsv contents;
# you'd really want to read it in from a file.

D = collections.OrderedDict()
for line in input.splitlines():
    key, value = line.split('\t')
    if key not in D:
        D[key] = []
    D[key].append(value.strip())

for key, values in D.items():
    print(key, ','.join(values), sep='\t')

rawDescription: read multiple lines from one TSV file and based on column append data with comma

description: Read multiple lines from one TSV file and based on column append data with comma


code: df1.drop(['Start Date', 'End Date'], axis='columns', inplace=True)

rawDescription: How to find the number of days between two dates for dataframe manipulation

description: Find the number of days between two dates for dataframe manipulation


rawDescription: Split list into chunks by condition

description: Split list into chunks by condition


code:
[uniform(lower_limit, upper_limit) if i > some_value else i
 for i in Z]

rawDescription: Replace values in a 2D array with different random numbers


code:
class Pruefer(namedtuple("Pruefer", "ident maxNum name")):
    def __new__(cls, ident, maxNum=float('inf'), name=""):
        return super(Pruefer, cls).__new__(cls, ident, maxNum, name)

Pruefer(1)

rawDescription: Python: Quick and dirty datatypes (DTO)

description: Python: Quick and dirty datatypes (DTO)


code:
from scipy import interpolate
f = interpolate.interp2d(x, y, gx, kind='cubic')
results = f(cx, cy)

rawDescription: Getting scalar values of z2(x,y) numpy array along a contour defined by a coordinate list


code:
seqs = [ ''.join(motif) for motif in motifs ]
bc   = best.count(bseq)+1
profilte.extend([ map(lambda x: bc / float(len(x)),
    seq) for base in 'ACGT' ] for seq in seqs)

rawDescription: How to break down an expression into for-loops

description: Break down an expression into for-loops


code:
for n4 in range(0, 22):
   ...
   if (add >= limit):
      break

rawDescription: Very slow python running time when trying to solve project Euler. Unsure if python or slow algorithm


rawDescription: When loading a dll in Python does the dir function shows its methods?


code:
import json

with open('config.json') as jsonf:
    config = json.loads(jsonf.read())

WAIT_FIXED=int(config['WAIT_FIXED'])
STOP_MAX_ATTEMPT_NUMBER=int(config['STOP_MAX_ATTEMPT_NUMBER'])

rawDescription: Dynamic parameters with Python's retry decorator


code:
def ProcessRawData(RawData):
    if len(RawData) == 114733:
        return RawData[1:-44].reshape(-1, 32)
    return None

rawDescription: High-speed alternatives to replace byte array processing bottlenecks


code:
from django.http import HttpResponse

def some_view(request):
    if request.REQUEST.get('key') == 'value':
        if request.META.get('REMOTE_USER', None):
            do_something()
        else:
            response = HttpResponse('Text to send if user hits Cancel button', status=401)
            response['WWW-Authenticate'] = 'Basic realm="My Realm'
            return response
        ...

rawDescription: Python/Django - HTTP authentication

description: Python/Django - HTTP authentication


Resetting csv.DictReader(StringIO.StringIO(some_string))


code:
dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] }
max(dictionary, key=lambda key: dictionary[key][0])
max(dictionary, key=lambda key: dictionary[key][1])

rawDescription: Get most frequent item in python dictionary given frequencies


code:
for ind, line in enumerate(l):
    l[ind] = ";".join(line.split())
print(l)

rawDescription: insert a character into a list in python

description: Insert a character into a list in python


rawDescription: numpys argsort, sorting column based on another one

description: Numpys argsort, sorting column based on another one


rawDescription: When will numpy copy the array when using reshape()


code:
class Comprehension(object):
    def __init__(self, iterable):
        self._iterable = iterable

    def __iter__(self):
        return iter(self._iterable)

    def __getattr__(self, name):
        return Comprehension(getattr(elt, name) for elt in self._iterable)

    def __getitem__(self, item):
        return Comprehension(elt[item] for elt in self._iterable)

    def __call__(self, *args, **kwargs):
        return Comprehension(elt(*args, **kwargs) for elt in self._iterable)

rawDescription: How to get a vector from a list in list in python?

description: Get a vector from a list in list in python


code:
import regex
a = "aoooaoooa"
b = "aoooabbba"
rx = r"a(.{1,3})a(?1)a"
print(regex.search(rx, a).group(0))
print(regex.search(rx, b).group(0))
print(regex.search(rx, "abacca").group(0))

rawDescription: How to match length of variable size backreference but not content

description: Match length of variable size backreference but not content


code: lower = mid +1

rawDescription: Python number guessing game

description: Python number guessing game


rawDescription: __init__ argument mismatch between super and subclass


code: np.array([np.amax(row) for row in A])

rawDescription: Whats the best way to iterate over multidimensional array and tracking/doing operations on iteration index


code:
class CharSeq:
    def __init__(self, first, last):
        self.first = ord(first)
        self.last = ord(last)
    def __iter__(self):
        return (chr(i) for i in xrange(self.first, self.last+1))

set(CharSeq('a', 'c'))

rawDescription: Operator Overloading Python

description: Operator Overloading Python


code:
for k,v in newList.items():
    print(k,v)

rawDescription: Python - Access contents of list after applying Counter from collections module


code: ax.plot_surface(x, y, z,  rstride=1, cstride=1, facecolors=cm.jet(norm(colorfunction)))

rawDescription: Normalizing Colormap Used by Facecolors in Matplotlib


code:
['duck', 'goose', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose']
['duck', 'goose', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose']
['a', 'b', 'a', 'c', 'a', 'b', 'a', 'c', 'a', 'a']

rawDescription: Sorting a string in array, making it sparsely populated


code:
from collections import defaultdict
D = lambda: defaultdict(D)
d = D()
set_val(d, ['k1', 'k2', 'k3'], "hi")
d
d['k1']['k2']['k3']

rawDescription: Pythonic way of accessing recursively nested dict