code:
class GDataQuery(gdata.contacts.client.ContactsQuery):
    """
    ContactsQuery class to accept alt parameter
    """

    def __init__(self, domain=None, auth_token=None, **kwargs):
        super(GDataQuery, self).__init__(domain, auth_token, **kwargs)
        self.alt = 'json'
        self.max_results = 1000

    def modify_request(self, http_request):
        if self.group:
            gdata.client._add_query_param('group', self.group, http_request)
        if self.orderby:
            gdata.client._add_query_param('orderby', self.orderby, http_request)
        if self.sortorder:
            gdata.client._add_query_param('sortorder', self.sortorder, http_request)
        if self.showdeleted:
            gdata.client._add_query_param('showdeleted', self.showdeleted, http_request)
        if self.alt:
            gdata.client._add_query_param('alt', self.alt, http_request)

        gdata.client.Query.modify_request(self, http_request)

rawDescription: Use Google Contacts library (gdata) to fetch json response?


code: min(colors, key=difference_func)

rawDescription: Python find closest match out of list

description: Python find closest match out of list


code: atoms = [Hydrogen(), Hydrogen(), Oxygen(), Oxygen()]

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


rawDescription: Python: Appending to a list in a dictionary


code: table_row = '{label:<{lwidth}} {row[0]:<{cwidth}} {row[1]:<{cwidth}} {row[2]:<{cwidth}} {row[3]:<{cwidth}}'

rawDescription: Formatting output python

description: Formatting output python


rawDescription: How to get the values from a NumPy array using multiple indices

description: Get the values from a NumPy array using multiple indices


code:
foo: one
bar: ten

rawDescription: substitute of function pointers in python

description: Substitute of function pointers in python


code:
num_x_steps = 3
num_y_steps = 5
x, y = np.mgrid[0:1:(num_x_steps * 1j), 0:2:(num_y_steps * 1j)]

rawDescription: How do I insert variable step into Numpy mgrid?

description: Insert variable step into Numpy mgrid


code:
from __future__ import print_function
from time import sleep

print("hello, ", end="")
sleep(2)
print("world!")

rawDescription: Printing on the same line with time.sleep()


code:
import os
for n in (27, 33, 35):
    pylib = 'python%s.lib' % n
    if os.path.exists(pylib):
        build_libpython(n)
        pydef = 'python%s.def' % n
        lc_def = sum(1 for line in open(pydef))
        libpy = 'libpython%s.a' % n
        lc_lib = sum(1 for line in os.popen('ar -t %s' % libpy))
        assert lc_def == lc_lib

rawDescription: Link to Python with MinGW

description: Link to Python with MinGW


code:
my_config = MyConfigParser()
my_config.read('example.cfg')
couples = my_config.get_list_of_tups('section', 'couples')
couples

rawDescription: Python argparser. List of dict in INI

description: Python argparser. List of dict in INI


code:
def func(a, b=None):
    if b is None:
        b = []
    b.append(a)
    return b

rawDescription: python function in which a parameter is external if mentioned or internal if it is not mentioned

description: Python function in which a parameter is external if mentioned or internal if it is not mentioned


