code: x = example() # calls example and assigns the return value to x

rawDescription: How to port a Python program to Ruby

description: Port a Python program to Ruby


code: ' '.join(letter for letter, count in hand.iteritems() for i in range(count))

rawDescription: going through a dictionary and printing its values in sequence

description: Going through a dictionary and printing its values in sequence


code:
from itertools import accumulate, islice, cycle
import operator

l = list(accumulate(islice(cycle([1, -2, 3]), 10), operator.add))
print(l)

rawDescription: Create a list that follows a certain creation pattern


code:
if brush2.get_rect().collidepoint(pygame.mouse.get_pos()):
    (brush, brush2) = (brush2, brush) # swaps brush and brush2
    pygame.display.update()

rawDescription: paint application - python

description: Paint application - python


code:
def all_steps(self):
    user = self.user_created.first_name
    return [(getattr(self, attr), step.replace('<user_created>', user))
            for attr, step in zip(_STEP_NAMES, self.STEPS)]

def next_step(self):
    user = self.user_created.first_name
    step = next((i for i, attr in enumerate(_STEP_NAMES)
                        if getattr(self, attr) is None),
                None) # assumes Python 2.6+
    if step == None:
         return "Done!"
    else:
         return str(step) + ": " + self.STEPS[step].replace('<user_created>', user)

rawDescription: Redundant code in Django models.py. How do I improve it?


code:
class DictAdditionalValueWrapper:
    def __init__(self, baseDict, specialKey, specialValue):
        self.baseDict = baseDict
        self.specialKey = specialKey
        self.specialValue = specialValue

    def __getitem__(self, key):
        if key == self.specialKey:
            return self.specialValue

        return self.baseDict[key]

    # ...

rawDescription: How to pass in a dictionary with additional elements in python?

description: Pass in a dictionary with additional elements in python


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

# lowercase variables are 1D arrays
x = np.linspace(0, 2 * np.pi, 10)
y = np.sin(x)
u = np.cos(x)
v = np.sin(x)

# capitalized variables are 2D arrays
xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)
X, Y = np.meshgrid(xi, yi)
U = interpolate.griddata((x, y), u, (X, Y), method='cubic')
V = interpolate.griddata((x, y), v, (X, Y), method='cubic')

plt.figure()
plt.quiver(x, y, u, v, scale_units='xy', angles='xy', scale=1.5)
plt.streamplot(X, Y, U, V, color=U**2+V**2, linewidth=2, cmap=plt.cm.autumn)
plt.show()

rawDescription: Matplotlib - Using 1-D arrays in streamplot()


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
)

rawDescription: Django - how to tell if user was redirected to the page by @login_required?


code: df

rawDescription: Pandas Time-Series: Find previous value for each ID based on year and semester


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

bwimshow = functools.partial(plt.imshow, vmin = 0, vmax = 255,
                             cmap = plt.get_cmap('gray'))

dots = np.random.randn(10,10)*255
bwimshow(dots)
cbar = plt.colorbar()

plt.show()

rawDescription: imshow(img, cmap=cm.gray) shows a white for 128 value

description: Imshow(img, cmap=cm.gray) shows a white for 128 value


rawDescription: finding non-numeric rows in dataframe in pandas?

description: Finding non-numeric rows in dataframe in pandas


code:
import numpy as np
import pandas as pd

df = pd.read_table('data', sep='\s+')
df = df.set_index(['id', 'match', 'bookmaker']).unstack(['bookmaker'])

rawDescription: Transform rows in columns in Pandas

description: Transform rows in columns in Pandas


code:
a = [('hello', 1, 2), ['foo', 5, 3], {0: 'bar', 1: 'baz'}]
sorted(a)
sorted(a, key=lambda x: x[1])
b = ['hello', 1, 3]
sorted(b)

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code:
def get_accessor_name(self):
    # This method encapsulates the logic that decides what name to give an
    # accessor descriptor that retrieves related many-to-one or
    # many-to-many objects. It uses the lower-cased object_name + "_set",
    # but this can be overridden with the "related_name" option.
    if self.field.rel.multiple:
        # If this is a symmetrical m2m relation on self, there is no reverse accessor.
        if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model:
            return None
        return self.field.rel.related_name or (self.opts.object_name.lower() + '_set')
    else:
        return self.field.rel.related_name or (self.opts.object_name.lower())

rawDescription: How does django one-to-one relationships map the name to the child object?


code: lambda x: int(x) if x and x.isdigit() else None

rawDescription: Lambda instead of "if" statement

description: Lambda instead of "if" statement


rawDescription: Using Python to manipulate data from a CSV only applying it to the first result


code:
TestCode = PyCompiler(file, module, [lib])
TestCode.compile()
test = TestCode.include()

rawDescription: Compiling C++ code using Python interpreter running under windows shell


rawDescription: python find a pattern in string and enclose it in braces

description: Python find a pattern in string and enclose it in braces


code:
def factorial_cap(num):
    c=1
    while(c<num):
        num=num/float(c)
        c=c+1
    return c

rawDescription: Starting loops with python

description: Starting loops with python


rawDescription: Register username and password

description: Register username and password


code: df['Entry time'] = pd.to_datetime(df['Entry Time'])

rawDescription: Calculate difference between two datetimes if both present in pandas DataFrame


rawDescription: Getting rows from a data frame which satisfy a condition in pandas


code:
Array        # _type_, _length_
Structure    # _fields_, _anonymous_, _pack_, _swappedbytes_
Union        # _fields_, _anonymous_, _pack_, _swappedbytes_

rawDescription: Determining whether an object is a ctypes array


code:
def isprime(n):
    if n % 1 != 0:
        return True
    else:
        for j in range(2, math.ceil(math.sqrt(n))):
            if n % j != 0:
                return False
        return True

rawDescription: Python and the modulus operator with very large numbers


code: A.reshape((-1, 3, 3)).swapaxes(-1, 1).reshape(A.shape)

rawDescription: Transposing arrays in an array

description: Transposing arrays in an array


code:
from itertools import combinations
[j for i in range(len(foobar)+1) for j in combinations(foobar,i)]

rawDescription: Generating all possible subsets of a given QuerySet in Django


code: [(m.span()[0], m.span()[1] + 1) for m in re.finditer('(?=aa)', 'aaadaa')]

rawDescription: Python regular expressions lookahead

description: Python regular expressions lookahead


rawDescription: How to parse data by subtituting part of a url

description: Parse data by subtituting part of a url


rawDescription: Python eliminate Tuples after zipping list of list of lists


rawDescription: how to split the text using python?

description: Split the text using python


code: [value for lst in dictA.itervalues() for value in lst]

rawDescription: List Comprehension of Lists Nested in Dictionaries


code:
import math
class Vector():
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        self.z += other.z
        return self

    def __sub__(self, other):
        self.x -= other.x
        self.y -= other.y
        self.z -= other.z
        return self

    def dot(self, other):
        return self.x*other.x + self.y*other.y + self.z*other.z

    def cross(self, other):
        tempX = self.y*other.z - self.z*other.y
        tempY = self.z*other.x - solf.x*other.z
        tempZ = self.x*other.y - self.y*other.x
        return Vector(tempX, tempY, tempZ)

    def dist(self, other):
        return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2 + (self.z-other.z)**2)

    def unitVector(self):
        mag = self.dist(Vector())
        if mag != 0.0:
            return Vector(self.x * 1.0/mag, self.y * 1.0/mag, self.z * 1.0/mag)
        else:
            return Vector()

    def __repr__(self):
        return str([self.x, self.y, self.z])

rawDescription: Calculate a point along a line segment one unit from a end of the seg


code:
def isPower(a,b):
    if a == 0 or b == 0:
        return False
    def realIsPower(a, b):
        if a == 1:
            return True
        elif a%b != 0:
            return False
        elif realIsPower((a/b), b):
            return True
        else:
            return False
    return realIsPower(a, b)

rawDescription: Why does my recursive function return None?


code:
opening = cv2.morphologyEx(current, cv2.MORPH_OPEN, kernel7)
cl1[np.where(opening == 0)] = 0

rawDescription: Image processing issues with blood vessels


code:
def numerology(z):
    zstr1=str(z)
    accum1=0
    for x in zstr1:
        accum1 += int(x)
    str2=str(accum1)
    accum2=0
    for x in str2:
        accum2 += int(x)
    return accum2

rawDescription: converting iteration into a function

description: Converting iteration into a function


code:
try:
    nltk.data.find('punkt.zip')
except LookupError:
    nltk.download('punkt')

rawDescription: How do I test whether an nltk resource is already installed on the machine running my code?

description: Test whether an nltk resource is already installed on the machine running my code


rawDescription: Python program needs full path in Notepad++


code:
def case_insensitive_unique_list(data):
    seen, result = set(), []
    for item in data:
        if item.lower() not in seen:
            seen.add(item.lower())
            result.append(item)
    return result

rawDescription: Python returning unique words from a list (case insensitive)


code: df.loc[(df.Name.isin(['Avi','Dav','Ron'])) & (df.Age < 33), 'Babys'] += 1

rawDescription: change column values in CSV using python

description: Change column values in CSV using python


code: self.image = pygame.transform.rotate(self.imagePuff, self.angle)

rawDescription: How to animate scale and rotate in pygame using rotozoom

description: Animate scale and rotate in pygame using rotozoom


code:
list_value = [["f", "o", "c"], ['null', "o", 'null'], ['null', "o", 'null']]

[filter(lambda x: x!='null' and x!=None, inner_list) for inner_list in list_value]

[['f', 'o', 'c'], ['o'], ['o']]

rawDescription: Python remove null items from list

description: Python remove null items from list


code:
from  matplotlib.ticker import FuncFormatter

fig, ax = plt.subplots(1,1)
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
t.plot(ax=ax)

rawDescription: Matplotlib Line Graph with Pandas Pivot Table


code:
import itertools
a = [item for item in itertools.islice(e, 0, None, 8)]
b = [item for item in itertools.islice(e, 1, None, 8)]
c = [item for item in itertools.islice(e, 2, None, 8)]

rawDescription: Use Python zip to save data in separate columns from a binary file


code: pdfanchor = '\\phantomsection%\n  '

rawDescription: Creating minimal LaTeX syntax from reStructuredText with docutils


code:
nums = map(lambda x : random.randint(0,7), range(50))
nums

rawDescription: How to generate a list of 50 random colours in python?

description: Generate a list of 50 random colours in python


code:
foo.func_globals
foo.func_globals['bar'] = 'baz'
del foo.func_globals['__doc__']
foo.func_globals

rawDescription: Is func_globals mutable?

description: Is func_globals mutable


code:
def group(elements, comp_func):
    groups = {}
    for x in elements:
        prototype = next((y for y in groups if comp_func(x, y)), x)
        groups.setdefault(prototype, []).append(x)
    return groups

rawDescription: Gather elements from list into lists of lists of equal elements?


code:
import sqlite3
import datetime as DT

def adapt_timeobj(timeobj):
    return ((3600*timeobj.hour + 60*timeobj.minute + timeobj.second)*10**6
            + timeobj.microsecond)