code:
def smoke_machine():
    colors = {0: grey,
              1: dark_grey,
              2: light_grey}
    def create():
        for _ in xrange(random.choice([0,0,0,0,0,0,0,1,2,3])):
            behaviour = age(1), ascending(1), fan_out(400), wind(1, 15), kill_at(1000, 1000)
            p = Particle(colors[random.randint(0, 2)], random.randint(10, 15), *behaviour)
            yield p

    while True:
        yield create()

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
class Player(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    team = models.CharField(max_length=100)
    is_injured = models.BooleanField(default=False)
    is_banned = models.BooleanField(default=False)

rawDescription: Django: How to write groups and where those groups live?


code: mycount = sum(item.lower().count('b') for item in List1)

rawDescription: search substring in list in python

description: Search substring in list in python


code: sorted(myList, key=dist)

rawDescription: Order a list by all item's digits in Python


code:
np.percentile(x, 75, interpolation='linear')
np.percentile(x, 75, interpolation='midpoint')

rawDescription: NumPy percentile function different from MATLAB's percentile function


code:
bytearray([222,7])
Out[15]: bytearray(b'\xde\x07')

struct.unpack('H', bytearray([222,7]))
Out[16]: (2014,)

rawDescription: (Python) Formatting strings for struct.unpack?


code:
import pymel.datatypes as dt

i = dt.Matrix() # creates an identity matrix
m = dt.Matrix ( list_of_values) # use supplied numbers

rawDescription: Maya Python API Scaling a matrix about another matrix


code:
import re

str = "this is a sentence >>82384324"
rep = "which contains the number \\1"
pat = ">>(\\d+)"
res = re.sub(pat, rep, str)

print(res)

rawDescription: Match >>number and replace it

description: Match >>number and replace it


rawDescription: Python: A complete list of modules

description: Python: A complete list of modules


code:
def import_something():
    # decide what to import
    # ...
    mod = __import__( something )
    return mod
my_module = import_something()
my_module.do_stuff()

rawDescription: Python: importing through function to main namespace


code:
def handler():
    handler      # closure with circular reference

rawDescription: Does pygtk garbage-collect runtime-created functions connected to signals?


code:
template = """
def inner(_it, _timer):
    %(setup)s
    _t0 = _timer()
    for _i in _it:
        %(stmt)s
    _t1 = _timer()
    return _t1 - _t0
"""

rawDescription: Is it REALLY true that Python code runs faster in a function?


code:
SITE_PATH = os.path.abspath(os.path.dirname(__file__))
PROJECT_PATH = os.path.normpath(os.path.join(SITE_PATH, '..', '..'))
SRC_PATH = os.path.join(PROJECT_PATH, 'src')
if SRC_PATH not in sys.path:
    sys.path.insert(0, SRC_PATH)

rawDescription: Installing Django Apps outside of the project folder?


code:
form1 = {"energy_category": "electricity",
         "location": "home",
         "location-home": "shift",
         "distributor": "7",
         "postcode": "3000",
         "energy_concession": "0",
         "solar": "0",
         "disclaimer_chkbox": "disclaimer_selected"
         }

form2 = {"person-count":"1",
        "room-count":"1",
        "refrigerator-count":"1",
        "gas-type":"4",
        "pool-heating":"0",
        "spaceheating[]":"none",
        "spacecooling[]":"none",
        "cloth-dryer":"0",
        "cloth-dryer-freq-weekday":"",
        "waterheating[]":"other"}

import json
with requests.Session() as s:
    s.post(sub_url, data=form1)
    r = (s.get("https://compare.switchon.vic.gov.au/energy_questionnaire"))
    s.post("https://compare.switchon.vic.gov.au/energy_questionnaire/submit",
           data=form2)
    js = s.get("https://compare.switchon.vic.gov.au/service/offers").json()["offersList"]
    by_discount = sorted(js, key=lambda d: d["offerDetails"][0]["fullDiscountedPrice"])

rawDescription: Multi POST query (session mode)

description: Multi POST query (session mode)


rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
ax = X.new(A)
ax.methodA() # returns 5
ax.methodX() # returns 42
ax.methodB() # methodB not defined
bx = X.new(B)
bx.methodB() # returns 10
bx.new(B).methodX() # returns 42
bx.new(B).methodA() # methodA not defined

rawDescription: Decide baseclass at runtime

description: Decide baseclass at runtime


code:
def looping(A, p):
    m, n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    for r in range (m):
        for c in range (n):
            x = np.random.randint(0, p)
            B[r, c, x] = A[r, c]
    return B

def shuffling(A, p):
    m, n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    B[:,:,0] = A
    map(np.random.shuffle, B.reshape(m*n,p))
    return B

rawDescription: Copy numpy array from one (2-D) to another (3-D)


code:
from django import template
register = template.Library()

@register.inclusion_tag('blog/snippets/recent_posts.html')
def render_recent_blogposts():
    return {
        # This is just an example query, your actual models may vary
        'post_list': BlogPost.objects.all().order_by("published_on")[:4]
    }

rawDescription: Creating a "Recent Posts" list in a sidebar.


code:
def natatime(itr, fillvalue=None, n=2):
  return itertools.izip_longest(*(iter(itr),)*n, fillvalue=fillvalue)

rawDescription: reading lines 2 at a time

description: Reading lines 2 at a time


rawDescription: I cannot seem to find the correct formatting spec for preceding zeroes in python


code:
import fileinput
d = {}
for line in fileinput.input(['Day_1.dat', 'Day_2.dat', 'Day_3.dat']):
    city, temp = line.split()
    d.setdefault(city, []).append(temp)

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


code:
with open(os.path.join(filePath, filename), 'wb') as fp:
    wr = csv.writer(fp, quoting=csv.QUOTE_ALL)
    for rownum in xrange(sheet.nrows):
        wr.writerow(sheet.row_values(rownum))

rawDescription: python shutil: only copy part of the file

description: Python shutil: only copy part of the file


code: ":".join(",".join(str(elem) for elem in chunk) for chunk in chunks(l, n))

rawDescription: How to chunk any type of file in python and convert that file into string

description: Chunk any type of file in python and convert that file into string


code:
def key_fix_decorator(f):
    def wrapped(self, *args, **kwargs):
        if args and isinstance(args[0], str):
            args = (args[0].lower(),) + args[1:]
        return f(self, *args, **kwargs)
    wrapped.__name__ = f.__name__
    wrapped.__doc__ = f.__doc__
    return wrapped

rawDescription: Why doesn't my idea work in python2?

description: Why doesn't my idea work in python2


code:
# fill in missing data with 0, so the bar plots are aligned
df = df.pivot(index='insert', columns='quality').fillna(0).stack().reset_index()

colors = ['green', 'red']
positions = [0, 1]

for group, color, pos in zip(df.groupby('quality'), colors, positions):
    key, group = group
    print(group)
    group.plot('insert', 'mean', yerr='std', kind='bar', width=0.4, label=key,
               position=pos, color=color, alpha=0.5, ax=ax)

ax.set_xlim(-1, 11)
plt.show()

rawDescription: Plotting errorbar with mean and std after grouping


rawDescription: Convert following data to JSON format in python


code: a,b,c,d = (int(input()) for _ in range(4))

rawDescription: Entering few integers in one line

description: Entering few integers in one line


code:
def lcs(a, b):
    tbl = [[0 for _ in range(len(b) + 1)] for _ in range(len(a) + 1)]
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            tbl[i + 1][j + 1] = tbl[i][j] + 1 if x == y else max(
                tbl[i + 1][j], tbl[i][j + 1])
    res = []
    i, j = len(a), len(b)
    while i and j:
        if tbl[i][j] == tbl[i - 1][j]:
            i -= 1
        elif tbl[i][j] == tbl[i][j - 1]:
            j -= 1
        else:
            res.append(a[i - 1])
            i -= 1
            j -= 1
    return res[::-1]

list1 = [1, 2, 3, 4, 5, 6, 7]
list2 = [7, 6, 3, 4, 5, 8]
lcs(list1, list2)

rawDescription: Find overlap of two lists, preserving sequence order


code:
import random

names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Duglinglabat", "Dulko", "Fangot"

rand_name = random.choice(names)

with open("character_one.txt", "w") as c1:

    c1.write(rand_name)

rawDescription: Cannot write random choice from list into text file


code:
a, b = symbols('a b', cls=Wild)
expr.replace(Integral(a + b, x), Integral(a, x) + Integral(b, x))

rawDescription: Distribute integral over a summation in sympy


code: ['NICE', 'FLOWER', 'GOOD', 'YELLOW']

rawDescription: how to delete lowercase words from a string in python

description: Delete lowercase words from a string in python


rawDescription: Field calculated from Foreign Keys, need to save twice?


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

use_date = use_date+relativedelta(years=+1)

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


rawDescription: How can I solve multivariable linear equation in python?

description: Solve multivariable linear equation in python


script: doc['location'].distance(lat, lon) < doc['distance'].value

rawDescription: ElasticSearch GeoDistance Query

description: ElasticSearch GeoDistance Query


code: scores.append({'name': name, 'score': score})

rawDescription: How to store a name and score into a list?

description: Store a name and score into a list


rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


code:
def remove_comprising(words):
    seen = set()
    result_words = []
    for word in words:
        for small_word in words:
            if small_word in word and small_word != word:
                if small_word in seen:
                    word = word.replace(small_word, '')
                else:
                    seen.add(small_word)
        result_words.append(word)
    return [word.strip() for word in result_words if word not in seen]

rawDescription: How to remove inception words in list?

description: Remove inception words in list


code:
import csv

with open("name.csv", newline='') as infh:
    cr = csv.reader(infh)
    columns = {r[0]: list(r[1:]) for r in zip(*cr)}

rawDescription: Python Help: Creating a dict of {str:list of str} from csv file


code:
def longest_path(matrix):
    def inner_longest_path(x, y):
        best, best_path = 0, []
        # for all possible neighbor cells...
        for dx, dy in ((+1, 0), (-1, 0), (0, +1), (0, -1)):
            # if cell is valid and strictly smaller...
            if (0 <= x + dx < len(matrix) and 0 <= y + dy < len(matrix[x])
                    and matrix[x+dx][y+dy] < matrix[x][y]):
                n, path = inner_longest_path(x+dx, y+dy)
                # check if the path starting at that cell is better
                if n > best:
                    best, best_path = n, path
        return best + 1, [matrix[x][y]] + best_path

    return max(inner_longest_path(x, y) for x, row in enumerate(matrix)
                                        for y, _ in enumerate(row))

rawDescription: Maximum number of elements in the path of a matrix


code:
df = pd.DataFrame(arr, columns=some_list_of_names)
df[some_list_of_names] = myfunction(arr)

rawDescription: Modify pandas dataframe values with numpy array


rawDescription: operation in arrays

description: Operation in arrays


rawDescription: Python: Removing random whitespace from a string of numbers


rawDescription: pyparsing example

description: Pyparsing example


rawDescription: List comprehension without using an iterable


code:
import re
p = re.compile(r'\bclass(?:\(?es\)?)?(?:\s*(?:and|et|[,\s])?\s*\d+)+')
test_str = "Accepted for all the goods and services in classes 16 and 41."
results = [re.findall(r"\d+", x) for x in p.findall(test_str)]
print([x for l in results for x in l])
# => ['16', '41']

rawDescription: RegEx: Find all digits after certain string


code: new_a = [x + 1 for x in a]

rawDescription: Grasping the basics of in-place operations


code:
def delete(self, session_key=None):
    if session_key is None:
        if self.session_key is None:
            return
        session_key = self.session_key
    try:
        Session.objects.get(session_key=session_key).delete()
    except Session.DoesNotExist:
        pass

rawDescription: Does the django authentication logout function delete's session row in django_session table?


rawDescription: In Python, what's the correct way to instantiate a class from a variable?


code: [float(c)/t for c,t in zip(conversions, trials)]

rawDescription: How do I divide the members of a list by the corresponding members of another list in Python?

description: Divide the members of a list by the corresponding members of another list in Python


code:
# This should not be more than 8
BITS = 5

def get_last_bits(value, count):
    return value & ((1<<count) - 1)

def pack(data):
    buf = bytearray(1)
    used_bits = 0

    for num in data:
        # All zeroes is a special value marking unused bits
        if not isinstance(num, int) or num <= 0 or num.bit_length() > BITS:
            raise TooMuchBits(num)

        # Character fully fits into available bits in current byte
        if used_bits <= 8 - BITS:
            buf[-1] |= num << used_bits
            used_bits += BITS

        # Character should be split into two different bytes
        else:
            # Put lowest bit into available space
            buf[-1] |= get_last_bits(num, 8 - used_bits) << used_bits
            # Put highest bits into next byte
            buf.append(num >> (8 - used_bits))
            used_bits += BITS - 8

    return bytes(buf)

def unpack(data):
    buf = bytearray()
    data = bytearray(data)

    # Characters are filled with logic AND and therefore initialized with zero
    char_value = 0
    char_bits_left = BITS

    for byte in data:
        data_bits_left = 8

        while data_bits_left >= char_bits_left:
            # Current character ends in current byte
            # Take bits from current data bytes and shift them to appropriate position
            char_value |= get_last_bits(byte, char_bits_left) << (BITS - char_bits_left)

            # Discard processed bits
            byte = byte >> char_bits_left
            data_bits_left -= char_bits_left

            # Zero means the end of the string. It's necessary to detect unused space in the end of data
            # It's otherwise possible to detect such space as a 0x0 character
            if char_value == 0:
                break

            # Store and initialize character
            buf.append(char_value)
            char_value = 0
            char_bits_left = BITS

        # Collect bits left in current byte
        if data_bits_left:
            char_value |= byte
            char_bits_left -= data_bits_left

    return buf

rawDescription: How to encode English plain-text (consisting only of letters a-z and whitespace) using a 5-bit character encoding in Python?

description: Encode English plain-text (consisting only of letters a-z and whitespace) using a 5-bit character encoding in Python


rawDescription: Prefixing the results of string.split with the substring indices of each result


rawDescription: Get hours difference from UTC to given timezone with Python


code: json.dump(json_object, opfile)

rawDescription: How to save my variables to a txt file from a program

description: Save my variables to a txt file from a program


code:
for row in rdr:
    newrow = [row[n] for n in rows_to_keep]
    wrt.writerow(newrow)

rawDescription: Dynamic arguments in python write

description: Dynamic arguments in python write


code:
from concurrent.futures import ThreadPoolExecutor
io_pool_exc = ThreadPoolExecutor()

rawDescription: Read file line by line with asyncio

description: Read file line by line with asyncio


code:
class Node(object):
    byname = {}

    def __init__(self, name, parent=None):
        self.name = name
        self.parent = parent
        self.children = []
        self.byname[name] = self
        if parent is None:  # root pseudo-node
            self.code = 0
        else:  # all normal nodes
            self.parent.children.append(self)
            self.code = len(self.parent.children)

    def get_codes(self, codelist):
        if self.code:
            codelist.append(str(self.code))
            self.parent.get_codes(codelist)

root = Node('')

def get_code(nodename):
    node = Node.byname.get(nodename)
    if node is None: return ''
    codes = []
    node.get_codes(codes)
    codes.reverse()
    return '.'.join(codes)

rawDescription: Python: tree structure and numerical codes?


rawDescription: Sort list of tuples by specific tuple element in Python 3


code:
class Player(pygame.sprite.Sprite):
    def __init__ (self, frames, *groups):
        super(player,self).__init__(*groups)
        frame = 0
        self.image = frames[frame]
        ...

class Game(object):

    def main(self, screen):
        sprite = pygame.image.load('test.png')
        frames = sprite_system().slice_sheet(sprite,0,0,64,64,4)
        sprites = pygame.sprite.Group()
        self.player = Player(frames, sprites)
        ...

rawDescription: sprite_sheet system in python and pygame

description: Sprite_sheet system in python and pygame


rawDescription: How to reference numpy array objects?

description: Reference numpy array objects


code:
arr = np.array([[5, 4, -2, 1, -2, 0, 4, 4, -6, -1],
                [0, 1,  2, 2,  3, 4, 5, 6,  7,  8]])
axis = 1
u, indices = np.unique(arr, return_inverse=True)
u[np.argmax(np.apply_along_axis(np.bincount, axis, indices.reshape(arr.shape),
                                None, np.max(indices) + 1), axis=axis)]

rawDescription: How to find most frequent values in numpy ndarray?

description: Find most frequent values in numpy ndarray


code:
result = np.empty([image.shape[0], image.shape[1], 3], dtype=image.dtype)

result[:, :, 0] = image[:, :, 0]
result[:, :, 1] = image[:, :, 1]
result[:, :, 2] = (np.abs(image[:, :, 0]) > 1.) | (np.abs(image[:, :, 1]) > 1.)

rawDescription: Fast way to add calculated value element to multidimensional numpy array


code:
{'name': 'name', 'value': 'value'}
Position: 11
{'name': 'foo', 'value': '1'}
Position: 17
{'name': 'bar', 'value': '2'}
Position: 23

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


code: A = Cell(8,Cell(9,Cell(10)))

rawDescription: Python copy and concatenate linked lists, preserve order


rawDescription: Compute daily climatology using pandas python


code:
def find_text(text):
    return next((item.group(1) for item in PATTERN.finditer(text)), "")

rawDescription: Getting captured group in one line

description: Getting captured group in one line


rawDescription: Kivy: Update to ListView data with ListAdapter or DictAdapter does not change button text


code:
with open('raw.txt', 'r') as infile:
    f = infile.readlines()
    with open('filtered.txt', 'w') as outfile:
        for line in f:
            if 'subject_avatar' in line: # or other better rules
                outfile.write(line)

rawDescription: Parsing Data with non-uniform rows in python


code:
import re
import numpy as np
inputtext = 'Bbc World News (57%); DANONE SA (FRANCE) (52%), Mn-Public-Radio-Intl; SIC123 Industry (52%)'
[(name, int(perc) if perc else np.nan)
 for name, perc in re.findall(r'(\b[\w() -]+)(?:\s+\((\d+)%\))?(?=[,;]|$)', inputtext)]

rawDescription: One Way to Grab both text and percentages regex python distinguish numbers from letters within parantheses


rawDescription: Pandas Sort Order of Columns by Row

description: Pandas Sort Order of Columns by Row


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

x = np.random.uniform(-0.7,0.7,10)
y = np.random.uniform(-0.7,0.7,10)
z1 = np.random.uniform(-1,1,10)
z2 = - z1

circle=plt.Circle((0,0),1,color="black",fill=False)

triang1 = tri.Triangulation(x, y)
triang2 = tri.Triangulation(x, y)

mask1 = np.logical_or.reduce(( np.where(z1[triang1.triangles]<=0, 1,0).T ))
mask2 = np.logical_or.reduce(( np.where(z2[triang2.triangles]<=0, 1,0).T ))

triang1.set_mask(mask1)
triang2.set_mask(mask2)

ax = plt.subplot(111)
ax.set_aspect('equal')
ax.add_artist(circle)

t1 = ax.tripcolor(triang1, z1, shading='gouraud', cmap=matplotlib.cm.Greens, alpha=0.5)
t2 = ax.tripcolor(triang2, z2, shading='gouraud', cmap=matplotlib.cm.Reds, alpha=0.5)

rawDescription: Plot multiple sets of data with tripcolor - transparency in colormaps


code:
from operator import itemgetter

fields = itemgetter(0, 1)    # zero-based field numbers of the fields of interest
with open('sample_categories.csv') as csvfile:
    next(csvfile)     # skip over header line
    current_category = None
    outfile = None
    for line in csvfile:
        filename, category = fields(line.split())
        if category != current_category:
            if outfile is not None:
                outfile.close()
            outfile = open(category, 'w')
            current_category = category
        with open(filename) as infile:
            outfile.write(infile.read())

rawDescription: Joining files by corresponding columns in outside table


code:
import re
ss = 'Mandrake 9.2 (32 bit)'
new_line = re.sub(r'\(.*?\)','',ss)  #'Mandrake 9.2 '

rawDescription: How to clean string coming from index

description: Clean string coming from index


code:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen

objects = {}

class MyScreenManager(ScreenManager):
    pass

class MenuScreen(Screen):
    def switch_screen(self, text):
        objects['manager'].current = 'main'
        objects['main_button'].text = text

class MainScreen(Screen):
    pass

class TestApp(App):
    def build(self):
        objects['manager'] = self.root
        objects['main_button'] = self.root.ids.main.ids.button

if __name__ == '__main__':
    TestApp().run()

rawDescription: Simple Kivy code with two screens

description: Simple Kivy code with two screens


code:
def listcleaner(lst):
    if not lst:   # If list is empty
        return [] # Go no further
    if isinstance(lst[0], list):
        if lst[0]: # If the list has something in it, we want to run listcleaner() on it.
            return [listcleaner(lst[0])] + listcleaner(lst[1:])
        else: # Otherwise, just skip that list
            return listcleaner(lst[1:])
    else:
        return [lst[0]] + listcleaner(lst[1:]) # If it is not a list, return it unchanged plus listcleaner() on the rest.

a = listcleaner([1, [], [2, []], 5])
print(a)

rawDescription: recursive way to go through a nested list and remove all of a select value

description: Recursive way to go through a nested list and remove all of a select value


code:
import pdb

pdb.set_trace()

rawDescription: python: run interactive python shell from program

description: Python: run interactive python shell from program


rawDescription: python 2.7 username with minimum and max

description: Python 2.7 username with minimum and max


rawDescription: Access a specific sizer from wxFormBuilder in Python


code:
import matplotlib.pyplot as plt

def cross_hair(x, y, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    horiz = ax.axhline(y, **kwargs)
    vert = ax.axvline(x, **kwargs)
    return horiz, vert

cross_hair(0.2, 0.3, color='red')
plt.show()

rawDescription: cross hairs in python animation

description: Cross hairs in python animation


code:
while True:
    tmp = path_b + "-temp-%s" %(os.urandom(8).encode("hex"), )
    try:
        os.link(path_a, tmp)
    except OSError as e:
       if e.errno == 17: # file exists
          continue
       raise
    break

rawDescription: Python: How to atomically hardlink files for deduplication?


code:
class F(object):
    @staticorinstancemethod
    def math(instOrNone, v1, v2=None):
        return instOrNone.x + v1 if instOrNone else v1 + v2

rawDescription: Python: avoid defining both a classmethod and an instancemethod


code:
class MyWidget(AnchorLayout):
    ...
    def remove_rectangle(self, widget):
        self.grid_layout.remove_widget(widget)

rawDescription: removing Images on clicks in kivy

description: Removing Images on clicks in kivy


code:
print(int(str(55), 6))
# 35
print(int('10', 6))
# 6
print(int('6', 6))
# ValueError: invalid literal for int() with base 6: '6'

rawDescription: Converting base 6 to decimal?

description: Converting base 6 to decimal


code:
import dateparser
dateparser.parse(u'2016 21 января, четверг')
dateparser.parse(u'2016 21 Январь, Четверг')

rawDescription: Different datetime.strftime output with same locale settings


rawDescription: Python re match at specific point in string


rawDescription: Python values with units

description: Python values with units


code: idx = np.random.poisson(size=10)

rawDescription: Probabilistic selection from a numpy array


code: cherrypy.server.socket_queue_size = 10

rawDescription: Start CherryPy with different request_queue_size and timeout


code:
def changename(index):
    name = mb.menu.entrycget(index, "label")
    selectedText.set(name)
    mb.grid(row=1, column=1)

rawDescription: Creating a drop down menu item selection Python


rawDescription: How do I add elements from one numpy array to another at certain indices?

description: Add elements from one numpy array to another at certain indices


code:
import re
with open("test.txt") as f:
    inputString = f.read()

#remove all extra spaces so all items separated by only one space
inputString = re.sub(r" +", " ", inputString)

itemsInString = inputString.split(" ")

col1 = []
col2 = []
for index, item in enumerate(itemsInString):
    if index % 2 == 0:
        col1.append(float(item))
    else:
        col2.append(float(item))

print(col1)
print(col2)

rawDescription: how to split a very long row data into two column by python (from txt file)

description: Split a very long row data into two column by python (from txt file)


rawDescription: Generate Dictionary in Python at run time


rawDescription: Numpy: return boolean array after condition checking


code:
import theano, numpy
T = theano.tensor.matrix()
f = theano.function([T], T[[1, 2, 4]])
f(numpy.arange(25).reshape(5, 5))

rawDescription: Theano Tensor remove element?

description: Theano Tensor remove element


code:
def kurt2(X, w):
    n, m = X.shape
    K = np.zeros_like(X)
    W = 2*w + 1

    for j in xrange(m-W+1):
        for i in xrange(n-W+1):
            x = X[i:i+W,j:j+W].flatten()
            x2 = x*x
            x3 = x2*x
            x4 = x2*x2

            M1 = x.mean()
            M2 = x2.mean()
            M3 = x3.mean()
            M4 = x4.mean()
            M12 = M1*M1
            V = M2 - M12;

            K[w+i,w+j] = (M4 - 4*M1*M3 + 3*M12*(M12 + 2*V)) / (V*V) - 3
    return K

rawDescription: Implementing a "Kurtosis filter" using scipys generic_filter


code: parcelID = str(values)

rawDescription: Python List to String Conversion

description: Python List to String Conversion


code:
def allow_syncdb(self, db, model):
        "Explicitly put all models on all databases."
        return True

rawDescription: Django multidb: write to multiple databases


code: from PIL import Image

rawDescription: installing Pillow and PIL

description: Installing Pillow and PIL


code:
class CreateWorkbook:
    def openworkbook(self, data):
        self.output_filename = input('output filename:')
        self.workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx')
        self.worksheet = workbook.add_worksheet()

    def closeworkbook_msg1(self, data):
        #sets up the header row
        self.worksheet.write('A1','item1',bold)
        self.worksheet.write('B1', 'item2',bold)
        self.worksheet.write('C1', 'item3',bold)
        self.worksheet.autofilter('A1:C1')   #dropdown menu created for filtering

        # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
        for r, row in enumerate(data, start=1):  #where you want to start printing results inside workbook
            for c, col in enumerate(data):
                self.worksheet.write_column(r,0, i1)
                self.worksheet.write_column(r,1, i2)
                self.worksheet.write_column(r,2, i3)
        self.workbook.close()
        print('XLSX file named ' + output_filename + '_' + command_type +' was created')

    def closeworkbook_msg2(self, data):
        #sets up the header row
        self.worksheet.write('A1','item1',bold)
        self.worksheet.write('B1', 'item2',bold)
        self.worksheet.write('C1', 'item3',bold)
        self.worksheet.write('C1', 'item4',bold)
        self.worksheet.autofilter('A1:C1')   #dropdown menu created for filtering

        # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
        for r, row in enumerate(data, start=1):  #where you want to start printing results inside workbook
            for c, col in enumerate(data):
                self.worksheet.write_column(r,0, i1)
                self.worksheet.write_column(r,1, i2)
                self.worksheet.write_column(r,2, i3)
                self.worksheet.write_column(r,3, i4)
        self.workbook.close()
        print('XLSX file named ' + output_filename + '_' + command_type + ' was created')

rawDescription: Create an interactive command loop using inheritance python34


code:
timeit.Timer(lambda: heapq.merge(ll1i, ll2i)).repeat()
timeit.Timer(lambda: sorted(list(ll1i)+list(ll2i))).repeat()

rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
#stress test:

import random
nums = list(range(1,101))
testGroups = [set(random.sample(nums,random.randint(1,100))) for n in range(1000)]
foundGroups = maxIntersection(testGroups,3)

rawDescription: Find all subsets from list of sets that appears in at least N different sets


code:
from sqlalchemy import Column, Integer, Unicode, UnicodeText, String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from random import choice
from string import letters

engine = create_engine('sqlite:////tmp/teste.db', echo=True)
Base = declarative_base(bind=engine)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(40))
    address = Column(UnicodeText, nullable=True)
    password = Column(String(20))

    def __init__(self, name, address=None, password=None):
        self.name = name
        self.address = address
        if password is None:
            password = ''.join(choice(letters) for n in xrange(10))
        self.password = password

Base.metadata.create_all()

Session = sessionmaker(bind=engine)
s = Session()

rawDescription: Is it possible to store Python class objects in SQLite?


code:
import re

pattern1 = re.compile(r"""(?:s|season)(?:\s)(?P<s>\d+)(?:e|x|episode|\n)(?:\s)(?P<ep>\d+) # s 01e 02""", re.VERBOSE)
pattern2 = re.compile(r"""(?:s|season)(?P<s>\d+)(?:e|x|episode|\n)(?:\s)(?P<ep>\d+) # s01e 02""", re.VERBOSE)
pattern3 = re.compile(r"""(?:s|season)(?:\s)(?P<s>\d+)(?:e|x|episode|\n)(?P<ep>\d+) # s 01e02""", re.VERBOSE)
pattern4 = re.compile(r"""(?:s|season)(?P<s>\d+)(?:e|x|episode|\n)(?P<ep>\d+) # s01e02""", re.VERBOSE)
pattern5 = re.compile(r"""(?:s|season)(?P<s>\d+)(?:.*)(?:e|x|episode|\n)(?P<ep>\d+) # s01 random123 e02""", re.VERBOSE)
pattern6 = re.compile(r"""(?:s|season)(?:\s)(?P<s>\d+)(?:.*)(?:e|x|episode|\n)(?:\s)(?P<ep>\d+) # s 01 random123 e 02""", re.VERBOSE)
pattern7 = re.compile(r"""(?:s|season)(?:\s)(?P<s>\d+)(?:.*)(?:e|x|episode|\n)(?P<ep>\d+) # s 01 random123 e02""", re.VERBOSE)
pattern8 = re.compile(r"""(?:s|season)(?P<s>\d+)(?:.*)(?:e|x|episode|\n)(?:\s)(?P<ep>\d+) # s01 random123 e 02""", re.VERBOSE)

patterns = [pattern1, pattern2, pattern3, pattern4, pattern5, pattern6, pattern7, pattern8 ]

test="Hello seinfeld season 01episode 22 foo bar"

for idx, p in enumerate(patterns):
    m = re.search(p, test)
    if m:
        print('MATCHED PATTERN: {}'.format( patterns[idx].pattern ) )
        print('    SEASON:  {}'.format( m.group('s')) )
        print('    EPISODE: {}'.format( m.group('ep')) )

rawDescription: Python regular expression multi patterns, extracting right groups


code: flierprops = dict(marker='o', markerfacecolor='green', markersize=12, linestyle='none')

rawDescription: Remove edgewidth of matplotlib boxplot flier


code:
pw = ''
while len(pw) < 6 or len(pw) > 12:
    pw = raw_input('Please enter a password between 6-12 characters long: ')

rawDescription: Restart a while loop?

description: Restart a while loop


code:
indices = ind.ravel() + np.repeat(range(0, 8*ind.shape[0], 8), ind.shape[1])
out = data.ravel()[indices]
out = out.reshape(ind.shape)

rawDescription: Extract elements of a 2d array with indices from another 2d array


code:
indices = frozenset(range(step))
result = [el for i, el in enumerate(seq) if i % step2 in indices]

rawDescription: What is the pythonic way of slicing an array into stepped contiguous blocks?


code:
request = json.load(sys.stdin)
response = handle_request(request)
print("Content-Type: application/json", end="\n\n")
json.dump(response, sys.stdout, indent=2)

rawDescription: Passing variables between Python and Javascript


rawDescription: Split list of datetime objects into keys(date) and values(times)


code:
with open('output', 'w') as f:
    f.write('\t'.join(l[1:]) + '\n')

rawDescription: writing tab separated values into a file

description: Writing tab separated values into a file


code:
[Section1]
db_username = "db_user"
db_password = "db_passwd"

rawDescription: Where to store data I don't want in code?


code: map(func, lis)

rawDescription: Converting a text file to a list

description: Converting a text file to a list


code:
from ConfigParser import ConfigParser

from fabric.tasks import Task
from fabric.api import execute, task

@task()
def build(**options):
    """Your build function"""

class Deploy(Task):

    name = "dev"

    def __init__(self, *args, **kwargs):
        super(Deploy, self).__init__(*args, **kwargs)

        self.options = kwargs.get("options", {})

    def run(self, **kwargs):
        options = self.options.copy()
        options.update(**kwargs)
        return execute(build, **options)

config = ConfigParser()
config.read("deploy.ini")

sections = [
    section
    for section in config.sections()
    if section != "globals" and ":" not in section
]

for section in sections:
    options = {"name": section}
    options.update(dict(config.items("globals")))
    options.update(dict(config.items(section)))

    t = Deploy(name=section, options=options)
    setattr(t, "__doc__", "Deploy {0:s} instance".format(section))
    globals()[section] = task

rawDescription: fabric different parameters in different hosts

description: Fabric different parameters in different hosts


code:
upload_file = form.save(commit=False)
upload_file.filename = request.FILES['theFile'].name
upload_file.save()

rawDescription: Django file upload: filename not sticking


code:
class BaseTestCase(unittest.TestCase):
    xmlfile = None  # will be set by containing test suite

rawDescription: python unittest multiple mixins

description: Python unittest multiple mixins


code:
# the value 0.3 cannot be exactly represented in floating points
# read this for starters: https://docs.python.org/3/tutorial/floatingpoint.html
et.find(".//element").text = float64(0.3)

rawDescription: How to solve TypeError: cannot serialize float Python Elementtree

description: Solve TypeError: cannot serialize float Python Elementtree


code: df[["Name", "Infraction", "Yards"]] = list(df.Detail.apply(extract))

rawDescription: Trying to parse string and create new columns in data frame in Python pandas


code: top.propagation = False

rawDescription: Python logging for non-trivial uses?

description: Python logging for non-trivial uses


code:
from itertools import izip
for index, item in izip(xrange(limit), items):
    print(item)

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code: tup_after = [v for t in tup_Before for v in t]

rawDescription: Flattening a list of tuples

description: Flattening a list of tuples


code:
['redyed']
['reeded']

rawDescription: Python - finding words based on repeated characters specified in a string


code:
def _refactorMe(func):
        @functools.wraps(func) #the wraps decorator propagates name/docsting
        def wrapper(parm1, parm2):
            if parm1:
                code_chunk_1

            func(parm1, parm2)

            if parm2:
                code_chunk_2

        return wrapper

rawDescription: Code refactoring with python decorators?

description: Code refactoring with python decorators


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)

        self.label = wx.StaticText(self.panel, label="Label")
        self.text = wx.TextCtrl(self.panel)
        self.button = wx.Button(self.panel, label="Test")

        self.button1 = wx.Button(self.panel, label="ABOVE")
        self.button2 = wx.Button(self.panel, label="BELLOW")

        self.horizontal = wx.BoxSizer()
        self.horizontal.Add(self.label, flag=wx.CENTER)
        self.horizontal.Add(self.text, proportion=1, flag=wx.CENTER)
        self.horizontal.Add(self.button, flag=wx.CENTER)

        self.vertical = wx.BoxSizer(wx.VERTICAL)
        self.vertical.Add(self.button1, flag=wx.EXPAND)
        self.vertical.Add(self.horizontal, proportion=1, flag=wx.EXPAND)
        self.vertical.Add(self.button2, flag=wx.EXPAND)

        self.panel.SetSizerAndFit(self.vertical)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxPython wx.TextCtrl dynamically resizing to fill panel width

description: WxPython wx.TextCtrl dynamically resizing to fill panel width


rawDescription: Define a column type as 'list' in Pandas


code: df_result = pd.DataFrame(ts, columns=['value'])

rawDescription: Get column name where value is something in pandas dataframe


code: (x1, y1), (x2, y2) = map(literal_eval, s.split(' - '))

rawDescription: extracting data from formatted string (python)

description: Extracting data from formatted string (python)


code:
def formatdt(dt):
    return dt.strftime('%Y-%m-%d %H:%M:%S.')+(
           "%0.3f"%(dt.microsecond/10**6))[2:]

rawDescription: Python 3.4: how to add zero milliseconds and change their formatting


code: response = br.submit(name='ctl00$ContentPlaceHolder1$uxResults$uxNext').read()  #"Press" the next submit button

rawDescription: Screenscaping aspx with Python Mechanize - Javascript form submission


rawDescription: Trouble plotting Pandas Series

description: Trouble plotting Pandas Series


code:
import re
text = 'foo bar 1 st, 2 nd, 33 rd, 134 th baz quz'
re.sub(r'([0-9]+)\s+(st|nd|rd|th)\b', '\\1\\2', text)

rawDescription: Python remove whitespace from regex substring match in file


code:
foo = __import__('a')
mydocstring = foo.__doc__