def convert_timeobj(val):
    val = int(val)
    hour, val = divmod(val, 3600*10**6)
    minute, val = divmod(val, 60*10**6)
    second, val = divmod(val, 10**6)
    microsecond = int(val)
    return DT.time(hour, minute, second, microsecond)

# Converts DT.time to TEXT when inserting
sqlite3.register_adapter(DT.time, adapt_timeobj)

# Converts TEXT to DT.time when selecting
sqlite3.register_converter("timeobj", convert_timeobj)

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()

# declare timecol to be of type timeobj
cur.execute("create table test (timecol timeobj)")

cur.executemany("insert into test (timecol) values (?)",
                [(DT.time(1,2,3,4), ), (DT.time(5,6,7,8),) ])

rawDescription: Best way to store python datetime.time in a sqlite3 column?

description: Store python datetime.time in a sqlite3 column


code:
import time
import urllib.request
import concurrent.futures

URL = 'http://localhost:8080/'
TIMEOUT = 60
DELAY = 0.05
MAX_WORKERS = 20
REQ_RANGE = range(1, 101)

def load_url():
    with urllib.request.urlopen(URL, timeout=TIMEOUT) as conn:
        return conn.read()

with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
    futures = {}
    for i in REQ_RANGE:
        print("Sending req {}".format(i))
        futures[executor.submit(load_url)] = i
        time.sleep(DELAY)
    results = []
    for future in concurrent.futures.as_completed(futures):
        try:
            data = future.result().decode()
        except Exception as exc:
            print(exc)
        else:
            results.append((futures[future], data))
    curr_max = 0
    for i, data in sorted(results, key=lambda r: r[0]):
        new_max = int(data.split()[-1])
        assert new_max >= curr_max, "The data was not updated correctly"
        print("Req {}: {}".format(i, data))
        curr_max = new_max

rawDescription: CherryPy: how to stop and buffer incoming request while data is updated


code:
key = createMagicalKey()

ciphertext = key.encrypt(data)

data = key.decrypt(ciphertext)

rawDescription: Pythonic solution to cryptographic agility that avoids violating Liskov's substitution principle


code: ['note', 'to', 'from', 'heading', 'body']

rawDescription: List of distinct XML element names using BeautifulSoup


code:
x = Library()
vars(x)

rawDescription: Python: Printing nested classes

description: Python: Printing nested classes


code: script, filename = argv

rawDescription: How to implement command line switches to my script?

description: Implement command line switches to my script


code:
s = "someinteger5withanother1someinteger4withanother2someinteger3withanother3"
values = re.findall(r'someinteger(.+?)withanother(.+?)', s)
values
values.sort()
values

rawDescription: how to add and sort multidimentional array in python?

description: Add and sort multidimentional array in python


code: simplifying_generator = (element[0] for element in my_array_of_arrays)

rawDescription: I have single-element arrays. How do I change them into the elements themselves?