rawDescription: Getting doc string of a python file

description: Getting doc string of a python file


code:
if self.reqRouterSocket in socketEvents:
    multipart = self.reqRouterSocket.recv_multipart()
    multipart = [multipart[-2]] + multipart
    del multipart[-2]
    self.repRouterSocket.send_multipart(multipart)

rawDescription: ZMQ Python Request Reply Broker for Addressed Asynchronous Requests


rawDescription: How to extract the bits of larger numeric Numpy data types

description: Extract the bits of larger numeric Numpy data types


rawDescription: change the format of a numpy array with no loops

description: Change the format of a numpy array with no loops


code:
import pandas
df1 = pandas.read_csv('df1.csv')
df2 = pandas.read_csv('df2.csv')
df1
df2

rawDescription: Partial merge in Pandas

description: Partial merge in Pandas


code: slices = np.bitwise_and(bg, gr)

rawDescription: Detect gray things with OpenCV

description: Detect gray things with OpenCV


code:
import requests
r = requests.post('http://server/myapp/method', data={'aaa': 'bbb'})

rawDescription: pycurl equivalent of "curl --data-binary"

description: Pycurl equivalent of "curl --data-binary"


code:
graph = pydot.Dot(graph_type='graph')
graph.add_node(pydot.Node('literal_0_0', label='0'))
graph.add_node(pydot.Node('literal_0_1', label='0'))
graph.add_node(pydot.Node('literal_1_0', label='1'))
graph.add_node(pydot.Node('literal_1_1', label='1'))

rawDescription: pydot: is it possible to plot two different nodes with the same string in them?

description: Pydot: is it possible to plot two different nodes with the same string in them


code:
N = 100
data = np.random.random((N, 7))
x = data[:,0]
y = data[:,1]
points = data[:,2:4]
# color is the length of each vector in `points`
color = np.sqrt((points**2).sum(axis = 1))/np.sqrt(2.0)
rgb = plt.get_cmap('jet')(color)

rawDescription: Plot 2-dimensional NumPy array using specific columns


rawDescription: Extract files from a zip folder with sub folders into a single folder


code: s = urlparse.urlunparse((o.scheme, o.netloc, '', '', '', ''))

rawDescription: How can I get the base URI in AppEngine?

description: Get the base URI in AppEngine


code:
new_data = []
for x, v1, v2 in zip(data, var1, var2):
    new_data.extend([y + [v1] + [v2] for y in x])
pd.DataFrame(new_data, columns=['data', 'min', 'max', 'var1', 'var2'])

rawDescription: List of list to pandas dataframe

description: List of list to pandas dataframe


code:
class UserProfile(Document):
    user = ReferenceField(User, required=True, primary_key=True)
    name = StringField()

rawDescription: Migrating From Django to Pyramid

description: Migrating From Django to Pyramid


code:
if host_id in myDict:
    speed = myDict[host_id]

rawDescription: search dictionary in python for the matching value

description: Search dictionary in python for the matching value


code:
import wx

class GraphicsPage(wx.grid.Grid):

    def __init__(self, parent, width, height):
        super(GraphicsPage, self).__init__(parent, -1)
        self.CreateGrid(width, height)

        self.SetRowLabelSize (0)
        self.SetMargins(0,0)
        self.AutoSizeColumns(False)
        self.ForceRefresh()

rawDescription: How to pass arguments to a custom class in python?

description: Pass arguments to a custom class in python


rawDescription: Method that gets called on module deletion in Python


code: ar = [int(i) for i in input().split()]

rawDescription: How do i take formatted input in python?

description: Take formatted input in python


code:
logger = logging.getLogger()

gm = ThreadedTlsSMTPHandler(("smtp.gmail.com", 587), 'bugs@my_company.com', ['admin@my_company.com'], 'Error found!', ('my_company_account@gmail.com', 'top_secret_gmail_password'))
gm.setLevel(logging.ERROR)

logger.addHandler(gm)

try:
    1/0
except:
    logger.exception('FFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUU-')

rawDescription: How to make SMTPHandler not block

description: Make SMTPHandler not block


code:
def myupdate( self ):
    return db( **dictvar )

rawDescription: web2py: how to update multiple fields in table

description: Web2py: how to update multiple fields in table


code:
GQL_PARTS_BY_PRODUCT = ProductParts.gql('WHERE products = :1')
for product in productData:
    productDict = {}
    typeDict = {}
    productDict['productName'] = product.name

    cache_key = 'productparts_%s' % (slugify(product.key()))
    partData = memcache.get(cache_key)

    if not partData:
        for type in typeData:
            typeDict[type.typeId] = { 'default' : '', 'optional' : [] }

        # here's a new approach that does just ONE datastore query (for each product)
        GQL_PARTS_BY_PRODUCT.bind(product)
        parts = GQL_PARTS_BY_PRODUCT.fetch(1000)
        for part in parts:
            if part.key() in self.defaultParts:
                part_type = 'default'
            else:
                part_type = 'optional'

            for label in labelsForLangCode:
                if label.key() in defaultPart.partLabelList:
                    typeDict[defaultPart.type.typeId][part_type] = label.partLangLabel
        # (end new code)
        memcache.add(cache_key, typeDict, 500)
        partData = memcache.get(cache_key)

    productDict['parts'] = partData
    productList.append(productDict)

rawDescription: Loading datasets from datastore and merge into single dictionary. Resource problem


rawDescription: Delete legend in an Excel plot with Python and win32com


code:
my_list=[]
for i in xrange(53,256):
    for j in xrange(0,208):
        for k in xrange(0,208):
            my_list.append("{0:02x}{1:02x}{2:02x}".format(i,j,k))

rawDescription: Create a list of hex codes given an Rgb range


code:
from fuzzywuzzy import process
df = pd.DataFrame([
                ['0016F00001c7GDZQA2',  'Daniela Abriani'],
                ['0016F00001c7GPnQAM',  'Daniel Abriani'],
                ['0016F00001c7JRrQAM',  'Nisha Well'],
                ['0016F00001c7Jv8QAE', 'Katherine'],
                ['0016F00001c7cXiQAI', 'Katerine'],
                ['0016F00001c7dA3QAI',  'Katherin'],
                ['0016F00001c7kHyQAI',  'Nursing and Midwifery Council Research Office'],
                ['0016F00001c8G8OQAU',  'Nisa Well']],
                columns=['ID', 'NAME'])

rawDescription: How do to fuzzy matching on excel file using Pandas?


code: np.linspace(0, 2*math.pi, 200)

rawDescription: How to Do Trigonometric Range of Floats in Python?


code:
joyx = lambda x: copysign(100, x) if abs(x) > 50 else 0
joyx(51), joyx(-51), joyx(50), joyx(-50), joyx(0)

rawDescription: Is there a Pythonic way of handling this sort of range mapping


code:
fields = {}
for name, attr in IMember.namesAndDescriptions():
    if isinstance(attr, schema.Field):
        fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)

rawDescription: How to dynamically add attributes to an interface

description: Dynamically add attributes to an interface


rawDescription: Simple way to get current memory usage from Guppy


code:
import PySide.QtWebKit
import sys
from PyQt4 import QtGui