code:
result = a.repeat([blockSize]*(cols//blockSize) + [cols % blockSize], axis=1)
result = result.repeat([blockSize]*(rows//blockSize) + [rows % blockSize], axis=0)
result

rawDescription: Fill larger matrix from smaller matrix

description: Fill larger matrix from smaller matrix


code: LOG.info('Spam and eggs are tasty!')

rawDescription: Naming Python loggers

description: Naming Python loggers


code:
somespider.py
# -*- coding: utf-8 -*-
import scrapy
import re
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from scrapy.spider import BaseSpider
from demo.items import DemoItem
from selenium import webdriver

def removeUnicodes(strData):
        if(strData):
            strData = strData.encode('utf-8').strip()
            strData = re.sub(r'[\n\r\t]',r' ',strData.strip())
        return strData

class demoSpider(scrapy.Spider):
    name = "domainurls"
    allowed_domains = ["domain.com"]
    start_urls = ['http://www.domain.com/used/cars-in-trichy/']

    def __init__(self):
        self.driver = webdriver.Remote("http://127.0.0.1:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNITWITHJS)

    def parse(self, response):
        self.driver.get(response.url)
        self.driver.implicitly_wait(5)
        hxs = Selector(response)
        item = DemoItem()
        finalurls = []
        while True:
            next = self.driver.find_element_by_xpath('//div[@class="showMoreCars hide"]/a')

            try:
                next.click()
                # get the data and write it to scrapy items
                item['pageurl'] = response.url
                item['title'] =  removeUnicodes(hxs.xpath('.//h1[@class="page-heading"]/text()').extract()[0])
                urls = self.driver.find_elements_by_xpath('.//a[@id="linkToDetails"]')

                for url in urls:
                    url = url.get_attribute("href")
                    finalurls.append(removeUnicodes(url))

                item['urls'] = finalurls

            except:
                break

        self.driver.close()
        return item

rawDescription: selenium ajax dynamic pagination base spider

description: Selenium ajax dynamic pagination base spider


code:
def bbox2_3D(img):

    r = np.any(img, axis=(1, 2))
    c = np.any(img, axis=(0, 2))
    z = np.any(img, axis=(0, 1))

    rmin, rmax = np.where(r)[0][[0, -1]]
    cmin, cmax = np.where(c)[0][[0, -1]]
    zmin, zmax = np.where(z)[0][[0, -1]]

    return rmin, rmax, cmin, cmax, zmin, zmax

rawDescription: bounding box of numpy array

description: Bounding box of numpy array


rawDescription: communication with 0mq

description: Communication with 0mq


code:
import inspect
def common_bases(seq):
    iseq = iter(seq)
    bases = set(inspect.getmro(type(next(iseq))))
    for item in iseq:
        bases = bases.intersection(inspect.getmro(type(item)))
        if not bases:
           break
    return bases

rawDescription: Python check if all elements of a list are the same type


code:
import unittest
import other_module

__private_stuff = 1 # if it would have single underscore, it would bot be a problem.

class ComplexTestCase(unittest.TestCase):
    def test_internal_symbol(self):
        private_stuff = getattr(other_module, '__private_stuff')
        self.assertEqual(private_stuff, 1)

unittest.main(__name__)

rawDescription: How to test python module privates?

description: Test python module privates


rawDescription: max value in Python

description: Max value in Python


code:
x = set([1,2,3])
my_function(x.union)

rawDescription: How can I pass union/intersection methods as a parameter in Python?

description: Pass union/intersection methods as a parameter in Python


code:
class Stack:

    def __init__(self, parent = None, id=None):
        self.stackscount = 0
        self.capacity = 3
        self.items = []
        self.parent = parent
        self.id = id
        self.child = None

    def create(self):
        id = self.stackscount + 1
        id = str(id) + "_stack"
        return Stack(self, id)

    def push(self, item):
        if self.size() <= self.capacity:
            self.items.append(item)
        else:
            if self.child is None:
                self.child = self.create()
            self.child.push(item)

    def pop(self):
        if self.child is not None:
            item = self.child.pop()
            if len(self.child.items) == 0:
                self.child = None
        else:
            item = self.items.pop()
        return item

    def popAt(self):
        pass

    def peek(self):
        if self.child is not None:
            item = self.child.peek()
        else:
            item = self.items[len(self.items)-1]
        return item

    def size(self):
        l = len(self.items)
        if self.child is not None:
            l += self.child.size()
        return l

s = Stack()
s.push(10)

rawDescription: How to create new class instances dynamically at runtime in python?

description: Create new class instances dynamically at runtime in python


code:
class Circle(Shape):
    diameter = AttrMap('height')
    def __init__(self, height, foo_args, shape='circle'):
        Shape.__init__(self, shape, height) # assigns the attributes there
        # other assignments

rawDescription: child class attribute different name

description: Child class attribute different name


rawDescription: Need to aggregate count(rowid, colid) on dataframe in pandas


rawDescription: Pythonic way to insert every 2 elements in a string


code:
if not reloading and event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed() == (1, 0, 0) and ammo > 0:
    ammo -= 1
    bullet = Bullet()
    all_sprites_list.add(bullet)
    bullet_list.add(bullet)

rawDescription: How do I make a reload timer for my player's weapon in pygame?

description: Make a reload timer for my player's weapon in pygame


rawDescription: How to perform operations on rows of Dataframes which contain elements linked to a value in another Dataframe in Python?

description: Perform operations on rows of Dataframes which contain elements linked to a value in another Dataframe in Python


code: [item for item in wordlist if item.startswith(hand)]

rawDescription: Python lists and list item matches - can my code/reasoning be improved?


code:
import colorama   # OR: from colorama import init
colorama.init()   # AND THEN: init()

rawDescription: Python hide already printed text

description: Python hide already printed text


code:
from shutil import move
move(sourceplayers, destinationplayers)

rawDescription: python file overwriting with os module

description: Python file overwriting with os module


code: listC = [b for b in listB if any(b in a for a in listA)]

rawDescription: match element of a list based on another list in python where elements of one list is the substring of elements of another list

description: Match element of a list based on another list in python where elements of one list is the substring of elements of another list


code:
def foo(l, func):
    for in_str in l[0]:
       print(func(in_str))

l = ["Hello world!", "helloworld"]

print(foo(l,str.isalpha))

rawDescription: Passing method to a function in Python

description: Passing method to a function in Python


code: generator = itertools.repeat(seed)

rawDescription: Algorithm to generate pseudorandom numbers serie, reproducible knowing initial seed


code: plot(x1, minList, label='blau')

rawDescription: show date on axis of a plot in matplotlib

description: Show date on axis of a plot in matplotlib


code:
hello = [['<User: mr--adhikari>'], ['<User: mr--adhikari>'], ['<User: mr--adhikari>', '<User: awesome>']]
[ [y.lstrip('<User: ').rstrip('>') for y in x] for x in hello ]

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

description: Convert this list in a given format


code:
shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_shorter_edge = 400
height_smaller_than_width = tf.less_equal(height, width)

new_shorter_edge = tf.constant(400)
new_height, new_width = tf.cond(
    height_smaller_than_width,
    lambda: new_shorter_edge, (width / height) * new_shorter_edge,
    lambda: new_shorter_edge, (height / width) * new_shorter_edge)

rawDescription: TensorFlow Resize image tensor to dynamic shape


code:
sql = '''SELECT * FROM app_book
         WHERE app_book.pub_date IN
           (SELECT MAX(app_book.pub_date)
            FROM app_book
            GROUP BY app_book.author_id)
         ORDER BY app_book.pub_date DESC'''
books = list(Book.objects.raw(sql)[:5])

rawDescription: How to retrieve the first X objects with unique attribute value

description: Retrieve the first X objects with unique attribute value


rawDescription: Different results achieved using Python's os.walk function and ls command


code:
if __name__ == "__main__":
    stdscr = curses.initscr()
    stdscr.clear()
    choice = my_raw_input(stdscr, 2, 3, "cool or hot?").lower()
    if choice == "cool":
        stdscr.addstr(5,3,"Super cool!")
    elif choice == "hot":
        stdscr.addstr(5, 3," HOT!")
    else:
        stdscr.addstr(5, 3," Invalid input")
    stdscr.refresh()
    stdscr.getch()
    curses.endwin()

rawDescription: How to input a word in ncurses screen?

description: Input a word in ncurses screen


code:
scipy.io.wavfile.write('test.wav', rate, data_bis.astype(data.dtype))
scipy.io.wavfile.read('test.wav')

rawDescription: Issues with scipy.io wave file processing after applying fourier transforms


code: reduce(lambda l, i: l[i], indices, somelist)

rawDescription: Python: Accessing elements of multi-dimensional list, given a list of indexes


code:
last, lastG = 0, 0
for g in num:
  Lval,x = quad(L, lastG, g)
  last, lastG = last + Lval, g
  Lv=np.append(Lv,[last])

rawDescription: How to make my python integration faster?

description: Make my python integration faster


code:
def f(*args, bar=fubar):
    for x in args:
        do_something(bar, x)

f(arg1, arg2, arg3, bar=fubar)
# f(fubar, arg1, arg2, arg3) is not allowed

rawDescription: Python - Sending multiple values for one argument to a function


code:
L1 = [3, 4, 6, 2]
f = operator.itemgetter(0)
f(L1)
# 3

f = operator.itemgetter(2)
f(L1)
# 6

rawDescription: Working of Enumerate in Python

description: Working of Enumerate in Python


code:
#file: argp.py

import argparse

parser = argparse.ArgumentParser(prog='PROG')
parser_subparsers = parser.add_subparsers()
sub = parser_subparsers.add_parser('sub')
sub_subparsers = sub.add_subparsers()
sub_sub = sub_subparsers.add_parser('sub_sub')
sub_sub_subparsers = sub_sub.add_subparsers()
sub_sub_sub = sub_sub_subparsers.add_parser('sub_sub_sub')

rawDescription: Python: argparse subcommand subcommand?

description: Python: argparse subcommand subcommand


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

rawDescription: beautiful soup extracting parent/sibling tr table class

description: Beautiful soup extracting parent/sibling tr table class


code: map(list,zip(*lis))

rawDescription: how to make a list of first characters in from list of strings

description: Make a list of first characters in from list of strings


rawDescription: What does [:-1] mean/do in python?

description: What does [:-1] mean/do in python


code:
ls = [1, 2, 3, 3]
[x for x in ls if ls.count(x) == 1]

rawDescription: Remove duplicates from list, including original matching item


code: df['itp'].interpolate('spline', order=3, s=0, inplace=True)

rawDescription: How to use `Series.interpolate` in pandas with the old values modified

description: Use `Series.interpolate` in pandas with the old values modified


code:
import numpy as np
from matplotlib import gridspec, pyplot as plt

x = np.linspace(0,100)
y = np.sin(x)

fig = plt.figure()

gs = gridspec.GridSpec( 100,100 )
ax1 = fig.add_subplot(gs[ :50, : ])
ax2 = fig.add_subplot(gs[ 55:, : ])

ax1.plot( x, y, label=r'sine' )

h,l=ax1.get_legend_handles_labels() # get labels and handles from ax1

ax2.legend(h,l)                     # use them to make legend on ax2

plt.show()

rawDescription: Python's matplotlib legend in separate axis with gridspec


code:
import os
from win32com.shell import shell, shellcon
print(shell.__file__)
path = os.path.expanduser(r'~\Desktop\desktop.ini')
pidl = shell.SHParseDisplayName(path, 0, None)[0]
flags = (shellcon.SHGFI_PIDL |
         shellcon.SHGFI_SYSICONINDEX |
         shellcon.SHGFI_ICON |
         shellcon.SHGFI_DISPLAYNAME)
shell.SHGetFileInfo(pidl, 0, flags)

rawDescription: How to use SHGetFileInfo with SHGFI_PIDL in python

description: Use SHGetFileInfo with SHGFI_PIDL in python


code: {f: getattr(filters, f) for f in dir(filters) if not f.startswith('__')}

rawDescription: Adding a modules functions automatically to a dict


code:
# make one figure with 2 axes
fig, ax_lst = plt.subplots(1, 2)

for i, ax in zip(xrange(2), ax_lst):
    # get the data
    t = a[i+1:(i+1)*60, 2]
    z = a[i+1:(i+1)*60, 3]
    est_z = a[i+1:(i+1)*60, 6]
    # do the plot
    my_plotter(ax, t, z, est_Z)
# save the figure with both plots
fig.savefig('both.png')

rawDescription: matplotlib for loop to show, save and redraw all plots

description: Matplotlib for loop to show, save and redraw all plots


code:
def request( url, type, headers, simulate = False, data = {}):
    if simulate:
        recovery_command = {"url":url, "type" : type, "data" : data}
        recovery.add_command(json.dumps(recovery_command))
        ...

rawDescription: Loading function parameters from a text file


code:
def digit_or_slash(s):
    return all(c in "0123456789/" for c in s)

rawDescription: How to I check that a string contains only digits and / in python?


code:
# should be sys.argv[1]
sys.argv[1]

rawDescription: Pass argument from command button on Access form to python script


code:
d = {}
d.setdefault('foo', {})['bar'] = 'baz'
d
d.setdefault('foo', {})['ni'] = 'ichi'
d

rawDescription: How to associate elements in a set with multiple dict entries

description: Associate elements in a set with multiple dict entries


code:
# file1.py
variable = 6

rawDescription: Connection between objects in two Python files


code:
df.reset_index(inplace=True)

print (df.index)
RangeIndex(start=0, stop=20, step=1)

rawDescription: Convert pandas df multi index to columns


code:
from timeit import timeit
from operator import itemgetter

T = [('a',3), ('b', 4), ('c', 5), ('d', 1), ('e',2)]

def one():
    [v for _, v in T]

def two():
    [v[-1] for v in T]

def three():
    list(map(itemgetter(1), T))

def four():
    list(map(lambda x:x[1], T))

def five():
    list(zip(*T))[1]

for func in (one, two, three, four, five):
    print(func.__name__ + ':', timeit(func))

rawDescription: getting only integers from a list of tuples python 3

description: Getting only integers from a list of tuples python 3


code:
import numpy as np
import scipy.stats as stats

mu = 0.3
sigma = 5

num_tests = 10**5
num_rejects = 0
alpha = 0.05
for i in xrange(num_tests):
    data = np.random.normal(mu, sigma, 10000)
    # normed_data = (data - mu) / sigma    # this is okay
    # 4915/100000 = 0.05 rejects at rejection level 0.05 (as expected)
    normed_data = (data - data.mean()) / data.std()    # this is NOT okay
    # 20/100000 = 0.00 rejects at rejection level 0.05 (not expected)
    D, pval = stats.kstest(normed_data, 'norm')
    if pval < alpha:
        num_rejects += 1
ratio = float(num_rejects) / num_tests
print('{}/{} = {:.2f} rejects at rejection level {}'.format(
    num_rejects, num_tests, ratio, alpha))

rawDescription: Implementing a Kolmogorov Smirnov test in python scipy


code: point()

rawDescription: Python: variable is undefined when calling function containing the variable


code:
s = pd.Series(np.random.rand(1000)).cumsum()
diffs = np.subtract.outer(s, s)

rawDescription: Algorithm to find indices of two numbers in Series with difference within a specified range


code:
def option(function):
    def wrapper(*args, **kwargs):
        if len(args) > 0 and args[0] is not None:
          return function(*args, **kwargs)
    return wrapper

rawDescription: Python idiom for applying a function only when value is not None


code:
import pandas as pd
import io

text = '''\
STK_ID RPT_Date sales cash
000568 20120930 80.093 57.488
000596 20120930 32.585 26.177
000799 20120930 14.784 8.157
'''

df = pd.read_csv(io.BytesIO(text), delimiter = ' ',
                 converters = {0:str})
df.set_index(['STK_ID','RPT_Date'], inplace = True)

rawDescription: How to change Pandas dataframe index value?

description: Change Pandas dataframe index value


rawDescription: addition of int and str

description: Addition of int and str


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

img = mpimg.imread('image.png')
arr = 0.2126* img[...,0] + 0.7152* img[...,1] + 0.0722 * img[...,2]
plt.imshow(arr, cmap=plt.get_cmap('gray'))
plt.show()

rawDescription: Making an image black and white in python without pillow


code:
DEFAULT_BURST_WINDOW = datetime.timedelta(seconds=5)
DEFAULT_WAIT_WINDOW = datetime.timedelta(seconds=15)

class BurstThrottle(object):
    max_hits = None
    hits = None
    burst_window = None
    total_window = None
    timestamp = None

    def __init__(self, max_hits, burst_window, wait_window):
        self.max_hits = max_hits
        self.hits = 0
        self.burst_window = burst_window
        self.total_window = burst_window + wait_window
        self.timestamp = datetime.datetime.min

    def throttle(self):
        now = datetime.datetime.utcnow()
        if now < self.timestamp + self.total_window:
            if (now < self.timestamp + self.burst_window) and (self.hits < self.max_hits):
                self.hits += 1
                return datetime.timedelta(0)
            else:
                return self.timestamp + self.total_window - now
        else:
            self.timestamp = now
            self.hits = 1
            return datetime.timedelta(0)

rawDescription: Limiting/throttling the rate of HTTP requests in GRequests


rawDescription: How do I create this object with the models I have set up?

description: Create this object with the models I have set up


code:
def stepashka_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = "http://online.stepashka.com/filmy/#/page/" + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for resoult in soup.findAll("div", {"class": "video-title"}):
            a_tag = resoult.a
            print(a_tag["href"])
        page += 1

stepashka_spider(1)

rawDescription: Python Web Crawler not printing any result


code:
import sys
sys.stdout = open('logfile', 'w')

rawDescription: Python, logging print statements while having them print to stdout


rawDescription: What python code generates all possible groupings (trees) for binary operators


code:
from registration.backends.simple.views import RegistrationView
from .forms import UserRegistrationForm

class MyRegistrationView(RegistrationView):
    form_class= UserRegistrationForm

rawDescription: Removing second password input from django-registration form


code: series.index = series.index.map(lambda v: v.replace('@', ''))

rawDescription: Replacing Index values using regex matching


rawDescription: Understanding this memoize decorator

description: Understanding this memoize decorator


code:
def main():
    mydict = X()
    # You now have access to the dictionary you created in X

rawDescription: passing dictionaries to other functions

description: Passing dictionaries to other functions


code:
length=int(input("Enter the length of the sequence: "))
numList=[]
count=0
for i in range(length):
    num=int(input("Enter number "+str(i+1)+ ": "))
    numList.append(num)

for x in range(len(numList)-1):
    num1=numList[x]
    num2=numList[x+1]
    if((num1%2==1) and (num2%2==1)):
        count=count+1
    else:
        continue

print("The number of pairs of adjacent odd numbers is "+str(count))

rawDescription: Calculating number of adjacent odd numbers


rawDescription: How to filter pandas dataframe columns by partial label

description: Filter pandas dataframe columns by partial label


code: all(dict_obj.get(key) is not None for key in properties_to_check_for)

rawDescription: Check to see if a collection of properties exist inside a dict object in Python


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

# Generate random data.
x1 = np.random.randn(50)
y1 = np.linspace(0, 1, 50)
x2 = np.random.randn(20)+15.
y2 = np.linspace(10, 20, 20)

# Plot both curves.
fig, ax1 = plt.subplots()

ax1.set(xlabel='x_1', ylabel='y_1')
ax1.plot(x1, y1, c='r')

tempax = ax1.twinx()
ax2 = tempax.twiny()
ax2.plot(x2, y2, c='b')
ax2.set(xlabel='x_2', ylim=[min(y2), max(y2)])
tempax.set_ylabel('y_2', rotation=-90)

plt.show()

rawDescription: One secondary label missing when plotting x and y secondary axis


code:
c.execute('''CREATE TABLE x2
             (freq INT, w1 INT, w2 INT,
              FOREIGN KEY(w1) REFERENCES lex(wID),
              FOREIGN KEY(w2) REFERENCES lex(wID),
              PRIMARY KEY(w1, w2) )''')

rawDescription: Trouble with a join statement in SQLite

description: Trouble with a join statement in SQLite


code:
import sys

print(...)
sys.stdout.flush()

rawDescription: Need Python 3.4 version of print() from __future__


code:
# Attributes of interest
attrs = ['Id', 'Phone', 'FirstName', 'LastName', 'Email']
records = od['records']

data = {}

for rec in records:
    for k in attrs:
        # setdefault initializes the array for key if necessary
        data.setdefault(k, []).append(rec[k])

dframe = pandas.DataFrame(data)

print(dframe)

rawDescription: Python: Parsing OrderedDict of OrderedDicts into Pandas Dataframe


code:
import pandas as pd
binary = lambda s: int(s, 2)
df = pd.read_csv('rawdata.txt', converters={'voltage(V) ': binary, 'current(A)': binary})
print(df)

rawDescription: I am trying to get binary data from text and converting to numpy arrays


code:
A = np.arange(5) + 0.5
A += np.bincount(B) * 1  # replace the 1 with the number you want to add
A

rawDescription: indexing/slicing in numpy array to modify it

description: Indexing/slicing in numpy array to modify it


code:
query = """
     INSERT INTO credit
         (bank, number, card, int1, value, type, int2)
     VALUES
          (?, ?, ?, ?, ?, ?, ?)
        """
data =  ['Citi', '5567', 'visa', 6000, 9.99, '23', 9000]

cursor.execute(query, data)

rawDescription: Passing SQLite variables in Python

description: Passing SQLite variables in Python


code:
list(new(3)) == list(variable_strings_complete(3))
list(new(20)) == list(variable_strings_complete(20))
list(new(10, alphabet=range(4))) == list(variable_strings_complete(10, range(4)))

rawDescription: Iterator for all lexicographically ordered variable strings up to length n


code: (x, y, z) = my_array.T

rawDescription: how to deal in a pythonic way with list of arrays or single array

description: Deal in a pythonic way with list of arrays or single array


code:
salary[mini_idx]
name[mini_idx]
salary[maxi_idx]
name[maxi_idx]

rawDescription: Printing Employee and Salary from parallel array in Python


code:
fruitcount = {Fruit("banana", "red"):5}
fruitcount[f]

rawDescription: Python: Tuples/dictionaries as keys, select, sort


rawDescription: Variable scope problems with dictionaries


code:
def pytest_runtest_logreport(report):
    if report.failed:
        report.longrepr.sections.append(("Header", "Message", "-"))
        report.sections.append(("Captured stdout", "This is added to stdout"))
        report.sections.append(("Captured stderr", "This is added to stderr"))
        report.sections.append(("Custom Section", "This can only be seen in the console - the xml won't have it."))

rawDescription: Customizing pytest junitxml failure reports


code:
somefield = forms.TextField(
    required=True,
    widget=forms.TextInput(attrs={'required': 'true'}),
)

rawDescription: Don't allow submit form when fields in blank Django Python


code:
dest_dir = '/home/xxxx/public_html/xxxx.com/test/uploads/'
os.rename(dest_dir + fn, dest_dir + 'equations.txt')

rawDescription: Renaming file on server with python

description: Renaming file on server with python


code:
wordCount = Counter(w.strip('.,:?')
    for line in inputFile for w in line.split())

rawDescription: Removing a char from String in Python

description: Removing a char from String in Python


code:
from setuptools import setup

setup(
    name='confectionary',
    version='1.0.0',
    py_modules=['confectionary'],
    entry_points='''
        [console_scripts]
        crunchy_frog=confectionary.confections:crunchy_frog
        anthrax_ripple=confectionary.confections:anthrax_ripple
        spring_surprise=confectionary.confections:spring_surprise
    ''',
)

rawDescription: Can I get pip to delete scripts that I installed but no longer want?

description: Get pip to delete scripts that I installed but no longer want


code:
parser = argparse.ArgumentParser()
args, extras = parser.parse_known_args()

rawDescription: Unpacking arguments from argparse

description: Unpacking arguments from argparse


code: abs(start_time - end_time) > timedelta(hours=6)

rawDescription: Converting date into hours

description: Converting date into hours


code:
index_0 = [i for i, v in enumerate(a) if v == 0]
index_1 = [i for i, v in enumerate(a) if v == 1]

rawDescription: how to find all the index of an element in a list Python

description: Find all the index of an element in a list Python


code: '{:.2e}'.format(random.uniform(1.0, 3.0) * 10 ** random.randint(5, 10))

rawDescription: Generate random scientific notation float in python


code:
my_str = b'[["innovation",3],["marketing",3],["credentials",2],["trends",2]]'

from ast import literal_eval
literal_eval(my_str)

rawDescription: Python convert string of characters into proper list structure


code:
with open('myfile.txt', 'r') as f:
    s = f.readlines()

rawDescription: How to get two line above a selected string?

description: Get two line above a selected string


code:
DATA = {
0 : ("3", "3", "1"),
1 : ("2", "1", "2"),
2 : ("1", "2", "3")
}

import wx
import wx.lib.mixins.listctrl as listmix

class MyList(wx.ListCtrl, listmix.ColumnSorterMixin):
    def __init__(self, parent, columns):
        wx.ListCtrl.__init__(self, parent, style=wx.LC_REPORT)
        self.itemDataMap = DATA
        listmix.ColumnSorterMixin.__init__(self, columns)

    def GetListCtrl(self):
        return self

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

        self.list = MyList(self, 3)
        self.list.InsertColumn(0, "A")
        self.list.InsertColumn(1, "B")
        self.list.InsertColumn(2, "C")

        items = DATA.items()
        for key, data in items:
            index = self.list.Append(data)
            self.list.SetItemData(index, key)

        self.Show()

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

rawDescription: Sort items in UltimateListCtrl

description: Sort items in UltimateListCtrl


code: "Return value: %c%c%c" % (5,6,7)

rawDescription: Hex data from socket, process and response


rawDescription: Python - return tuple with integer range where multiple lists of integers match


code: [x for x in Person().__dict__.keys() if not x.startswith('_')]

rawDescription: Python/Django debugging: print model's containing data


code:
import json
li = []
def getinput(li):
    li.append(raw_input("Type in a string: "))

rawDescription: Saving an Element in an Array Permanently


code:
import ast

ast.literal_eval(x)

rawDescription: Convert Python string to list

description: Convert Python string to list


code:
[['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT ii'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT iii'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT iv'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT v'],
 ['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT vi'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vii'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT viii'],
 ['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT ix'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT x'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xi'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xii'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP X2', 'COMMENT xiii'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xiv'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xv'],
 ['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xvi']]

rawDescription: What is the best way in python to get a denormalized array from this ordered array?


code:
right_order = (mapping[l] for l in letters)
transposed = zip(*right_order)
for column in transposed:
    print(*(column), sep='')

rawDescription: Python: Print first dictionary value for all keys on first line, second on second etc


code:
year_perf = df.groupby(['Year'])[['Close']].last()
year_perf['annual_perf'] = year_perf.pct_change(periods=1)
year_perf = year_perf.reset_index()
year_perf.head()

rawDescription: Index or group by attributes of a DateTimeIndex in Pandas


rawDescription: Sending progress from thread to gui

description: Sending progress from thread to gui


code:
import pymongo
client = pymongo.MongoClient("mongodb://10.20.30.40/")

rawDescription: Non-Localhost PyMongo Client

description: Non-Localhost PyMongo Client


code:
import types

def f(x, y=2):
    return x,y

g = types.FunctionType(f.func_code, f.func_globals, name=f.func_name,
                       argdefs=f.func_defaults,
                       closure=f.func_closure)
print(f(1))
print(g(1))
assert f is not g

rawDescription: How to create a copy of a python function

description: Create a copy of a python function


rawDescription: How to use index as a key in Python?

description: Use index as a key in Python


code:
import re

with open("tcomment.txt","r") as tf:
    text = ""
    for line in tf:
        text += line
tf.close()
text = text.replace("\n","")
text = text.replace(">",">\n")
text = text.replace("<","\n<")
text = re.sub("
\s*
","

", text)
text = text.replace("
\n", "")
text = text.replace("
\n","\n")
text = re.sub("<[/]{0,1}blockquote>","<chunk>",text)
text = re.sub("]+?>","<chunk>",text)
text = text.replace("","")
text = re.sub("\n+","", text)
text = re.sub("\s{2,}"," ", text)
text = re.sub("<chunk>\s*<chunk>","<chunk>",text)
bits = text.split("<chunk>")
bits[0] = "Latest:"
comments = []
for i in range(len(bits)):
    temp = ""
    j = 0 - (i+1)
    if (len(bits)-i) > i:
        temp = "" + bits[i] + " " + bits[j]
        comments.append(temp)

comments.reverse()
for comment in comments:
    print("
%s
" % (comment))
    print()

rawDescription: Interpreting nested HTML <blockquote>s in Python?


rawDescription: Get files and put into list in another method


code:
from test import *

e = Entity()
register_builtins(e)

c = e.create_component("DerivedComponent") # Has type <class 'module.DerivedComponent'>
c.f() # Prints "DerivedComponent::f()" as expected.

class PythonDerivedComponent(PythonComponent):
    def update(self, dt):
        print("PythonDerivedComponent::update(" + str(dt) + ")")
    def g(self):
        print("PythonDerivedComponent::g()")

e.register_component("PythonDerivedComponent", PythonDerivedComponent)
e.create_component("PythonDerivedComponent")

c = e.component("PythonDerivedComponent")
print(type(c))
c.g() # Now works.

rawDescription: Retrieving a Python type back from c++

description: Retrieving a Python type back from c++


code:
"""
This module is...

Module variables:

* var1: var1 doc
* var2: var2 doc
"""

my_vars = [{'name': 'var1', 'value': 'first'},
           {'name': 'var2', 'value': 'second'}]

for var in my_vars:
    exec("{var[name]} = '{var[value]}'".format(var=var))

...
...

rawDescription: Sphinx - autodata shows str.__doc__

description: Sphinx - autodata shows str.__doc__


rawDescription: Finding the index of an item in a list of lists


code:
link = (
    Link(street=..., ltype=..., use=..., length=...)
        .starting_at(node_a, bearing=..., setback=...)
        .finishing_at(node_b, bearing=..., setback=...)
        .forward_route(lanes, left, right, speed, fspd, capacity)
        .reverse_route(lanes, left, right, speed, fspd, capacity)
)

rawDescription: Initializing instance variable: Idiomatic way


code:
from datetime import datetime
format(datetime.now(), '%Y')

rawDescription: String output modifiers in Python

description: String output modifiers in Python


code:
import struct
import time
x = int(time.time())
x
hex(x)
struct.pack('<Q', x)

rawDescription: How write local time (REG_BINARY) to registry with _winreg Python


code:
# -*- coding: utf-8 -*-
import boto
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message

QNAME = 'qinbound'
SQSREGION = 'us-west-1'

class Qserver():
    """A simple Q server."""
    _current_message = None

    def __init__(self, qname=None, sqsregion=None):
        self.qname = qname or QNAME
        self.sqsregion = sqsregion or SQSREGION
        self.sqsconn = boto.sqs.connect_to_region(self.sqsregion)
        self.q_in = self.sqsconn.get_queue(self.qname)

    def __iter__(self):
        return self

    def __next__(self):
        while True:
            qmessage = self.q_in.read(wait_time_seconds=20)
            if qmessage is not None:
                self._current_message = qmessage
                return qmessage

    next = __next__

    def delete_current(self):
        if self._current_message is not None:
            self.q_in.delete_message(self._current_message)

rawDescription: Python - how can I use generators more succinctly?


rawDescription: A more elegant way of creating tuples of tuples from lists


code:
try:
  binary = struct.pack('>f', value)
  if struct.unpack('>f', binary)[0] != value:
    binary = struct.pack('>d', value)
except OverflowError:
  binary = struct.pack('>d', value)

rawDescription: Differentiate between single and double precision


code:
import importlib

def call_command(cmd):
    mod = importlib.import_module('get_' + cmd)
    func = getattr(mod, cmd)
    return func()

rawDescription: best practices: dynamic method execution in python

description: Best practices: dynamic method execution in python


code:
class WashHandler(object):

    def __init__(self):
        self.cost = 0

    def main_wash(self):
        self.cost += 5
        user_input = input("yes or no, Do you want soap added?")

        if user_input == "yes":
            self.soap_addition()

        self.drying_addition()
        self.finish()

    def soap_addition(self):
        self.cost += 2

    def drying_addition(self):
        self.cost += 1

    def finish(self):
        print("Your total is ", str(self.cost))

rawDescription: how to pass over a function if not called upon

description: Pass over a function if not called upon


code:
def recur(v, times, lst=[]):
    if (times != 0):
        v = vclass.makesomething(v,a).attribute1()
        lst.append(v)
        return recur(v, times-1, lst)
    return lst

rawDescription: writing a recurring code that takes previous defined instance and creates new one

description: Writing a recurring code that takes previous defined instance and creates new one


code: resultList = [x.decode("utf-8") for x in initList ] # where utf-8 is encoding used

rawDescription: editing List content in Python

description: Editing List content in Python


code:
from bs4 import BeautifulSoup

data = """

"""

soup = BeautifulSoup(data, 'html.parser')

for div in soup.find_all('div', {'x-attrsite': True}):
    del div['x-attrsite']
    div['{attrsite}'] = None

for div in soup.find_all('div', {'x-inner': True}):
    div.replace_with('{inner}')

print(soup.prettify())

rawDescription: How to parse HTML to a string template in Python?

description: Parse HTML to a string template in Python


code:
from random import randrange
def is_prime(n, k=10):
    if n == 2:
        return True
    if not n & 1:
        return False

    def check(a, s, d, n):
        x = pow(a, d, n)
        if x == 1:
            return True
        for i in xrange(s - 1):
            if x == n - 1:
                return True
            x = pow(x, 2, n)
        return x == n - 1

    s = 0
    d = n - 1

    while d % 2 == 0:
        d >>= 1
        s += 1

    for i in xrange(k):
        a = randrange(2, n - 1)
        if not check(a, s, d, n):
            return False
    return True

rawDescription: Working with large primes in Python

description: Working with large primes in Python


code:
import feedparser
rsslist=["http://skottieyoung.tumblr.com/rss", "http://mrjakeparker.com/feed/"]

def feed_modified_date(feed):
    # this is the last-modified value in the response header
    # do not confuse this with the time that is in each feed as the server
    # may be using a different timezone for last-resposne headers than it
    # uses for the publish date

    modified = feed.get('modified')
    if modified is not None:
        return modified

    return None

def max_entry_date(feed):
    entry_pub_dates = (e.get('published_parsed') for e in feed.entries)
    entry_pub_dates = tuple(e for e in entry_pub_dates if e is not None)

    if len(entry_pub_dates) > 0:
        return max(entry_pub_dates)

    return None

def entries_with_dates_after(feed, date):
    response = []

    for entry in feed.entries:
        if entry.get('published_parsed') > date:
            response.append(entry)

    return response

for feed_url in rsslist:
    print('--------%s-------' % feed_url)
    d = feedparser.parse(feed_url)
    print('feed length %i' % len(d.entries))

    if len(d.entries) > 0:
        etag = d.feed.get('etag', None)
        modified = feed_modified_date(d)
        print('modified at %s' % modified)

        d2 = feedparser.parse(feed_url, etag=etag, modified=modified)
        print('second feed length %i' % len(d2.entries))
        if len(d2.entries) > 0:
            print("server does not support etags or there are new entries")
            # perhaps the server does not support etags or last-modified
            # filter entries ourself

            prev_max_date = max_entry_date(d)

            entries = entries_with_dates_after(d2, prev_max_date)

            print('%i new entries' % len(entries))
        else:
            print('there are no entries')

rawDescription: Python etag/last modified not working; how to get latest rss


code: print('the words in this synset are ' + word[0] + ',' + word[1])

rawDescription: Assigning variables in a loop in Python

description: Assigning variables in a loop in Python


code:
import win32com.client
catapp = win32com.client.Dispatch('CATIA.Application')
satapp.StartCommand('Your_macro_name')

rawDescription: Run a Catia macro with a python script

description: Run a Catia macro with a python script


code:
super(B).m
super(B).__get__(B(), B)

rawDescription: Usage of Python 3 super()

description: Usage of Python 3 super()


code: r = re.split(r'\n\s*\n', data) # for more than 2 newlines: r'\n[\s\n]*\n'

rawDescription: Python regex - split string at back to back line breaks with [possibly] spaces in between


rawDescription: Extract items from n-line chunks in a file, count frequency of items for each chunk, Python


code: tree = nx.bfs_tree(G, 4)

rawDescription: How can i get directed tree from graph?

description: Get directed tree from graph


code:
import csv

grades = {}
with open('grades.tsv', newline='') as csv_f:
    for row in csv.DictReader(csv_f, delimiter='\t'):
        fullname = row['fname'] + ' ' + row['lname']
        grades[fullname] = float(row['marks'])

print(grades)

rawDescription: Creating a dictionary from csv

description: Creating a dictionary from csv


rawDescription: Split and retain character of split python


code:
import operator

operators = {"+": operator.add, "-": operator.sub, "*": operator.mul}
operand1 = random.choice(numbers)
operand2 = random.choice(numbers)
op = random.choice(operators)
expected_answer = op(operand1, operand2)

rawDescription: Make python ask questions from strings

description: Make python ask questions from strings


rawDescription: merge sift descriptor matrix, numpyarray

description: Merge sift descriptor matrix, numpyarray


code:
n = 2    # axis to slice along

sliced2 = np.rollaxis(np.rollaxis(a, n, 0)[1::2], 0, n + 1)

assert np.all(sliced1 == sliced2)

rawDescription: numpy take can't index using slice

description: Numpy take can't index using slice


code:
from publicsuffix import PublicSuffixList
psl = PublicSuffixList()
psl.get_public_suffix(res.netloc)
psl.get_public_suffix('www.example.domain.co.uk')

rawDescription: Python web scraping - print only part of url


code:
class FederalHoliday(AutoEnum):
    NewYear = "First day of the year.", 'absolute', Month.JANUARY, 1
    MartinLutherKingJr = "Birth of Civil Rights leader.", 'relative', Month.JANUARY, Weekday.MONDAY, 3
    President = "Birth of George Washington", 'relative', Month.FEBRUARY, Weekday.MONDAY, 3
    Memorial = "Memory of fallen soldiers", 'relative', Month.MAY, Weekday.MONDAY, 5
    Independence = "Declaration of Independence", 'absolute', Month.JULY, 4
    Labor = "American Labor Movement", 'relative', Month.SEPTEMBER, Weekday.MONDAY, 1
    Columbus = "Americas discovered", 'relative', Month.OCTOBER, Weekday.MONDAY, 2
    Veterans = "Recognition of Armed Forces service", 'relative', Month.NOVEMBER, 11, 1
    Thanksgiving = "Day of Thanks", 'relative', Month.NOVEMBER, Weekday.THURSDAY, 4
    Christmas = "Birth of Jesus Christ", 'absolute', Month.DECEMBER, 25

    def __init__(self, doc, type, month, day, occurance=None):
        self.__doc__ = doc
        self.type = type
        self.month = month
        self.day = day
        self.occurance = occurance

    def date(self, year):
        "returns the observed date of the holiday for `year`"
        if self.type == 'absolute' or isinstance(self.day, int):
            holiday =  Date(year, self.month, self.day)
            if Weekday(holiday.isoweekday()) is Weekday.SUNDAY:
                holiday = holiday.replace(delta_day=1)
            return holiday
        days_in_month = days_per_month(year)
        target_end = self.occurance * 7 + 1
        if target_end > days_in_month[self.month]:
            target_end = days_in_month[self.month]
        target_start = target_end - 7
        target_week = list(xrange(start=Date(year, self.month, target_start), step=one_day, count=7))
        for holiday in target_week:
            if Weekday(holiday.isoweekday()) is self.day:
                return holiday

    @classmethod
    def next_business_day(cls, date, days=1):
        """
        Return the next `days` business day from date.
        """
        holidays = cls.year(date.year)
        years = set([date.year])
        while days > 0:
            date = date.replace(delta_day=1)
            if date.year not in years:
                holidays.extend(cls.year(date.year))
                years.add(date.year)
            if Weekday(date.isoweekday()) in (Weekday.SATURDAY, Weekday.SUNDAY) or date in holidays:
                continue
            days -= 1
        return date

    @classmethod
    def year(cls, year):
        """
        Return a list of the actual FederalHoliday dates for `year`.
        """
        holidays = []
        for fh in cls:
            holidays.append(fh.date(year))
        return holidays

rawDescription: Python enum, when and where to use?

description: Python enum, when and where to use


code:
import os, pprint
filenames = [f for f in os.listdir('D:\\Freeware')]
name_and_ext_list = [os.path.splitext(f) for f in filenames]
pprint.pprint(filenames)
pprint.pprint(name_and_ext_list)

rawDescription: Renaming files according to a set of rules


code:
import datetime

new_l = sorted((x.split('~') for x in l),
               key=lambda x: (x[0],
                              datetime.datetime.strptime(x[3], '%m/%d/%Y %H:%M'),
                              x[2],
                              x[1]))

rawDescription: Sorting a list of strings by their components


code:
class Color(HashableObject):
    """Named colors for use in styles."""
    BLACK = 'FF000000'
    WHITE = 'FFFFFFFF'
    RED = 'FFFF0000'
    DARKRED = 'FF800000'
    BLUE = 'FF0000FF'
    DARKBLUE = 'FF000080'
    GREEN = 'FF00FF00'
    DARKGREEN = 'FF008000'
    YELLOW = 'FFFFFF00'
    DARKYELLOW = 'FF808000'

rawDescription: Setting styles in Openpyxl

description: Setting styles in Openpyxl


code:
self.btn = tk.Button(self, text = "button")
self.btn.grid(row = 1, column = 1)

rawDescription: How to make Tkinter button to be placed in particular position?

description: Make Tkinter button to be placed in particular position


code:
import collections

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el

rawDescription: How to flatten a list of list with variable lengths into a single list? python

description: Flatten a list of list with variable lengths into a single list? python


code:
def divider(lst,n):
    lst = [float(x) for x in lst[::-1]]
    for i in range(1,n+1):
        lst = [x/i for x in lst]
        yield lst

rawDescription: loop through a list and use previous elements

description: Loop through a list and use previous elements


rawDescription: How do I create a tree out of this?

description: Create a tree out of this


code:
date_series = pd.date_range('2015-01-05', '2015-01-15', freq='1D')
date_df = pd.DataFrame(dict(date=date_series, dummy=1))

cross_join = date_df.merge(df, on='dummy')
cond_join = cross_join[(cross_join.start <= cross_join.date) & (cross_join.date <= cross_join.end)]
grp_join = cond_join.groupby(['date'])
final = (
    pd.DataFrame(dict(
        val_count=grp_join.size(),
        val_sum=grp_join.value.sum(),
        val_median=grp_join.value.median()
    ), index=date_series)
    .fillna(0)
    .reset_index()
)

rawDescription: Aggregate events with start and end times with Pandas


code:
def __init__(self, *args):
    # ...
    self._ids = {}

def append(self, id, value):
    if id in ids:
        raise ValueError('This order already exists!')
    super(Orders, self).append(Order(id, value))
    self._ids[id] = len(self) - 1

rawDescription: Remove namedtuple from list based on value


code:
import argparse
myparser = argparse.ArgumentParser(description='parser test')
myparser.add_argument("product_1", help="enter product1")
myparser.add_argument("product_2", help="enter product2")

args = myparser.parse_args()
firstProduct = args.product_1
secondProduct = args.product_2
print(firstProduct, secondProduct)

rawDescription: python using argparse.ArgumentParser method

description: Python using argparse.ArgumentParser method


code:
for j in range(count):
    g.append(data[j]['club_name'])
    identity.append(data[j]['url'])

rawDescription: Consuming JSON into django view

description: Consuming JSON into django view


code:
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

rawDescription: Get full path for a file in python

description: Get full path for a file in python


rawDescription: How to call an existing LibreOffice python macro from a python script

description: Call an existing LibreOffice python macro from a python script


code:
import multiprocessing
import time

lock = multiprocessing.Lock()

def worker(nr):
    lock.acquire()
    time.sleep(0.100)
    lock.release()
    print(nr)

numbers = [i for i in range(20)]

if __name__ == '__main__':
    multiprocessing.freeze_support()
    pool = multiprocessing.Pool(processes=3)
    results = pool.map(worker, numbers)
    pool.close()
    pool.join()

rawDescription: Is it possible to start Pool processes sequentially?


code: df['timestamp'] = df.apply(lambda row: pd.Timestamp(row.date + ' ' + row.time), axis=1)

rawDescription: Indexing by multiple fields with pandas in python


rawDescription: I am having trouble exiting my infinite loop in pygame


code:
server.select(imap_folder)
# List all messages
typ, data = server.search(None, 'ALL')
# iterate through messages
for num in data[0].split():
    typ, data = server.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])')
    # parse data to get message id

rawDescription: How to get 'Message-ID' using imaplib

description: Get 'Message-ID' using imaplib


code:
def find_files(root,d):
    for directory,subdirs,files in os.walk(root):
        if d in subdirs:
            yield os.join(root,directory,d)

rawDescription: Python Glob.glob: a wildcard for the number of directories between the root and the destination


code:
lookupTable, indexed_dataSet = np.unique(dataSet, return_inverse=True)
lookupTable
indexed_dataSet

rawDescription: Map a NumPy array of strings to integers


code:
class Program():

    def __init__(self):
        self._access_token = None
        self._refresh_token = None
        self.CONFIG_PATH = 'test.conf'

    def write_tokens_to_config(self):
        """Write token value to the config
        """

        parser = SafeConfigParser()
        parser.read(self.CONFIG_PATH)
        if not parser.has_section('Token'):
            parser.add_section('Token')
        parser.set('Token', 'access_token', self._access_token)
        parser.set('Token', 'refresh_token', self._refresh_token)
        with open(self.CONFIG_PATH, 'wb') as f:
            parser.write(f)

rawDescription: Python SafeConfigParser mocking

description: Python SafeConfigParser mocking


code:
from collections import Counter
with open('calculate_ids.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',', quotechar='|')
     counts = Counter(map(tuple,reader))

rawDescription: Count the elements in a csv file with python


rawDescription: ManyToMany relation custom serializer

description: ManyToMany relation custom serializer


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

xs = np.linspace(0, 1, 20); ys = np.sin(xs)

fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(xs, ys)

# This should be called after all axes have been added
fig.tight_layout()
fig.savefig('test.png')

rawDescription: Reduce left and right margins in matplotlib plot


code:
b_new = -(1/tau)*log((1+L2*b)/kinf)
b_delta = b_new - b
# do whatever you want with b_delta and finally override the old b with the new b
b = b_new

rawDescription: Transcendental Equation

description: Transcendental Equation


code:
from itertools import product

dic = {}
for z, y, x in product(range(20), range(150), range(200)):
    dic[x, y, z] = [self.images[j].GetScalarComponentAsDouble(x, y, z, 0)
                     for j in range(4)]

rawDescription: Different list values for dictionary keys


code:
# important.py

# This magic variable controls what gets import via
# from important import *
__all__ = ['dothis', 'dothat']

def dothis():
    pass

def dothat():
    pass

def private1():
    pass

rawDescription: Always include file when importing module in python


code:
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FuncFormatter
fig, ax = plt.subplots(1, 1)

def alternate_formatter(x, ind):
    rm = np.mod(x, 1)
    if np.abs(rm) < .1:
        return '{:d}'.format(int(x))
    return '{:.1f}'.format(rm)

ax.xaxis.set_major_locator(MultipleLocator(.5))
ax.xaxis.set_major_formatter(FuncFormatter(alternate_formatter))

ax.set_xlim(0, 10)

rawDescription: Manipulate xticks, need every second xtick to just be the decimal and smaller font


code:
import thread

class GlobalRequestMiddleware(object):
    _threadmap = {}

    @classmethod
    def get_current_request(cls):
        return cls._threadmap[thread.get_ident()]

    def process_request(self, request):
        self._threadmap[thread.get_ident()] = request

    def process_exception(self, request, exception):
        try:
            del self._threadmap[thread.get_ident()]
        except KeyError:
            pass

    def process_response(self, request, response):
        try:
            del self._threadmap[thread.get_ident()]
        except KeyError:
            pass
        return response

rawDescription: Is there a way to access the context from everywhere in Django?


rawDescription: Broadcasting a python function on to numpy arrays


rawDescription: Adding + sign to exponent in matplotlib axes


code:
from rest_framework import serializers

from polls.models import Order

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ('doc', 'order', 'nothing')

# note we do not use other serializers

rawDescription: Importing data to a particular model

description: Importing data to a particular model


rawDescription: Print lists Advanced

description: Print lists Advanced


code:
transposed = {key_b: {key_a: dct[key_a].get(key_b, '') for key_a in dct}
              for key_b in keys}

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code: new_list = filter(lambda foo: foo.location == 2, foos)

rawDescription: How to map 2 lists with comparison in python

description: Map 2 lists with comparison in python


code:
f = open('input.csv', 'r')
g = open('output.txt', 'w')

# Header lines must be kept separately since we will be using them for every time
first_line = f.readline()
headers = first_line.split(',')
headers[-1] = headers[-1].strip()
length = len(headers)

# Capitalize each header word.
for i in range(length):
    headers[i] = headers[i].capitalize()

counter = 1
for line in f:
    values = line.split(',')
    values[-1] = values[-1].strip() #remove EOL character
    g.write('[Wind' + str(counter) + ']' + "\n")
    for i in range(length):
        g.write(headers[i] + "=" + values[i] + "\n")
    counter += 1

g.close()
f.close()

rawDescription: Write text from EXCEL to text as a LIST using PYTHON or other programming method


code: (total-free)/total

rawDescription: Python system resources enumeration

description: Python system resources enumeration


code:
merged = df.merge(df2, on='key')

valid = (merged.date >= merged.valid_from) & \
        (merged.date <= merged.valid_to)

df['joined_value'] = merged[valid].value_y

rawDescription: SQL like joins in pandas

description: SQL like joins in pandas


code:
with open("ex4.txt") as inf:
    data = []
    for line in inf:
            line = line.split()
            if (len(line)==3) and (tuple(line) not in data):
                    data.append(tuple(line))

data

rawDescription: Sorting items in a text file in python

description: Sorting items in a text file in python


code: min(points_list, key=lambda x: distance(x, point_a))

rawDescription: How can I get the element of a list that has a minimum/maximum property in Python?

description: Get the element of a list that has a minimum/maximum property in Python


code:
from collections import Counter
inpt = [{'object':'square', 'color':'red', 'size':'big'},
        {'object':'square', 'color':'red', 'coord':(0,0)},
        {'object':'square', 'color':'red'},
        {'object':'triangle', 'color':'blue', 'adj':'beautiful'},
        {'object':'triangle', 'color':'blue', 'attr':'none'}]
Counter((d['object'], d['color']) for d in inpt)
_.most_common()

rawDescription: counting common key-value pairs in a list of dictionaries

description: Counting common key-value pairs in a list of dictionaries


code: dict((a,int(b)) for a,b in (t.split('=') for t in s.split(',')))

rawDescription: From string in a csv cell to dict

description: From string in a csv cell to dict


code:
from itertools import groupby
from nltk.tree import Tree

def get_pairs(t, cat):
    pairs = sorted(_get_pairs(t, cat), key=lambda x:x[0])
    for is_none, _adjacents in groupby(pairs, lambda x:x[1] is None):
        if is_none:
            continue
        adjacents = list(_adjacents)
        for (_, p1), (_, p2) in zip(adjacents, adjacents[1:]):
            yield p1, p2

def _get_pairs(t, cat, path=(), idx=(), has_root_cat=False):
    if isinstance(t, str):
        if has_root_cat:
            yield idx, path[:-1] + ((path[-1], t,),)
        else:
            yield idx, None
        return
    for i, ch in enumerate(t):
        found_cat = has_root_cat or t.node == cat
        new_path = path + (t.node,) if found_cat else path
        new_idx = idx + (i,)
        get_pairs_children = _get_pairs(ch, cat, new_path, new_idx, found_cat)
        for pair in get_pairs_children:
            yield pair

rawDescription: NLTK: how can I list all pairs of adjacent subtrees (rooted in specific nonterminal) of a parse tree


code:
def clear(self):
    self.RobotMap = [[self.EmptyValue for i in xrange(self.sizeY)] for j in xrange(self.sizeX)]

rawDescription: python script speed improvements

description: Python script speed improvements


code: set([endDate - timedelta(x) for x in xrange(days)]) - set(queryset)

rawDescription: Return a list of missing values?

description: Return a list of missing values


code:
def save(lst):
    for i in range(len(lst)):
        txtfile = "enegep{}.txt".format(i) #enegep is like the identifier of the files
        artigo = convert_pdf_to_txt(lista[0])
        with open(txtfile, "w") as textfile:
            textfile.write(artigo)

rawDescription: PDF scraping: how to automate the creation of txt files for each pdf scraped in Python?


rawDescription: numpy with python: convert 3d array to 2d

description: Numpy with python: convert 3d array to 2d


code:
timeit('{a: 1 for a in range(100)}')
timeit('dict.fromkeys(range(100), 1)')

rawDescription: Python converting a list into a dict with a value of 1 for each key


code:
import vtk

# create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# create points
points = vtk.vtkPoints()
points.InsertNextPoint(1.0,0.0,0.0)
points.InsertNextPoint(0.0,0.0,0.0)
points.InsertNextPoint(0.0,1.0,0.0)

triangle = vtk.vtkTriangle()
triangle.GetPointIds().SetId(0,0)
triangle.GetPointIds().SetId(1,1)
triangle.GetPointIds().SetId(2,2)

triangles = vtk.vtkCellArray()
triangles.InsertNextCell(triangle)

# polydata object
trianglePolyData = vtk.vtkPolyData()
trianglePolyData.SetPoints( points )
trianglePolyData.SetPolys( triangles )

# mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(trianglePolyData)

# actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)

# assign actor to the renderer
ren.AddActor(actor)

#++++++++++++++++++++++++++++++++++++++++++++++++
# Get the edges from the mesh
edges = vtk.vtkExtractEdges()
edges.SetInput(trianglePolyData)
edge_mapper = vtk.vtkPolyDataMapper()
edge_mapper.SetInput(edges.GetOutput())

# Make an actor for those edges
edge_actor = vtk.vtkActor()
edge_actor.SetMapper(edge_mapper)

# Make the actor red (there are other ways of doing this also)
edge_actor.GetProperty().SetColor(1,0,0)

ren.AddActor(edge_actor)

# Avoid z-buffer fighting
vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()
#------------------------------------------------

# enable user interface interactor
iren.Initialize()
renWin.Render()
iren.Start()

rawDescription: How to display only triangle boundaries on textured surface in vtk?

description: Display only triangle boundaries on textured surface in vtk


rawDescription: Round labels and sum values in label-value pair 2d-numpy array


code:
import json
ds = json.loads(json_data_string) #this contains the json
unique_stuff = { each['obj_id'] : each for each in ds }.values()

rawDescription: Remove duplicates from json data

description: Remove duplicates from json data


code:
timeit.repeat(lambda: [d[ind] for ind in sub_list])
timeit.repeat(lambda: map(lambda ind: d[ind], sub_list))

rawDescription: Retrieve properties of a class instance stored in a dictonary


rawDescription: numpy.ma.cov - pairwise correlations for with missing values?

description: Numpy.ma.cov - pairwise correlations for with missing values


code:
import numpy as np
np.array(a).T.tolist()

rawDescription: Transpose nested list in python

description: Transpose nested list in python


code:
already_seen = set()

for line in myfile:
    for word in mylist:
        if word in already_seen:
            continue

        if word in line:
            print(word + "found")
            already_seen.add(word)

rawDescription: Comparing a word in a list to a word in a file


code:
class Company(models.Model):
    pass

class Item(models.Model):
    ...
    owner = models.ForeignKey(Company, related_name='owned_items')
    holder = models.ForeignKey(Company, related_name='held_items')

rawDescription: How to model lending items between a group of companies

description: Model lending items between a group of companies


rawDescription: How do I create a group of lists from imported data from access?

description: Create a group of lists from imported data from access


code:
# The kind argument can also take values "multilist", "singlelist", "text",
# "clickable" and "file":
#  find first control that will accept text, and scribble in it
form.set_value("rhubarb rhubarb", kind="text", nr=0)

rawDescription: Filling textarea with Python mechanize module


code: os.path.relpath('/absolute/path', '/')

rawDescription: Most pythonic way to relocate a path to a new root directory


rawDescription: Python - Replace part of regex?

description: Python - Replace part of regex


rawDescription: Find average in a 2D array

description: Find average in a 2D array


rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


code: x = row.translate(None, string.digits)

rawDescription: Convert string (without any separator) to list


code: dict(zip(headers, zip(*sdata)))

rawDescription: Storing the columns of a spreadsheet in a Python dictionary


rawDescription: Printing "*" characters separated by dashes with the print function's "sep" paramter


code: beef, chicken, corn, cheese, yogurt, hippo

rawDescription: Removing a comma after list ends

description: Removing a comma after list ends


code:
BUCKET_SIZE_DAYS = 10

def put(self):
    self.manufacture_bucket = int(self.manufacture_date.toordinal() / BUCKET_SIZE_DAYS)
    super(self.__class__, self).put()

def filter_date_after(self, date_start):
    first_bucket = int(date_start.toordinal() / BUCKET_SIZE_DAYS)
    last_bucket = int(datetime.datetime.today().toordinal() / BUCKET_SIZE_DAYS)

    for this_bucket in range(first_bucket, last_bucket+1):
        for found in self.filter("manufacture_bucket =", this_bucket):
            if found.manufacture_date >= date_start:
                yield found

rawDescription: Inequality Filters on a date and a number


code:
from collections import Counter
w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
c = Counter(w)

rawDescription: Numpy bincount() with floats

description: Numpy bincount() with floats


code:
from pybrain.tools.shortcuts import buildNetwork
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.datasets import SupervisedDataSet,UnsupervisedDataSet
from pybrain.structure import LinearLayer
ds = SupervisedDataSet(10, 11)
z = map(int,'1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6 1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6 1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7'.split())
obsLen = 10
predLen = 11
for i in xrange(len(z)):
  if i+(obsLen-1)+predLen < len(z):
    ds.addSample([z[d] for d in range(i,i+obsLen)],[z[d] for d in range(i+1,i+1+predLen)])

net = buildNetwork(10, 20, 11, outclass=LinearLayer,bias=True, recurrent=True)
trainer = BackpropTrainer(net, ds)
trainer.trainEpochs(100)
ts = UnsupervisedDataSet(10,)
ts.addSample(map(int,'1 3 5 7 2 4 6 7 1 3'.split()))
[ int(round(i)) for i in net.activateOnDataset(ts)[0]]

rawDescription: Request for example: Recurrent neural network for predicting next value in a sequence


code:
def check_call(args):
    subprocess.check_call(args)

rawDescription: How would you test this function?

description: How would you test this function


code:
parser = argparse.ArgumentParser()
parser.add_argument("operation", help="mathematical operation that will be performed",
    choices=['add', 'subtract', 'multiply', 'divide'])
parser.add_argument("num1", help="the first number", type=int)
parser.add_argument("num2", help="the second number", type=int)
args = parser.parse_args()

rawDescription: Python - Difference between docopt and argparse


code: ' '.join(' '.join(nltk.tag.tuple2str(item) for item in sent) for sent in tpl)

rawDescription: operating on embedded tuples/strings, python

description: Operating on embedded tuples/strings, python


rawDescription: Python format output in concise manner

description: Python format output in concise manner


code:
import math

# Initialize the calendar matrix
cal = []
for i in range(5): # 5 weeks
    cal.append([])
    for j in range(7): # 7 days per week
        cal[i].append('')

# Set the calendar for some month
start = 3 # Wed
for day in range(31):
    row = math.floor( (day+start) / 7)
    col = (day+start) - 7*row
    cal[row][col] = str(day+1)

print(cal)

rawDescription: python tkinter calender, placing the numbers

description: Python tkinter calender, placing the numbers


rawDescription: How to access axis label object in matplotlib?

description: Access axis label object in matplotlib


code:
import urllib.request
req = urllib.request.Request("http://www.google.com", method="HEAD")
resp = urllib.request.urlopen(req)
resp.url

rawDescription: Why am I able to read a HEAD http request in python 3 urllib.request?


code:
['Marilyn Manson', 'Web', 'Skydera Inc.', 'Stone Sour']
['Voices Inside', 'Expressivista']

rawDescription: How to split tokens, count number of tokens, and write in a file in python?

description: Split tokens, count number of tokens, and write in a file in python


code: {pkg: ver for pkg, ver in packages if "numpy" in pkg}

rawDescription: Searching PyPI by topic

description: Searching PyPI by topic


code:
def myfunc(row):
    return sum(row) > .5

bool_arr = np.array([myfunc(row) for row in x])
x_new = x[bool_arr]

rawDescription: Filter rows of a numpy array?

description: Filter rows of a numpy array


code:
from datetime import datetime, timezone
d = datetime.now(timezone.utc)
d
str(d)
d.strftime('%a, %d %b %Y %H:%M:%S %Z')
d.strftime('%a, %d %b %Y %H:%M:%S %z')

rawDescription: How make Javascript new Date().toUTCString() into Python


rawDescription: How to append dictionary to a list in loop

description: Append dictionary to a list in loop


code:
self.StatusTextVar = "Success"
self.StatusTextVar = "Wrong input. Retry"

rawDescription: Python 2.7: updating Tkinter Label widget content


rawDescription: How to convert a unicode character representation from string to unicode in python?

description: Convert a unicode character representation from string to unicode in python


code:
customers = [
    ['customerID1', 'NameOfCustomer1', 'e','t','c', '01 02 03'],
    ['customerID2', 'NameOfCustomer2', 'e','t','c', '02 05']
    ]

cust_keys = ('id', 'name', 'q1','q2','q3','categories')
cdicts = [dict(zip(cust_keys, cust_vals)) for cust_vals in customers]
cdicts

rawDescription: How to use a list item to address a dictionary key and append the respective value

description: Use a list item to address a dictionary key and append the respective value


code:
from pprint import pprint
from datetime import datetime
from itertools import groupby

rows = [('Frodo party', datetime(3018, 9, 22, 10, 38)),
        ('Nazgul defeat Rangers', datetime(3018, 9, 22, 11, 57)),
        ('Frodo finishes packing', datetime(3018, 9, 23, 10, 59)),
        ('Gandalf tames Shadowfax', datetime(3018, 9, 23, 13, 11)),
        ('Gandalf crosses the Isen', datetime(3018, 9, 24, 18, 46))]

for key, values in groupby(rows, key=lambda row: row[1].date()):
    print('-')
    pprint(key)
    pprint(list(values))

rawDescription: Django - Group By with Date part alone

description: Django - Group By with Date part alone


code:
# create aliases for each assumed user (A, B, C)
A = aliased(User)
B = aliased(User)
C = aliased(User)
# also aliases to navigate relationship and check same user
Aa = aliased(User)
Bb = aliased(User)

triads = (
    session.query(A, B, C)
    .join(B, A.follows)  # A follows B
    .join(Aa, B.follows).filter(Aa.id == A.id)  # B follows Aa (same as A)
    .join(C, A.follows)  # A follows C
    .join(Bb, C.follows).filter(Bb.id == B.id)  # C follows Bb (same as B)
    .filter(~C.follows.any(User.id == A.id))  # exclude C following A
)

for a, b, c in triads:
    print(a, b, c)

rawDescription: SQLAlchemy: directed relationships within triads


code:
@task()
@log_begin_end
def srv_dev(destination=development):
    configure(file_server, destination)

rawDescription: How to simplify python logging code

description: Simplify python logging code


code:
r = g.groupby(level='c2').apply(lambda x: x.loc['a'] - x.loc['b'])
r

rawDescription: how to perform calculations across specific rows and columns of a crosstabulation in pandas?

description: Perform calculations across specific rows and columns of a crosstabulation in pandas


code:
class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.text = CustomText(self)
        self.vsb = tk.Scrollbar(orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.text.tag_configure("bigfont", font=("Helvetica", "24", "bold"))
        self.linenumbers = TextLineNumbers(self, width=30)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side="right", fill="y")
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)

        self.text.insert("end", "one\ntwo\nthree\n")
        self.text.insert("end", "four\n",("bigfont",))
        self.text.insert("end", "five\n")

    def _on_change(self, event):
        self.linenumbers.redraw()

rawDescription: Tkinter adding line number to text widget


rawDescription: Python apply_along_axis of multiple arrays


code:
import json
from pprint import pprint

import lxml.html
import requests

response = requests.get('http://scores.espn.go.com/nba/scoreboard?date=20150405')
doc = lxml.html.fromstring(response.content)

data = doc.xpath("//div[@id='scoreboard-page']/@data-data")[0]
data = json.loads(data)

pprint(data)

rawDescription: Scraping new ESPN site using xpath [Python]


code:
maxx=[]
a=[(1,2),(4,5),(1,0)]
b = [(3,2),(9,4),(2,2)]
maxx.append(a.pop(a.index(max(a,key=sum))))
maxx.append(b.pop(b.index(max(b,key=sum))))
a
b
maxx

rawDescription: Python adding values in Tuples

description: Python adding values in Tuples


code: listbox.insert(END, i, *dic[i])

rawDescription: Python Tkinter:When string with space inserted into Listbox, brackets appear


code:
ab = list(itertools.chain(
    (i['name'] for i in user),
    (i['rating'] for i in next_level),
    (i['count'] for i in comment_values),
    (i['count'] for i in likes_values),
    (i['value'] for i in rating_values),
    (i['date'] for i in date),
))

rawDescription: Django turn lists into one list

description: Django turn lists into one list


code:
class users(db.Model):
    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    userName = db.Column(db.String, nullable=False)

    friends = association_proxy(
        '_friends', 'friend',
        creator=lambda v: friendships(friend=v),
    )

    best_friend = db.relationship(
        'users',
        secondary='BestFriends',
        primaryjoin='users.id==bestFriends.user_id',
        secondaryjoin='users.id==bestFriends.best_friend_id',
        uselist=False,
        backref=db.backref('best_friend_of', uselist=False),
    )

class friendships(db.Model):
    __tablename__ = "Friendships"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)
    friend_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)

    user = db.relationship(users, foreign_keys=user_id, backref='_friends')
    friend = db.relationship(users, foreign_keys=friend_id)

class bestFriends(db.Model):
    __tablename__ = "BestFriends"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False)
    best_friend_id = db.Column(db.Integer, db.ForeignKey('Users.id'))

rawDescription: Build Model.query of a related model

description: Build Model.query of a related model


code:
file1 = open("karolo.txt","w")
file3 = open("karolo.txt","r")
file1.write("abcd\n")
file1.flush()
file34 = file3.read()
print(file34)

#remember to close the files when you are done with them!
file1.close()
file3.close()

rawDescription: How to print strings from a txt file in python3.x

description: Print strings from a txt file in python3.x


code:
def defaultdict_factory_factory(default_factory):
    return partial(defaultdict, default_factory)

rawDescription: Populating a defaultdict at init time

description: Populating a defaultdict at init time


code:
for i in range(1,109):
    url = "http://www.bbc.co.uk/food/recipes/search?page={pagenum}&cuisines[0]=british&sortBy=lastModified".format(pagenum = i)
    doYourThing(url)

rawDescription: Parsing of multiple webpages using Python


code:
if(singlePlayerCard in [1,2,3,4,5,6,7,8,9,10]):
    singlePlayerCardValue = singlePlayerCard

rawDescription: Python Blackjack game - referenced before assignment


code:
import os
import sys

with open('/dev/tty6', 'rb') as inf, open('/dev/tty6', 'wb') as outf:
    os.dup2(inf.fileno(), 0)
    os.dup2(outf.fileno(), 1)
    os.dup2(outf.fileno(), 2)

rawDescription: Sending curses application's output to tty1


rawDescription: Pythonic way to merge two overlapping lists, preserving order


code:
print(" ".join(["{"+w[1:]+"}" if w[0] == "%" else w for w in s.split(" ")]).format(*args))

three and two and one

rawDescription: String formatting : Replace "%0 %1 %2" with tuple with 0,1,2 indexes


rawDescription: Remove elements from the array

description: Remove elements from the array


code:
w.sendline('stty -echo')
w.prompt()

rawDescription: How to get filename from remote location into string in Python?

description: Get filename from remote location into string in Python


code: m = np.arange(5*4).reshape(5,4)

rawDescription: Dot product between a matrix and a 1d-array in numpy


code:
seen = set()
np.array([x for x in a if seen.isdisjoint(x) and not seen.update(x)])

rawDescription: Removing rows in a 2D array that have the same value


code:
import re
text = "This is the description of  the
 text"
text = re.sub("<.*?>", "", text)
#text = "This is the description of  the  text"

rawDescription: Delete HTML Tags from string Python

description: Delete HTML Tags from string Python


code: f(*secondary_args, x, y, z, **secondary_kwargs)

rawDescription: Differences between functools.partial and a similar lambda?


code:
def users():
    form = SQLFORM.grid(db.auth_user)
    return dict(form=form)

rawDescription: How can I create new auth_user and auth_group on Web2py running on Google App Engine (GAE)?

description: Create new auth_user and auth_group on Web2py running on Google App Engine (GAE)


code:
def apply_recursive(ob, func):
    if not isinstance(ob, list):
        return func(ob)
    return [apply_recursive(elem, func) for elem in ob]

rawDescription: How to create a new nested list from a function and an existing nested list in python?

description: Create a new nested list from a function and an existing nested list in python


code:
from itertools import chain
list(chain(*(someDict[x] for x in supraList)))

rawDescription: List comprehension with some kind of loop interdependence?


code:
from django.db import connection, transaction
from django.db.models.signals import post_delete, post_save

def update_b_count(instance, **kwargs):
    """
    Updates the B count for the A related to the given B.
    """
    if not kwargs.get('created', True) or kwargs.get('raw', False):
        return
    cursor = connection.cursor()
    cursor.execute(
        'UPDATE yourapp_a SET b_count = ('
            'SELECT COUNT(*) FROM yourapp_b '
            'WHERE yourapp_b.a_id = yourapp_a.id'
        ') '
        'WHERE id = %s', [instance.a_id])
    transaction.commit_unless_managed()

post_save.connect(update_b_count, sender=B)
post_delete.connect(update_b_count, sender=B)

rawDescription: Django models - how to filter number of ForeignKey objects


rawDescription: modified a given list inside a function

description: Modified a given list inside a function


code:
"""
one line summary

longer explanation

Args:
    a (int): parameter description

Returns:
    (tuple): tuple containing:

        servers(list) servers to use
        msg (str): logging message string
"""

rawDescription: Can sphinx napoleon document function returning multiple arguments?


code:
from collections import Counter
histogram = Counter(list_)

rawDescription: Seeing if values in a list are of equal value ~Python


code:
first = lambda n : n.split()[0]
first_names = map(first,names)

rawDescription: Best way to split strings

description: Split strings


code:
def reduce(self):
    gcd = findgcd(self.numerator, self.denominator)

rawDescription: How to invoke some method during the initialising process of an instance in Python

description: Invoke some method during the initialising process of an instance in Python


rawDescription: How to find the count of a word in a string?

description: Find the count of a word in a string


code: url =[urlparse(u).netloc for u in ifile]

rawDescription: Python .csv writer

description: Python .csv writer


code:
sent = ['this', 'is', 'a', 'foo', 'bar']
current_token = sent.pop(0) # i.e. 'this'
range(len(sent))

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


rawDescription: Combining two python scripts to run as one program


rawDescription: Order by dig-like rating in django

description: Order by dig-like rating in django


code:
# Modified from http://stackoverflow.com/a/13615802/2924421

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# C struct definitions
wintypes.ULONG_PTR = wintypes.WPARAM

SendInput = ctypes.windll.user32.SendInput

PUL = ctypes.POINTER(ctypes.c_ulong)

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

def KeyDown(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyUp(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    extra = ctypes.c_ulong(0)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag | KEYEVENTF_KEYUP, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyPress(unicodeKey):
    time.sleep(0.0001)
    KeyDown(unicodeKey)
    time.sleep(0.0001)
    KeyUp(unicodeKey)
    time.sleep(0.0001)

def GetKeyCode(unicodeKey):
    k = unicodeKey
    curKeyCode = 0
    if k == "up": curKeyCode = 0x26
    elif k == "down": curKeyCode = 0x28
    elif k == "left": curKeyCode = 0x25
    elif k == "right": curKeyCode = 0x27
    elif k == "home": curKeyCode = 0x24
    elif k == "end": curKeyCode = 0x23
    elif k == "insert": curKeyCode = 0x2D
    elif k == "pgup": curKeyCode = 0x21
    elif k == "pgdn": curKeyCode = 0x22
    elif k == "delete": curKeyCode = 0x2E
    elif k == "\n": curKeyCode = 0x0D

    if curKeyCode == 0:
        return 0, int(unicodeKey.encode("hex"), 16), KEYEVENTF_UNICODE
    else:
        return curKeyCode, 0, 0

rawDescription: Key echo in Python in separate thread doesn't display first key stroke


code:
#considering you have two lists 'list1' and 'list2'

intersection = set(list1).intersection(set(list2))

rawDescription: Intersection of two Unicode Arrays in Python


code:
import re
line = '...snake_perrot_cat_expression dog...'
re.findall(r'cat_(.*?)\s*dog', line)

rawDescription: Find expression delimited by known strings


code:
from itertools import izip
sample = [(1, 3, 1), (4, 5, 1), (8, 2, 1)]
sums = [sum(t) for t in izip(*sample)]
# sums == [13, 10, 3]

rawDescription: Two sums from one list

description: Two sums from one list


code:
import itertools
import operator
from functools import reduce

fs_cat = [
    {'cat': 66, 'count': 5, 'ids': [20, 21, 22, 23, 24]},
    {'cat': 27, 'count': 4, 'ids': [20, 22, 23, 24]},
    {'cat': 29, 'count': 2, 'ids': [20, 24]},
]

result = []
for n in range(1, len(fs_cat) + 1):  # 1, 2, ..., len(fs_cat)
    for xs in itertools.combinations(fs_cat, n):
        cat = '&'.join(map(str, sorted(x['cat'] for x in xs)))
        ids = sorted(reduce(operator.and_, (set(x['ids']) for x in xs)))
        result.append({'cat': cat, 'count': len(ids), 'ids': ids})

rawDescription: Difficulty getting the item count for the combinations of list of items from python dictionary