class BrowserWindow(PySide.QtWebKit.QWebView):

    SCRIPT_TEMPLATE = 'document.elementFromPoint({}, {});'

    def __init__(self, _parent):
        super(BrowserWindow, self).__init__()
        PySide.QtWebKit.QWebView(None)
        print('init')

    def mousePressEvent(self, event):
        # prepare script to execute
        frame = self.page().mainFrame()
        scroll = frame.scrollPosition()
        x = scroll.x() + event.x()
        y = scroll.y() + event.y()
        script = self.SCRIPT_TEMPLATE.format(x, y)

        # get 'src' attribute
        obj = frame.evaluateJavaScript(script)
        if 'src' in obj:
            src = obj['src']
        else:
            src = None

        # delegate event handling to super class
        if not src:
            return super(BrowserWindow, self).mousePressEvent(event)

        # download image and set wallpaper

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    view = BrowserWindow(None)
    view.load("http://google.com")
    view.show()
    sys.exit(app.exec_())

rawDescription: Add possibility to launch commands from browser


code:
def status_display_with_comment(comment):
    def decorator(function):
        def wrapper():
            print(comment)
            print("Entering", function.__name__)
            result = function()
            print("Exited", function.__name__)
            return result
        return wrapper

    return decorator

def a_function():
    print('a_function executes')

a_function_SD_WC = status_display_with_comment('a comment')(a_function)
a_function_SD_WC()

rawDescription: A more elegant way for this python decorator


code:
while mustcontinue:
  pid, exitstat = os.wait()
  cmdline = childid.pop(pid)
  p = subprocess.Popen(cmdline.split())
  childid[p.pid] = cmdline

rawDescription: Execute and monitor multiple instances of external program in Python


code:
buffer = bytearray(8)
floats32 = np.frombuffer(buffer, dtype="<f4")
floats32[0] = 1
print(buffer) # shows buffer has been modified

rawDescription: Define Ctypes array that overlaps in memory for numpy array and multiprocessing


rawDescription: What does the [0]*x syntax do in Python?

description: What does the [0]*x syntax do in Python


code:
data = np.genfromtxt('input_file', dtype=None , delimiter=",")
print (data)

rawDescription: How to read a text file with mixed data_types automatically in Python?

description: Read a text file with mixed data_types automatically in Python


code:
from endless_pagination.templatetags.endless import PaginateNode
from endless_pagination import (
    settings,
    utils,
)

class CustomPaginateNode(PaginateNode):
    def render(self, context):
        # Handle page number when it is not specified in querystring.
        if self.page_number_variable is None:
            default_number = self.page_number
        else:
            default_number = int(self.page_number_variable.resolve(context))

        # Calculate the number of items to show on each page.
        if self.per_page_variable is None:
            per_page = self.per_page
        else:
            per_page = int(self.per_page_variable.resolve(context))

        # Calculate the number of items to show in the first page.
        if self.first_page_variable is None:
            first_page = self.first_page or per_page
        else:
            first_page = int(self.first_page_variable.resolve(context))

        # User can override the querystring key to use in the template.
        # The default value is defined in the settings file.
        if self.querystring_key_variable is None:
            querystring_key = self.querystring_key
        else:
            querystring_key = self.querystring_key_variable.resolve(context)

        # Retrieve the override path if used.
        if self.override_path_variable is None:
            override_path = self.override_path
        else:
            override_path = self.override_path_variable.resolve(context)

        # Retrieve the queryset and create the paginator object.
        objects = self.objects.resolve(context)
        paginator = self.paginator(
            objects, per_page, first_page=first_page, orphans=settings.ORPHANS,
            context=context) # <--- passing context here

    # Normalize the default page number if a negative one is provided.
    if default_number < 0:
        default_number = utils.normalize_page_number(
            default_number, paginator.page_range)

    # The current request is used to get the requested page number.
    page_number = utils.get_page_number_from_request(
        context['request'], querystring_key, default=default_number)

    # Get the page.
    try:
        page = paginator.page(page_number)
    except EmptyPage:
        page = paginator.page(1)

    # Populate the context with required data.
    data = {
        'default_number': default_number,
        'override_path': override_path,
        'page': page,
        'querystring_key': querystring_key,
    }
    context.update({'endless': data, self.var_name: page.object_list})
    return ''

rawDescription: How to do result post-processing before rendering with django endless-pagination?

description: Do result post-processing before rendering with django endless-pagination


code:
import pytz
eastern = pytz.timezone('US/Eastern')
df.index = index.tz_localize(pytz.utc).tz_convert(eastern)

rawDescription: Converting time zone pandas dataframe

description: Converting time zone pandas dataframe


rawDescription: this python script can be shortened/optimized, how?

description: This python script can be shortened/optimized, how


code:
'<text>
Ducdame was John Cowper Powys

other text
</text>'

rawDescription: Getting the whole content within the tag including html tags


code:
l = ['a', 'c', 'e', 'b']
[x for pair in zip(l,l) for x in pair]

rawDescription: Duplicate element in python list

description: Duplicate element in python list


code:
def is_vowel(w,i):
    if w[i].lower() in ['a','e','i','o','u']:
        return True
    else:
        return False

def is_consonant(w, i):
    return w[i].isalpha() and not is_vowel(w, i)

string = "Hello World!"

print(is_vowel(string, 0))
print(is_consonant(string, 0))
print(is_vowel(string, 1))
print(is_consonant(string, 1))

rawDescription: Writing def vowel(w,i):

description: Writing def vowel(w,i):


code:
def FormForUser(user):
  class TmpClass(forms.ModelForm):
    def __init__(self, *args, **kwargs):
      super(TmpClass, self).__init__(*args, **kwargs)
      self.fields['group'].queryset = user.group_set.all()

    class Meta:
      model = Project
      fields = ['group', 'another']

rawDescription: Django ModelForm with User data in Generic View


code:
def get_text_name(arg):
    temp = [x.split(': ') for x in arg]
    return temp[0][0], [t[1] for t in temp]
rating_text, rating_names = get_text_name(rating)
rating_text
rating_names

rawDescription: Extracting multiple string values of variable length before and after a delimiter in a list


rawDescription: Choosing which dictionary to use based on user input in Python


code:
ax = df.plot() # your plot
fig = ax.get_figure()
fig.savefig('image.png')

rawDescription: Python pandas.io.data save plot?

description: Python pandas.io.data save plot


code:
import re

pattern  = '(?:[a-z]{3}|[A-Z]{3}|\d{3}|[\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]{3})'
password = 'y8kpBD8zcZLKRSh1j7vwCMDQ5orR8VEP!'
matches  =  re.search(pattern, password)

rawDescription: Finding a recurrance of three ASCII families in a string


code:
df = d1.merge(d2, how='right', on='a')
df['sum'] = df.b + df.d
df

rawDescription: Pandas: how to broadcast values by specific column rather than index when doing arithmetic operation?


rawDescription: Alternatives to variable-width lookbehind in Python regex


code:
code_block = compile(open('other.py').read(), 'other.py', 'exec')
blob = {}
exec(code_block, blob)
print("blob %s" % blob['toto'])

rawDescription: Python 2 How to debug code injected by the exec block


code:
def fn(match):
  return unichr(int(match.group(1)))

re.sub('&#([^;]*);', fn, inputtext, flags=re.UNICODE)

rawDescription: python re.sub with variable

description: Python re.sub with variable


code: new_date_list, flipkart_sale_list, paytm_sale_list = map(list, zip(*sorted_lists))

rawDescription: python sort lists from 1 list based on date elements

description: Python sort lists from 1 list based on date elements


rawDescription: Naming returned columns in Pandas aggregate function?


code:
counts = {}
for i in file_list:
    counts.setdefault(i.extension, 0)
    counts[i.extension] += 1

rawDescription: Counting entries with Python dictionary datatype


code:
res=[]
res

rawDescription: How to clean up this string in python with strip?

description: Clean up this string in python with strip


code:
import datetime
target_time = datetime.datetime(2014, 8, 1, 14, 0, 0)
now = datetime.datetime.now()
time_to_go = target_time - now
print(time_to_go)

rawDescription: Python: TimeDate Issue

description: Python: TimeDate Issue


code: {year: strip_year(winner, year) for year, winner in enumerate(winners, 1903)}

rawDescription: Add a Year to each item in list or Dictionary


rawDescription: How to import a single function to my main.py in python from another module?

description: Import a single function to my main.py in python from another module


code:
from collections import defaultdict
import csv
from operator import and_
import re

DATAFILE = "data-download-pub78.txt"

def get_words(s):
    return re.findall("[a-z]+", s.lower())

def build_index(items):
    word_index = defaultdict(set)
    ein_index = {}
    for ein, name in items:
        for word in get_words(name):
            word_index[word].add(name)
        ein_index[name] = ein
    return word_index, ein_index

with open(DATAFILE, "rb") as inf:
    incsv = csv.reader(inf, delimiter="|")
    items = (row[:2] for row in incsv if len(row) >= 2)
    words, eins = build_index(items)

def find_matches(s):
    wordlst = (words[wd] for wd in get_words(s))
    charities = reduce(and_, wordlst)
    res = [(eins[ch], ch) for ch in charities]
    res.sort(key=lambda x: int(x[0]))
    return res

def main():
    while True:
        s = raw_input("Enter all or part of a charity name, or nothing to quit: ").strip()
        if s:
            charities = find_matches(s)
            if charities:
                print("{} matches:".format(len(charities)))
                for ch in charities:
                    print("{}: {}".format(*ch))
                print("")
            else:
                print("No matches found.")
        else:
            break

if __name__=="__main__":
    main()

rawDescription: Grabbing Nonprofit EINs through scraping Guidestar or Citizenaudit search results


code:
if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        server_name = sys.argv[1]
    else:
        server_name = '127.0.0.1'
    print('\n'.join(sorted(list_shares(server_name))))

rawDescription: How to list remote windows host shared directories in Python?

description: List remote windows host shared directories in Python


code:
from scrapy.http.request import Request

def start_requests(self):
    for i in xrange(1, 100):
        url = 'www.examples.com/sports/companies?searchTerm=news+sports&pg=' + i
        yield Request(url=url, callback=parse_torrent)

rawDescription: Specifying rules in the Linkextractors in scrapy


code: cur.execute('INSERT INTO my_passwords VALUES (?)', self.create_password())

rawDescription: Get Return Value from one function and use on another


code:
import statsmodels.api as smf
res = smf.load('results.pickle')
res.predict(...)

rawDescription: Provide your own coefficients in Pandas regression


code:
import csv

with open('original.txt','r') as f, open('new.txt','w') as o:
   reader = csv.reader(f, delimiter=' ')
   writer = csv.writer(o, delimiter=' ')
   for row in reader:
       if len(row) == 12 and row[0]:
           writer.write(row)

rawDescription: How to delete lines in a file in Python?

description: Delete lines in a file in Python


code:
while '  ' in lines:  # notice the two-spaces-string
    lines = lines.replace('  ', ' ')
columns = [line.split(' ')[:2] for line in lines.split('\n') if line]

rawDescription: Suggestion for python regex and selecting columns


code:
def setup_worker2(queue):
    global x
    x = random.random()
    global a_queue, a, clockExp

    a_queue = queue
    a = a_queue.get()    # wait for the first `a` value
    clockStart = dt.datetime.now()
    clockExp = clockStart + dt.timedelta(seconds=900)

def worker2(item):
    global a, clockExp

    clockCur = dt.datetime.now()
    clockRem = (clockExp - clockCur).total_seconds()
    if clockRem < 60: # start checking for a new `a` value 60 seconds before its needed
        try:
            a = a_queue.get_nowait()
            clockStart = dt.datetime.now()
            clockExp = clockStart + dt.timedelta(seconds=900)
        except queue.Empty:
            pass

    return f(item, a)

def main2(L):
    queue = multiprocessing.Queue()     # setup the queue for the a values

    pool = multiprocessing.Pool(initializer=setup_worker2, initargs=(queue,))

    result = pool.map_async(worker2, L) # send the items to the pool asynchronously

    while True:                   # loop for sending a values through the queue
        a = getRenewed()          # get a new item
        for _ in range(os.cpu_count()):
            queue.put(a)          # send one copy per worker process

        try:
            result.wait(900-5)    # sleep for ~15 minutes, or until the result is ready
        except multiprocessing.TimeoutError:
            pass                  # if we got a timeout, keep looping!
        else:
            break                 # if not, we are done, so break out of the loop!

rawDescription: Multiprocessing subject to timer

description: Multiprocessing subject to timer


code:
exams = Exam.objects.all()
total_score = 0
total_submitted = 0
passed = 0
for exam in exams:
    total_score += exam.score
    if exam.submitted:
        total_submitted += 1
    if exam.score >= 80:
        passed += 1
exam_aggregates = {
    'average': total_score / len(exams),
    'submitted': total_submitted,
    'passed': passed,
}

rawDescription: Using Django Count() with conditional lookup types


code: df.loc[df.index < ts] #ts is the timestamp

rawDescription: Subset Pandas Dataframe Everything up to a Date


rawDescription: unpack function in python

description: Unpack function in python


code: card_text = spades.pop(Fa)

rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
from decimal import Context
Context(prec=60).exp(1)

rawDescription: What is the largest number the Decimal class can handle?


rawDescription: Finding and deleting repeated data entries with two identical features identified by a third unique feature


code: ("NORTH " if b > 0 else "SOUTH ") + ("EAST" if a > 0 else "WEST")

rawDescription: How to shorten this if and elif code in Python

description: Shorten this if and elif code in Python


code:
class ModelNameAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super(ModelnameAdmin, self).save_model(request, obj, form, change)
        # Your code will follow ...

rawDescription: django admin hook run code from super

description: Django admin hook run code from super


code:
from pylab import *

x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")

# now get the figure size in real coordinates:
fig  = gcf()
fwidth = fig.get_figwidth()
fheight = fig.get_figheight()

# get the axis size and position in relative coordinates
# this gives a BBox object
bb = ax.get_position()

# calculate them into real world coordinates
axwidth = fwidth * (bb.x1 - bb.x0)
axheight = fheight * (bb.y1 - bb.y0)

# if the axis is wider than tall, then it has to be narrowe
if axwidth > axheight:
    # calculate the narrowing relative to the figure
    narrow_by = (axwidth - axheight) / fwidth
    # move bounding box edges inwards the same amount to give the correct width
    bb.x0 += narrow_by / 2
    bb.x1 -= narrow_by / 2
# else if the axis is taller than wide, make it vertically smaller
# works the same as above
elif axheight > axwidth:
    shrink_by = (axheight - axwidth) / fheight
    bb.y0 += shrink_by / 2
    bb.y1 -= shrink_by / 2

ax.set_position(bb)

show()

rawDescription: Drawing log-linear plot on a square plot area in matplotlib


code:
for i in executor.map(fct, v1, v2):
    print(str(i))

rawDescription: How to print results of Python ThreadPoolExecutor.map immediately?

description: Print results of Python ThreadPoolExecutor.map immediately


code:
df=pd.DataFrame({ 'id_int':np.random.randint(1,5,20) })
df['id_cat'] = df.id_int.astype('category')
df.dtypes
df.memory_usage()

rawDescription: Pandas describe() behaviour for numeric dtypes


code: [i for i,x in enumerate(stuff) if x == "baz"]

rawDescription: Emulate index method with generator

description: Emulate index method with generator


rawDescription: Using File IO to create matrix

description: Using File IO to create matrix


code:
def __init__(self, source=None, collidetext=None):
    super(Npcs, self).__init__(source=source)
    self.collidetext=collidetext

rawDescription: How to assign attributes to an instance during creation?

description: Assign attributes to an instance during creation


code: df

rawDescription: Python Pandas - Split different entries into separate rows allowing only certain combinations


code: df['Strain Name'] = df['Strain Name'].str.split('(').apply(lambda x: max(x, key=len))

rawDescription: pandas DataFrame conditional string split

description: Pandas DataFrame conditional string split


code: history.pushState(someState, "some title", "page.html");

rawDescription: Django jquery ajax

description: Django jquery ajax


rawDescription: Combining REs that can match multiple messy stock entries


code:
from datetime import datetime

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

FROM = "Leeds Bradford"
TO = "Antalya"

driver = webdriver.Firefox()
driver.get("http://jet2.com/")
driver.maximize_window()

wait = WebDriverWait(driver, 90)
actions = ActionChains(driver)

# wait for the page to load
wait.until(EC.element_to_be_clickable((By.ID, "return-flight-selector")))

# fill out the form
return_flight = driver.find_element_by_id('return-flight-selector').click()

depart_from = driver.find_element_by_id("departure-airport-input")
depart_from.clear()
depart_from.click()
depart_from.send_keys(FROM)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#ui-id-1 .ui-menu-item"))).click()

go_to = driver.find_element_by_id("destination-airport-input")
go_to.send_keys(TO)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#ui-id-2 .ui-menu-item"))).click()

# select depart date
datepicker = driver.find_element_by_id("departure-date-selector")
actions.move_to_element(datepicker).click().perform()

# find the calendar, month and year picker and the current date
calendar = driver.find_element_by_id("departureDateContainer")
month_picker = Select(calendar.find_element_by_class_name("ui-datepicker-month"))
year_picker = Select(calendar.find_element_by_class_name("ui-datepicker-year"))
current_date = calendar.find_element_by_class_name("ui-datepicker-days-cell-over")

# printing out current date
month = month_picker.first_selected_option.text
year = year_picker.first_selected_option.text
print("Current departure date: {day} {month} {year}".format(day=current_date.text, month=month, year=year))

# see if we have an available date in this month
try:
    next_available_date = current_date.find_element_by_xpath("following::td[@title='Click to see flights on this date' and ancestor::div/@id='ui-datepicker-div']")
except NoSuchElementException:
        while True:
            try:
                calendar.find_element_by_class_name("ui-datepicker-next").click()
            except NoSuchElementException:
                year_picker = Select(calendar.find_element_by_class_name("ui-datepicker-year"))
                year_picker.select_by_visible_text(str(int(year.first_selected_option.text) + 1))

            try:
                next_available_date = calendar.find_element_by_xpath(".//td[@title='Click to see flights on this date']")
                break
            except NoSuchElementException:
                continue

month_picker = Select(calendar.find_element_by_class_name("ui-datepicker-month"))
year_picker = Select(calendar.find_element_by_class_name("ui-datepicker-year"))

month = month_picker.first_selected_option.text
year = year_picker.first_selected_option.text

depart_date = datetime.strptime(" ".join([next_available_date.text, month, year]), "%d %b %Y")
next_available_date.click()

initial_return_date = depart_date.strftime("%d-%m-%Y")

return_date_input = driver.find_element_by_id("return-date-selector")
# remove readonly and disabled attributes
driver.execute_script("arguments[0].removeAttribute('disabled'); arguments[0].removeAttribute('readonly','readonly');", return_date_input)

# set the initial return date
return_date_input.clear()
return_date_input.send_keys(initial_return_date)

# open datepicker
return_date_input.click()

rawDescription: Store a date selected from one datepicker into the next datepicker


code:
class RedButton(Button):

    def __init__(self, parent, **options):
        Button.__init__(self, parent, bg='red', **options)

rawDescription: Adding a hovering option to my buttons in a class


code:
from collections import deque
fname = "source.txt"
last_lines = deque(maxlen = 4)
for line in open(fname):
  last_lines.append(line)
#file is closed when we leave the (for) block

outfname = fname
with open(outfname, "w") as of:
  for line in last_lines:
    of.write(line)

rawDescription: Python: splitlines() from text file then write them back to text file


code:
x =df.pivot(index='Dates', columns='week_days', values='data')
x.boxplot()

rawDescription: Best way to generate day-of-week boxplots from a Pandas timeseries

description: Generate day-of-week boxplots from a Pandas timeseries


code:
import csv
import re

key_value = re.compile('(?P<key>[A-Z]+)=(?P<value>[^\s=;]+)(?:(?=;)|$)')

with open(inputfilename) as infile, open(outputfilename, 'wb') as outfile:
    writer = csv.DictWriter(outfile, ('PERSON', 'HEIGHT', 'WEIGHT', 'AGE'), delimiter='\t')
    writer.writeheader()

    for line in infile:
        person = line.split('\t', 1)[0]
        row = dict(key_value.findall(line))
        row['PERSON'] = person
        writer.writerow(row)

rawDescription: Python - Extract and reformat field names from rows of data


code: any([False, True, False]) # returns True

rawDescription: Using the split function

description: Using the split function


rawDescription: Why does my negative slicing in Python not work?


code: writer = csv.writer(open("%s.csv" % filename, "wb"))

rawDescription: Parsing HTML rows into CSV

description: Parsing HTML rows into CSV


code:
import numpy as np
from scipy.sparse import coo_matrix

data = cursor.fetchall()
#data = [(1, 2, 1.2), (3, 4, 7.1)]

arr = np.array(data, dtype=[('row', int), ('col', int), ('value', float)])
spmat = coo_matrix((arr['value'], (arr['row'], arr['col'])))

rawDescription: Efficiently read a Python sparse matrix from SQL


code: choices = ['Arkansas', 'Manchuria', 'Bengal', 'Baja California']   # etc.

rawDescription: Print a variable selected by a random number


code:
list(dfs(data))
sorted(dfs(data), key=lambda x: x[0])

rawDescription: Inserting an element in list, at exact location, without array sizing in Python?


rawDescription: How do I capture multiple patterns from a line in python?

description: Capture multiple patterns from a line in python


rawDescription: Python Basics: How can i set two function parameters in equations?


code:
source
from pprint import pprint
import salt.client
local = salt.client.LocalClient()
pprint( local.cmd_full_return(
    '*', 'test.ping', verbose=True,
    ) )

rawDescription: Getting output of highstate from python code


code:
def print_chunks(chunk_result):
    for chunk in chunks:
        print(chunk)

rawDescription: Split python list into rows without libraries


code:
def Rabin_Karp_Matcher(text, pattern, d, q):
    n = len(text)
    m = len(pattern)
    h = pow(d,m-1)%q
    p = 0
    t = 0
    result = []
    for i in range(m): # preprocessing
        p = (d*p+ord(pattern[i]))%q
        t = (d*t+ord(text[i]))%q
    for s in range(n-m+1): # note the +1
        if p == t: # check character by character
            match = True
            for i in range(m):
                if pattern[i] != text[s+i]:
                    match = False
                    break
            if match:
                result = result + [s]
        if s < n-m:
            t = (t-h*ord(text[s]))%q # remove letter s
            t = (t*d+ord(text[s+m]))%q # add letter s+m
            t = (t+q)%q # make sure that t >= 0
    return result
print (Rabin_Karp_Matcher ("3141592653589793", "26", 257, 11))
print (Rabin_Karp_Matcher ("xxxxx", "xx", 40999999, 999999937))

rawDescription: Python: Rabin-Karp algorithm hashing

description: Python: Rabin-Karp algorithm hashing


code: patches[0].set_hatch('/')  # Pie slice #0 hatched.

rawDescription: How can I add textures to my bars and wedges?

description: Add textures to my bars and wedges


code:
import logging
logger = logging.getLogger("mypackage.mymodule")  # or __name__ for current module
logger.setLevel(logging.ERROR)

rawDescription: Change Flask logs from INFO to DEBUG

description: Change Flask logs from INFO to DEBUG


code:
import pandas
from io import StringIO

csv = StringIO("""index,A,B
0,1,0.0
1,1,3.0
2,1,6.0
3,2,0.0
4,2,5.0
5,2,7.0""")

df = pandas.read_csv(csv, index_col='index')
groups = df.groupby(by=['A'])
print(groups.apply(lambda g: g[g['B'] == g['B'].max()]))

rawDescription: Python pandas - filter rows after groupby


code:
from distutils.core import setup
import os, sys
import py2exe
from glob import glob
import PyQt5

NAME="ProgName"

qt_platform_plugins = [("platforms", glob(PyQt5.__path__[0] + r'\plugins\platforms\*.*'))]
data_files.extend(qt_platform_plugins)
msvc_dlls = [('.', glob(r'C:\Windows\System32\msvc?100.dll'))]
data_files.extend(msvc_dlls)
# print(data_files)

sys.argv.append('py2exe')

setup(
    data_files=data_files,
    # windows=["pyftp1.py",],
    windows=[
        {
            "script": "pyftp1.py",
            "icon_resources": [(0, "resources/favicon.ico")]
        }
    ],
    # zipfile=None,
    options={
        "py2exe": {
            "includes":["sip", "atexit",],
            # "packages": ['PyQt5'],
            "compressed": True,
            "dist_dir": "dist/" + NAME,
            # "bundle_files": 0,
            # "zipfile": None,
            "optimize": 2,
        }
    }
)

rawDescription: exe built with cx_Freeze, PyQt5, Python3 can't import ExtensionLoader_PyQt5_QtWidgets.py and run

description: Exe built with cx_Freeze, PyQt5, Python3 can't import ExtensionLoader_PyQt5_QtWidgets.py and run


code:
lst = [1,2,4,5]
map(lambda x: 'lower' if x < 3 else 'higher', lst)

rawDescription: using a conditional and lambda in map

description: Using a conditional and lambda in map


code:
RegionsOfInterest = ("2_10","15_18")

ListOfRegionsOfInterest = []
for i in range(0, len(RegionsOfInterest)):
    Start = int(RegionsOfInterest[i].split("_")[0])
    Stop  = int(RegionsOfInterest[i].split("_")[1])
    RegionOfInterest = (Start, Stop)
    ListOfRegionsOfInterest.append( RegionOfInterest )

i = 10

falls_into_a_region_of_interest = False
for x, y in ListOfRegionsOfInterest:
    if i >= x and i <= y:
        falls_into_a_region_of_interest = True
        break

rawDescription: if statement depending on list len

description: If statement depending on list len


code:
dict3 = {}
for key in dict1:
    if key in dict2:
        dict3[dict1[key]] = dict2[key]

rawDescription: Merge 2 dictionaries in Python

description: Merge 2 dictionaries in Python


code:
if 'paul' in boys:
    print(boys['paul'].age)
    print(boys['paul'].height)
else:
    print('no boy called paul')

rawDescription: in python is it possible to use/execute a string within a list as an object name

description: In python is it possible to use/execute a string within a list as an object name


code:
lower_bound = [0.2, 0.7, 1.5]
upper_bound = lower_bound[1:] + [np.inf]

for i in range(len(lower_bound)):
    mask = (flat >= lower_bound[i]) & (flat < upper_bound[i])
    flat[mask] = func(flat[mask], i)

rawDescription: How to modify a Numpy array with conditional and function

description: Modify a Numpy array with conditional and function


code:
'foo' * 100 is 'foo' * 100
intern('foo' * 100) is intern('foo' * 100)

rawDescription: The most effective way to assign unique integer id to a string?


code:
class Metric(object):
    def __init__(self, *args):
        if not len(args) == 2:
            raise ValueError("Usage: Metric([values],[percentiles])")
        values, percentiles = args
        self.max = max(values)
        self.median =np.median(values)
        self.min = min(values)
        self.percentile = get_percentile(values, percentiles)

rawDescription: Python: resolve problems with my Class

description: Python: resolve problems with my Class


code:
def apply_something(something, config, some_var):
    pass  # ...

import functools

reduce(functools.partial(apply_something, some_var=True),
       [1, 2, 3], something_initializer)

rawDescription: Passing more than two arguments in reduce function


code: prime = {x for x in range(2, 100) if all(x % y != 0 for y in range(2, x))}

rawDescription: Python generating prime numbers using Set Comprehension


rawDescription: Python , Printing Hex removes first 0?

description: Python , Printing Hex removes first 0


code:
import csv

with open(yourfile, 'rb') as infile:
    reader = csv.reader(infile)
    result = {c[0]: c[1:] for c in zip(*reader)}

rawDescription: reading of csv into dictionary, first line becomes the name

description: Reading of csv into dictionary, first line becomes the name


code:
def makeNumber(t):
    sum (10 ** i * e for i, e in enumerate(t[::-1]))
x = [[1,2,3], [4,5,6], [7,8,9]]
print([makeNumber(x) for x in it.product(*x)])

rawDescription: Print out all combinations of elements in an array of arrays


code:
df['value'] = values[:len(df)]
df

rawDescription: calculating rolling mean pandas with time-weighted values

description: Calculating rolling mean pandas with time-weighted values


code:
import numpy as np

def sigmoid(z):
    return 1 / (1+np.exp(-z))

def sigmoid_gradient(z):
    return sigmoid(z)*(1-sigmoid(z))

def randInitializeWeights(layer_in, layer_out):
    matrix = np.zeros((layer_out, 1 + layer_in))
    epsilon_init = 0.12
    matrix = np.random.rand(layer_out, 1+layer_in) * 2 * epsilon_init -epsilon_init
    return matrix

def gradient(theta, *args):

    X, y, num_inputs, num_hidden_units, num_labels, lamb = args

    m = len(X)

    y_bin = np.zeros((m, num_labels))

    for i in range(m):
        y_bin[i, y[i]] = 1

    theta1 = np.reshape(theta[0:(num_hidden_units*(num_inputs+1))],(num_hidden_units, (num_inputs+1)))  #5x4
    theta2 = np.reshape(theta[(num_hidden_units*(num_inputs+1)):],(num_labels, num_hidden_units+1))     #3x6

    theta1_grad = np.zeros(theta1.shape)
    theta2_grad = np.zeros(theta2.shape)

    delta1 = np.zeros(theta1.shape)
    delta2 = np.zeros(theta2.shape)

    #forward

    a_1 = np.hstack((np.ones((m, 1)), X))   #5x4

    z_2 = np.dot(a_1, theta1.transpose())   #5x5
    a_2 = sigmoid(z_2)                      #5x5

    a_2 = np.hstack((np.ones((m, 1)), a_2)) #5x6
    z_3 = np.dot(a_2, theta2.transpose())   #5x3

    h = sigmoid(z_3)                        #5x3

    #backward

    delta3 = h - y_bin                      #5x3
    delta2 = np.dot(delta3, theta2[:, 1:num_hidden_units+1]) * sigmoid_gradient(z_2) #5x5

    D1 = np.dot(delta2.transpose(), a_1)    #5x4
    D2 = np.dot(delta3.transpose(), a_2)    #3x6

    theta1_grad = D1/m      #5x4
    theta2_grad = D2/m      #3x6

    #regularization
    theta1_grad[:, 1:num_inputs+1] = theta1_grad[:, 1:num_inputs+1] +lamb/m*  theta1[:, 1:num_inputs+1]
    theta2_grad[:, 1:num_hidden_units+1] = theta2_grad[:, 1:num_hidden_units+1] +lamb/m*  theta2[:, 1:num_hidden_units+1]

    #unroll
    grad = np.hstack([theta1_grad.ravel(), theta2_grad.ravel()])
    return grad

def gradientChecking(lamb):
    input_layer_size = 3
    hidden_layer_size = 5
    num_labels = 3
    m = 5

    theta1 = randInitializeWeights(input_layer_size, hidden_layer_size)
    theta2 = randInitializeWeights(hidden_layer_size, num_labels)

    X = np.random.rand(m, input_layer_size)
    y = np.array([1, 2, 0, 1, 2])

    nn_params = np.hstack([theta1.ravel(), theta2.ravel()])

    #calculate gradient with function
    grad = gradient(nn_params, X, y, input_layer_size, hidden_layer_size, num_labels, lamb)
    #calculate numerical gradient
    num_grad = computeNumericalGradient(lambda theta: computeCost(theta, X, y, input_layer_size, hidden_layer_size, num_labels, lamb), nn_params)

    print('Function Gradient', 'Numerical Gradient')
    for i in range(len(grad)):
        print(grad[i], num_grad[i])

    diff = np.linalg.norm(num_grad-grad)/np.linalg.norm(num_grad+grad)
    print('Relative Difference: ')
    print(diff)

def computeCost(theta, X, y, num_inputs, num_hidden_units, num_labels, lamb):

    m = len(X)

    y_bin = np.zeros((m, num_labels))

    for i in range(m):
        y_bin[i, y[i]] = 1

    theta1 = np.reshape(theta[0:(num_hidden_units*(num_inputs+1))],(num_hidden_units, (num_inputs+1))) #5x4
    theta2 = np.reshape(theta[(num_hidden_units*(num_inputs+1)):],(num_labels, num_hidden_units+1)) #3x6

    a_1 = np.hstack((np.ones((m, 1)), X))   #5x4

    z_2 = np.dot(a_1, theta1.transpose())   #5x5
    a_2 = sigmoid(z_2)                      #5x5

    a_2 = np.hstack((np.ones((m, 1)), a_2)) #5x6
    z_3 = np.dot(a_2, theta2.transpose())   #5x3

    h = sigmoid(z_3)

    cost = np.sum(-y_bin * np.log(h)    -    (1-y_bin) * np.log(1-h))/m

    #regularization

    theta1_sq = theta1[:, 1:num_inputs+1] * theta1[:, 1:num_inputs+1];
    theta2_sq = theta2[:, 1:num_hidden_units+1] * theta2[:, 1:num_hidden_units+1];

    cost = cost + lamb/(2.0*m)*(np.sum(theta1_sq) + np.sum(theta2_sq))

    return cost

def computeNumericalGradient(J, theta):
    numgrad = np.zeros(theta.shape)
    perturb = np.zeros(theta.shape)
    e = 0.0001

    for p in range(1, np.size(theta)):
        perturb[p] = e
        loss1 = J(theta - perturb)
        loss2 = J(theta + perturb)

        numgrad[p] = (loss2 - loss1) / (2*e)
        perturb[p] = 0
    return numgrad

gradientChecking(1.0)

rawDescription: Trying to understand Gradient Checking error in 3-layer Neural Network


code:
import numpy as np
np_split_indexes= np.where(np.diff(np.diff(testcase))!=0)[0]+2
split_indexes= [0] + list(np_split_indexes) + [len(testcase)]
result= [testcase[a:b] for a,b in zip(split_indexes[:-1],split_indexes[1:])]

rawDescription: Finding all maximal monotone subsequences in python


code: listz = [list(i) for i in zip(listx, listy)]

rawDescription: Any way to zip to list of lists?

description: Any way to zip to list of lists


code: final1 = [i for i in words if i in "ATGC"]

rawDescription: How do I loop through a list?

description: Loop through a list


code: l = list(takewhile(lambda x: x < 10000, generate()))

rawDescription: Python Generator Cutoff

description: Python Generator Cutoff


code:
import re

from bs4 import BeautifulSoup

def filter_links(link):
    href = link and link.get('href')

    return all([
        link,
        link.name == 'a',
        href,
        not link.has_attr('no_track'),
        not href.startswith('mailto'),
        '{' not in target,
        not href.startswith('#')
    ])

content = "%s %s" % (self.html_body, self.plaintext)
pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')

soup = BeautifulSoup(content, "html5lib")

links = []
for link in soup.find_all(filter_links):
    target = link['href']
    name = link.get('data-name')

    target = pattern.search(target)
    if target:
        links.add({
            'name': name,
            'target': target.group()
        })

rawDescription: Python Beautifulsoup find unique links

description: Python Beautifulsoup find unique links


code: path = raw_input("Enter file and path")

rawDescription: Python, loop through files in a folder and do a word count


code:
import requests
from bs4 import BeautifulSoup

data = requests.get('http://epi.hbsna.com/products/dept.asp?msi=0&sid=6076533CE8C648AE9883BDDBED795B29&dept_id=315&parent_id=0').content
soup = BeautifulSoup(data, "html.parser")

table = soup.find(text="SKU#").find_parent("table")
for row in table.find_all("tr")[1:]:
    print([cell.get_text(strip=True) for cell in row.find_all("td")])

rawDescription: Locating table with no id or class attributes


code: df.groupby(pd.TimeGrouper(freq='15Min', base=df.index[-1].minute, closed='right', label='right')).sum()

rawDescription: How to do a group by in pandas of N observatios

description: Do a group by in pandas of N observatios


code:
x = input('Type the first name: ')
next(second for first, second in list if first == x)

rawDescription: Result the second element of a list in python


code:
from nltk.stem import snowball
stemmer = snowball.EnglishStemmer()
stemmer.stem('thee')
dir(stemmer)
stemmer._EnglishStemmer__special_words
stemmer._EnglishStemmer__special_words['thee'] = 'thou'
stemmer.stem('thee')

rawDescription: How to Stem Shakespere/KJV Using nltk.stem.snowball


rawDescription: actual objects and its references in python

description: Actual objects and its references in python


rawDescription: How to sort a nested dictionary by a nested key

description: Sort a nested dictionary by a nested key


code:
facebook.com
stackoverflow.com

rawDescription: mechanize - how to select links based on adjacent tags?

description: Mechanize - how to select links based on adjacent tags


code:
from django.db.models import Q

class QQ:
    def __xor__(self, other):
        not_self = self.clone()
        not_other = other.clone()
        not_self.negate()
        not_other.negate()

        x = self & not_other
        y = not_self & other

        return x | y

Q.__bases__ += (QQ, )

rawDescription: Perform a logical exclusive OR on a Django Q object


code:
import json
json_dict = json.loads('[{"id": "532befe4ee434047ff968a6e","company": "528458c4bbe7823947b6d2a3","values": [{"Value": "11","uniqueId": true},{"Value": "14","uniqueId": true}]},{"id": "532befe4ee434047ff968a","company": "528458c4bbe7823947b6d","values": [{"Value": "1111","uniqueId": true},{"Value": "10","uniqueId": true}]}]')

expected_values = []

js = json_dict[0]
for key,value in js.items():
    if key == 'values':
        expected_values.append(value[0]['Value'])

rawDescription: Django filtering based on list value

description: Django filtering based on list value


code: x=["co"+i+"e" for i in string.lowercase]

rawDescription: Return the number of times that the string "code" appears anywhere in the given string


code:
def finish(self, event):
    self.save()
    self.Destroy()
    sys.exit()

def save(self):
    windtitle = self.windtitle.GetLabelText()
    checkboxes = [{'checked': child.IsChecked(),
                   'label': child.GetLabel()}
                  for child in self.panel.GetChildren()
                  if isinstance(child, wx.CheckBox)]
    data = {
        'windtitle':windtitle,
        'checkboxes':checkboxes,
        }
    with open(CONFIGFILE, 'w') as f:
        json.dump(data, f)

rawDescription: Python - Saving state of a program between restarts?


code:
# main.py file
"""
Main module documentation (optional)
"""
# import modules

# function and class definitions

def main(*argv):
    # Parses the options (optional)
    import optparse
    parser = optparse.OptionParser(usage="%prog [<options>]\n" + __doc__)
    parser.add_option(...)
    parser.add_option(...)
    opt, args = parser.parse_args(list(argv))
    # Calls the appropriate function:
    my_function(...)

rawDescription: Compile a .pyw file so it can be run like .pyc without console


rawDescription: Finding the closest point(s) by ranking them


code:
from django.forms import ModelForm
from .models import Deal

class DealForm(ModelForm):
    class Meta:
        model = Deal
        fields = ['title', 'url']

rawDescription: Python/Django handling HTTP requests in the right way


rawDescription: Create new lists by adding elements

description: Create new lists by adding elements


code:
def add_property(inst, name, method):
    '''
    Adds a property to a class instance.
    Property must be added to the CLASS.
    '''
    cls = type(inst)

    if not hasattr(cls, '__perinstance'):
        cls = type(cls.__name__, (cls,), {})
        cls.__perinstance = True
        inst.__class__ = cls

    setattr(cls, name, property(method))

rawDescription: How to lock a method in python (prevent it to be overwritten)?

description: Lock a method in python (prevent it to be overwritten)


code:
import datetime
import random
import dateutil.relativedelta as dr
import itertools

day_of_week = [1,3,5,6]
hour = [1,10,15,17,20]
minute = [4,34,51,58]

now=datetime.datetime.now()
deltas=[]

for min,hr,dow in itertools.product(minute,hour,day_of_week):
    # dateutil convention: Monday = 0, Sunday = 6.
    next_dt=now+dr.relativedelta(minute=min,hour=hr,weekday=dow)
    delta=next_dt-now
    deltas.append(delta)

deltas.sort()

rawDescription: How to calculate timedelta until next execution for scheduled events

description: Calculate timedelta until next execution for scheduled events


code:
# get the logger instance
logger = logging.getLogger("main_logger.sub_module_logger")
# no configuration needed
# it inherits the configuration from the parent logger
...

rawDescription: python logging ensure a handler is added only once

description: Python logging ensure a handler is added only once


code:
data = '2010 Ferrari 599XX'.split(None, 1)
'|{}||'.format(data[0])

rawDescription: Adding characters to certain laces in string


code:
auxset = set(mylist)
for x in range(100):
  if x not in auxset:
    auxset.add(x)
    mylist.append(x)  # or whatever

rawDescription: in a loop, only add to a dictionary or list or tuple if doesn't contains the key

description: In a loop, only add to a dictionary or list or tuple if doesn't contains the key


code:
for name in root.findall(".//team/members/*/style"):
    print(name.text)

rawDescription: Read subelement of node values of an xml in python


code:
from contextlib import contextmanager
from sqlalchemy.orm import scoped_session, sessionmaker

class DbContext(object):
    def __init__(self, engine, session=None):
        self._engine = engine
        self._session = session or scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self._engine))
        self.query = self._session.query_property()
        self.current_session = None

    def start_session(self):
        self.current_session = self._session()

    def end_session(self):
        if self.current_session:
            self.current_session.commit()
            self.current_session.close()
        self.current_session = None

    @contextmanager
    def new_session(self):
        try:
            self.start_session()
            yield
        finally:
            self.end_session()

rawDescription: SQLAlchemy freezing application

description: SQLAlchemy freezing application


code: [[i for sub in combo for i in sub] for combo in zip(*inputlist)]

rawDescription: Arranging nested lists in python

description: Arranging nested lists in python


code:
print(MySQLCheck(host="localhost", user="root", password="pass"))
# Later, when I started the server:
# Later, when I started MySQL server with "--skip-grant-tables" option:

rawDescription: How to check a given MySQL server connects through Python?

description: Check a given MySQL server connects through Python


code:
timeit.timeit('with_heapq(the_dict)', 'from __main__ import the_dict, with_heapq', number=1000)
timeit.timeit('with_sorted(the_dict)', 'from __main__ import the_dict, with_sorted', number=1000)

rawDescription: How to maintain dictionary in a heap in python?

description: Maintain dictionary in a heap in python


code:
df['UserId'] = df['Username'].map(segment_dict)

new_users = df[pd.isnull(df['UserId'])]['Username'].unique()
for u in new_users:
    segment_dict[u] = unique_ids
    unique_ids += 1

rawDescription: Python Optimizations for basic CSV file

description: Python Optimizations for basic CSV file


code:
timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"\s*");s="          hello world!"*100', number=100000)
timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s="          hello world!"*100', number=100000)
timeit.timeit('s[:-len(s.lstrip())]', 's="          hello world!"*100', number=100000)

rawDescription: Grab a line's whitespace/indention with Python


code:
def get_averages(data):
    result = [average_daily_views(movie, customer, data) for customer in
              data[movie] for movie in data]

rawDescription: most pythonic way to calculate the average

description: Most pythonic way to calculate the average


code:
#! /usr/bin/python3
import datetime

def timerange(start, stop, step = datetime.timedelta(minutes = 15)):
    t = datetime.datetime(2000, 1, 1, start.hour, start.minute)
    stop = datetime.datetime(2000, 1, 1 if start <= stop else 2, stop.hour, stop.minute)
    while t < stop:
        yield t.time()
        t += step

rawDescription: Adjust start and end range for time list in Python


rawDescription: How to specify test timeout for python unittest?

description: Specify test timeout for python unittest


code: _command = "{} && cd {} && {} && {}".format(_driver, _path, _settings["compile"], _settings["exec"])

rawDescription: python 3 open terminal and run program

description: Python 3 open terminal and run program


code:
import StringIO
import numpy as np

def convert_m(fname):
    with open(fname, 'r') as fin:
        arrstr = fin.read()
    arrstr = arrstr.split('[', 1)[-1] # remove the content up to the first '['
    arrstr = arrstr.rsplit(']', 1)[0] # remove the content after ']'
    arrstr = arrstr.replace(';', '\n') # replace ';' with newline
    return StringIO.StringIO(arrstr)

rawDescription: Create numpy array from matrix declared inside .m matlab file


code:
class PrintJob:
    def __init__(self, name, pages):
        self.name = name
        self.pages = pages
        self.remaining = pages

    def tick(self):
        if self.remaining:
            self.remaining -= 1
        print("Job {}: {} / {} pages remain".format(self.name, self.remaining, self.pages))

    def is_done(self):
        return self.remaining == 0

class JobQueue:
    def __init__(self):
        self.jobs = []

    def enqueue(self, job):
        self.jobs.append(job)

    def dequeue(self):
        return self.jobs.pop(0)

    def is_empty(self):
        return not self.jobs

class Printer:
    def __init__(self, name, job_queue):
        self.name = name
        self.job_queue = job_queue
        self.current_job = None

    def tick(self):
        # make sure we have a job to work on
        if self.current_job is None:
            if self.job_queue.is_empty():
                print("Printer {} is idle".format(self.name))
                return
            else:
                self.current_job = self.job_queue.dequeue()
                print("Printer {} got job {}".format(self.name, self.current_job.name))
        # print!
        print("Printer {} is printing...".format(self.name))
        self.current_job.tick()
        # see if job is finished
        if self.current_job.is_done():
            print("Printer {} finished job {}".format(self.name, self.current_job.name))
            self.current_job = None

    def is_idle(self):
        return self.current_job is None

def main():
    # create job queue and two printers
    jobs = JobQueue()
    p1 = Printer(1, jobs)
    p2 = Printer(2, jobs)

    # add jobs
    jobs.enqueue(PrintJob(1, 5))
    jobs.enqueue(PrintJob(2, 7))
    jobs.enqueue(PrintJob(3, 13))

    # cycle until queue is empty
    tick = 0
    while not (jobs.is_empty() and p1.is_idle() and p2.is_idle()):
        tick += 1
        print("\n=== Tick {} ===".format(tick))
        p1.tick()
        p2.tick()

    print("\nAll done! Time for a pint...")

if __name__ == "__main__":
    main()

rawDescription: How to create a simulated printer in Python?

description: Create a simulated printer in Python


code: x2 = x.reshape(2, -1)

rawDescription: Splitted Array being filled in for loop by function calculating values from a splitted array


rawDescription: Multiplying every element of one array by every element of another array


code: from docx import Document

rawDescription: Parse .docx in python 3

description: Parse .docx in python 3