code:
y = int(yearString)
x = 0  # we will accumulate the sum in x
while y != 0:
    x += y % 10  # add one digit
    y //= 10  # discard one digit
    if y == 0 and x > 10:
        # We have pulled out all the digits from y, but x has
        # multiple digits.  Start over so we can sum the digits
        # from x.
        y = x
        x = 0

answer = x

rawDescription: python String interpolation vs another method

description: Python String interpolation vs another method


code:
from matplotlib import pyplot as plt
plt.style.use('ggplot')

rawDescription: ggplot styles in Python

description: Ggplot styles in Python


code:
for server, creds in enumerate(hosts):
    credentials = creds.get('admin') or creds.get('foobar')
    fill_admin_file(credentials)

rawDescription: python replace an element in a list

description: Python replace an element in a list


code:
"""

:var var1: var1 doc
:var var2: var2 doc
"""

rawDescription: Sphinx - autodata shows str.__doc__

description: Sphinx - autodata shows str.__doc__


rawDescription: Replace column separation of # with comma or tab


code:
# Get Cursor
@contextmanager
def get_cursor():
    con = db.getconn()
    try:
        yield con.cursor()
        con.commit()
    finally:
        db.putconn(con)

with get_cursor() as cursor:
    con.cursor.execute("INSERT INTO table (fields) VALUES (values) RETURNING id")
    id = cursor.fetchone()

rawDescription: How to use "INSERT" in psycopg2 connection pooling?

description: Use "INSERT" in psycopg2 connection pooling


code:
while len(used) > 7:
    used.popleft()

rawDescription: Display random choice (Python)

description: Display random choice (Python)


code:
from qserver import Qserver

myqserver = Qserver()
for msg in myqserver:
    # do something with message
    print(msg)
    if messageprocessok:
        myqserver.delete_current()

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


code:
a=data[0].strip()
b=map(int, data[1].strip().split())
c=int(data[2])
a
b
c

rawDescription: How does readline and readlines work in Python


rawDescription: order of parameters of function call of python

description: Order of parameters of function call of python


rawDescription: using python WeakSet to enable a callback functionality

description: Using python WeakSet to enable a callback functionality


rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code:
handler = WashHandler()
handler.main_wash()

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

description: Pass over a function if not called upon


code:
content = ''
file_obj = open('table.csv','r')
content = fle_obj.split(',')
print(content[column_number])

rawDescription: How to use first function's return value in second function?

description: Use first function's return value in second function


code:
with open(CACHE_FILENAME, 'r') as cache:
    cached = pickle.load(cache)

rawDescription: caching mysql query returned by Python script

description: Caching mysql query returned by Python script


code:
def is_prime(num):
    if num == 2:
        return True
    if not num & 1:
        return False
    return pow(2, num-1, num) == 1

rawDescription: Working with large primes in Python

description: Working with large primes in Python


rawDescription: Typecast "340" to int results in '34' losing the last zero


code: print ("the words in this synset are {0}".format(", ".join(word)))

rawDescription: Assigning variables in a loop in Python

description: Assigning variables in a loop in Python


rawDescription: How to set some xlim and ylim in Seaborn lmplot facetgrid

description: Set some xlim and ylim in Seaborn lmplot facetgrid


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

plt.figure(figsize=(1,1))

A = np.random.rand(60,60,3)

plt.imshow(A,
           cmap=plt.cm.gist_yarg,
           interpolation='nearest',
           aspect='equal',
           shape=A.shape)

plt.subplots_adjust(left=0,right=1,bottom=0,top=1)

plt.savefig('myfig.png',dpi=60)

rawDescription: Why is .imshow() producing images with more pixels than I have put in?


code: df['date'] += np.array(-df['date'].dt.second % 60, dtype='<m8[s]')

rawDescription: how to apply ceiling to pandas DateTime

description: Apply ceiling to pandas DateTime


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

rawDescription: Usage of Python 3 super()

description: Usage of Python 3 super()


code:
QPrinter(QPrinter.ScreenResolution)   #   96dpi,  752x992
QPrinter(QPrinter.PrinterResolution)  #   72dpi,  564x744
QPrinter(QPrinter.HighResolution)     # 1200dpi, 9400x12400

rawDescription: How to set QTextDocument margins and other properties (setHTML, print to pdf)?

description: Set QTextDocument margins and other properties (setHTML, print to pdf)


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


code:
import urllib.request

url = 'http://www.gutenberg.org/cache/epub/1342/pg1342.txt'
book = urllib.request.urlopen(url)
lines = book.readlines()
book.close()

reached_start = False
metadata = {}

for index, line in enumerate(lines):
    if line.startswith('***'):
        if not reached_start:
            reached_start = True
        else:
            break

    if not reached_start and ':' in line:
        key, _, value = line.partition(':')
        metadata[key.lower()] = value

rawDescription: Python: How to use %%% when parsing text


rawDescription: Python regex substitution using a dictionary


code:
newdict = {
    (key.year, key.month): sum(
        v[0] for k, v in olddict.iteritems()
        if (key.year, key.month) == (k.year, k.month)
    )
    for key in olddict
}

rawDescription: Modifying a dictionary with datetime as keys


code:
arr = np.memmap('mm', dtype='float32', mode='w+', shape=(1,10000000))
x = np.ones((1,10000000))
arr[:] = x
type(np.argsort(x))
type(np.argsort(arr))

rawDescription: Correct way to do operations on Memmapped arrays


code:
import heapq
import contextlib

with contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(fn)) for fn in inFiles]
    with open('output', 'w') as f:
        f.writelines(heapq.merge(*files))

rawDescription: how to join multiple sorted files in Python alphabetically?

description: Join multiple sorted files in Python alphabetically


code:
import codecs

data = f.read()
if data.startswith(codecs.BOM_UTF8):
    data = data[3:]

rawDescription: Reading UTF-8 file returns unexpected chars


code:
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.orderinglist import ordering_list

# ...

# :> convert relationship table to a mapped object
class AssetAssetDocument(Base):
    __tablename__ = 'asset_asset_document'

    asset_id = Column(ForeignKey(u'asset.id'), primary_key=True)
    asset_document_id = Column(ForeignKey(u'asset_document.id'), primary_key=True)
    documents_idx = Column(Integer)

    # :> define one-way relationship; will be used by association proxy
    document = relationship('AssetDocument')

class Asset(Base):
    __tablename__ = 'asset'

    id = Column(BigInteger, Sequence('seq_asset'), primary_key=True)
    version = Column(BigInteger, nullable=False)

    # :> define a relationship to a mapped relationship object
    # this one is able to use `ordering_list` factory
    _documents = relationship(
        AssetAssetDocument,
        order_by='AssetAssetDocument.documents_idx',
        collection_class=ordering_list('documents_idx'),
    )

    # :> define a desired relationship
    documents = association_proxy(
        '_documents', 'document',
        creator=lambda _d: AssetAssetDocument(document=_d),
    )

class AssetDocument(Base):
    __tablename__ = 'asset_document'

    id = Column(BigInteger, Sequence('seq_asset_document'), primary_key=True)
    version = Column(BigInteger, nullable=False)

rawDescription: SQLAlchemy Join Table with a field to order the rows


rawDescription: numpy take can't index using slice

description: Numpy take can't index using slice


code: sum(float(i) for i in s.split(','))

rawDescription: Summing elements of string in Python

description: Summing elements of string in Python


code: (s * 5).tolist()

rawDescription: How do I multiply each element in a list by a number?

description: Multiply each element in a list by a number


code:
{
    'Car': ['yellow', 'and', 'fast', 'Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'],
    'yellow': ['and', 'fast', 'Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'],
    'fast': ['Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'],
    'Toy': ['black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'],
    'black': ['and', 'fun', 'Person', 'tall', 'and', 'nice'],
    'fun': ['Person', 'tall', 'and', 'nice'],
    'Person': ['tall', 'and', 'nice'],
    'tall': ['and', 'nice'],
    'and': ['nice'],
    'nice': []
}

rawDescription: Function that creates a dictionary for words in a file


code:
from datetime import datetime
s = "03:00 PM - 05:00 PM"
[datetime.strptime(item, "%I:%M %p") for item in s.split(" - ")]

rawDescription: Python: Converting a string representing a time range to a struct_time object


code:
class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f

rawDescription: Can the staticmethod and classmethod decoraters be implemented in pure Python?


code:
sentence = input("Enter a sentence >>") #asking the user for an input
sentence_lower = sentence.lower() #making the sentence lower case
wordlist = [] #creating a empty list
sentencelist = sentence.split() #making the sentence into a list

with open ("part1.txt", "wt") as txtfile:
    for word in sentencelist: #for loop iterating over the sentence as a list
        if word not in wordlist:
            wordlist.append(word)
            txtfile.write(word +"\n")

poslist = [wordlist.index(word) for word in sentencelist]
print (poslist)

str1 = " ".join(str(x) for x in poslist)
with open ("part2.txt", "wt") as textfile:
    textfile.write (str1)

rawDescription: How can I create a list that is created using the indexes and items of two other lists?

description: Create a list that is created using the indexes and items of two other lists


code:
def go(it):
    for x in it:
        if x == 'b':
            yield [x] + list(go(it))
        else:
            yield x
            if x == 'c':
                break

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


rawDescription: Aggregate events with start and end times with Pandas


code: DT.datetime(2014, 12, 15, 0, 0) + DT.timedelta(days=1)

rawDescription: adding and subtracting from a date

description: Adding and subtracting from a date


rawDescription: cache.fetch in Django?

description: Cache.fetch in Django


rawDescription: geopy does not show correct output

description: Geopy does not show correct output


code:
def remove(self, id=None, value=None):
    for elem in self:
        if (id is not None and elem.id == id or
                value is not None and elem.value == value):
            super(Orders, self).remove(elem)
            break

rawDescription: Remove namedtuple from list based on value


code:
df
df.drop_duplicates()

rawDescription: drop duplicates in Python Pandas DataFrame not removing duplicates

description: Drop duplicates in Python Pandas DataFrame not removing duplicates


code:
df[0.5] = np.NaN
df.sort(axis=1).interpolate(axis=1)
df.sort(axis=1).interpolate(axis=1)[0.5]

rawDescription: Selection of a Series from pandas dataframe by interpolating column labels


code:
for ul in uls:
    for li in ul.findAll('li'):
        print(li)

rawDescription:
BeautifulSoup: How do I extract all the
s from a list of
s that contains some nested
s?


code:
from multiprocessing import Process, freeze_support
import multiprocessing
import time
from datetime import datetime as dt

def worker(nr):
    glock.acquire()
    print('started job: {} at {}'.format(nr, dt.now()))
    time.sleep(1)
    glock.release()
    print('ended   job: {} at {}'.format(nr, dt.now()))

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

def init(lock):
    global glock
    glock = lock

if __name__ == '__main__':
    multiprocessing.freeze_support()
    lock = multiprocessing.Manager().Lock()
    pool = multiprocessing.Pool(processes=3, initializer=init, initargs=(lock,))
    results = pool.map(worker, numbers)
    pool.close()
    pool.join()

rawDescription: Is it possible to start Pool processes sequentially?


code:
value1 = 4242
value2 = 4242
value1 == value2
value1 is value2
value3 = value1  # assignment
value1 == value3
value1 is value3

rawDescription: Pythonic way to check conditions

description: Pythonic way to check conditions


code:
import os
for root, dirs, names in os.walk(path):
    ...

rawDescription: python glob.glob - how to find a specific file (or a list of files) without knowing how deep it in in subdirs?

description: Python glob.glob - how to find a specific file (or a list of files) without knowing how deep it in in subdirs


rawDescription: Python - cleaning data to run apriori algorithm


code: IMAP4.fetch(message_set, 'UID')

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

description: Get 'Message-ID' using imaplib


rawDescription: Python: Save Excel File As-Is To Folder

description: Python: Save Excel File As-Is To Folder


rawDescription: Map a NumPy array of strings to integers


code:
import base64
import hashlib

future = datetime.datetime.now() + datetime.timedelta(minutes=5)
url = "/securedir/file.txt"
timestamp = str(time.mktime(future.timetuple()))
security = base64.b64encode(hashlib.md5( secret ).digest()).replace('+', '-').replace('/', '_').replace("=", "")
data = str(url) + "?st=" + str(security) + "&e=" + str(timestamp)

rawDescription: How to generate a nginx secure link in python

description: Generate a nginx secure link in python


code: b = -(1/tau)*log((1+L2*b)/kinf) # the old value of b gets lost here

rawDescription: Transcendental Equation

description: Transcendental Equation


code:
from itertools import product

dic = {}
for x, y, z in product(range(200), range(150), range(20)):
    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:
from decimal import *
getcontext().prec = 40
Decimal(1).exp()

rawDescription: Calculating e (base of the natural log) to high precision in Python?


code:
MIDDLEWARE_CLASSES = (
    'myproject.myapp.middleware.globalrequestmiddleware.GlobalRequestMiddleware',
    # ...
)

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


rawDescription: Speed the process of matching two columns using python


code: matching = [system for system in systems if 'foo' in system.mgmt_classes]

rawDescription: Overly complex list comprehension?

description: Overly complex list comprehension


code:
from matplotlib import colors
import matplotlib.pyplot as plt

alpha = 0.5

kwargs = dict(edgecolors='none', s=3900, marker='s')
for i, color in enumerate(['red', 'blue', 'green']):
    rgb = colors.colorConverter.to_rgb(color)
    rgb_new = make_rgb_transparent(rgb, (1, 1, 1), alpha)
    print(color, rgb, rgb_new)
    plt.scatter([i], [0], color=color, **kwargs)
    plt.scatter([i], [1], color=color, alpha=alpha, **kwargs)
    plt.scatter([i], [2], color=rgb_new, **kwargs)

rawDescription: calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib

description: Calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib


code: return float("".join(l))

rawDescription: convert array of tuples to 2 dimensional array

description: Convert array of tuples to 2 dimensional array


code:
from rest_framework.renderers import JSONRenderer
from polls.models import Order
from polls.serializers import OrderSerializer

bunch = OrderSerializer(Order.objects.all(), many=True)

#this will output "lines" part of desired output
JSONRenderer().render(bunch.data)

#next to get columns, or i say headers
headers = bunch.data[0].keys()
# headers = ['doc','order','nothing']
# !note will fail if bunch.data is empty

headers_prepared = map (lambda x: {'data': x} , headers)
# headers_prepared = [{'data': 'doc'}, {'data': 'order'}, {'data': 'nothing'}]

import collections # need to use OrderedDict to store in our sequence
ordered_all = ( ('columns', headers_prepared), ('lines', bunch.data) )

#finally desired output
JSONRenderer().render( collections.OrderedDict(ordered_all)   )

#all code and output tested on my dummy data

rawDescription: Importing data to a particular model

description: Importing data to a particular model


code:
import dis
dis.dis(f1)
dis.dis(f2)
dis.dis(f3)

rawDescription: What do backticks mean to the python interpreter: `num`


rawDescription: Print lists Advanced

description: Print lists Advanced


code: dct[item].get(key, '')

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


code: new_list = [foo for foo in foos if foo.location == 2]

rawDescription: How to map 2 lists with comparison in python

description: Map 2 lists with comparison in python


code:
height,direction,speed
1,2,3
3,2,1

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


code: used/total

rawDescription: Python system resources enumeration

description: Python system resources enumeration


code:
import logging
import requests

logging.basicConfig(level=logging.DEBUG)
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
s.get('http://httpbin.org/cookies/set/anothercookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)

rawDescription: Python requests speed up using keep-alive


code:
import binascii

binary = binascii.unhexlify(text)

rawDescription: Converting string to raw bytes

description: Converting string to raw bytes


rawDescription: Extract only the portion of a string between two regex patterns


code:
import marshal
import pickle

marshaled_bytecode = marshal.dumps(your_function.func_code)
# In this process, other function things are lost, so they have to be sent separated.
pickled_name = pickle.dumps(your_function.func_name)
pickled_arguments = pickle.dumps(your_function.func_defaults)
pickled_closure = pickle.dumps(your_function.func_closure)
# Send the marshaled bytecode and the other function things through a socket (they are byte strings).
send_through_a_socket((marshaled_bytecode, pickled_name, pickled_arguments, pickled_closure))

rawDescription: We need to pickle any sort of callable

description: We need to pickle any sort of callable


code:
def clear(self):
    self.RobotMap = self.sizeY * [self.sizeY * [self.EmptyValue]]

rawDescription: python script speed improvements

description: Python script speed improvements


code:
['the thing', 'normal']
['stuff', 'bold']
['is very important for various reasons, notably', 'normal']
['other things', 'bold']
['.', 'normal']

rawDescription: ElementTree text mixed with tags

description: ElementTree text mixed with tags


code:
i = iter(a)
b = dict(zip(i, i))

rawDescription: Convert a list to a dictionary in Python


code:
day2 = np.random.randint(255, size=day1.shape)
day3 = np.random.randint(255, size=day1.shape)

rawDescription: How to merge multiple arrays in python?

description: Merge multiple arrays in python


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

rawDescription: Return a list of missing values?

description: Return a list of missing values


code:
img
img.transpose(2,0,1).reshape(3,-1)

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

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


code: somedict = {x: 1 for x in somelist}

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


code:
def call(*args, **kwargs):
    pass
call(*return_args(), **kwargs)

rawDescription: Using variables from a returned function as arguments in another function


code:
response = connection.getresponse()
response.read()

rawDescription: Python http.client json request and response. How?


rawDescription: Pythonic insertion of variable number of arguments into a string


rawDescription: Filtering permutations of strings

description: Filtering permutations of strings


code:
class FileProxy(object):
    """Proxy to a remote file over zmq"""
    def __init__(self, url):
        self.socket = zmq.Context.instance().socket(zmq.PUSH)
        self.socket.connect(url)

    def write(self, chunk):
        """write a chunk of bytes to the remote file"""
        self.socket.send(chunk)

rawDescription: Python: write to single file from multiple processes (ZMQ)


code:
matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
    for i in k:
        dup.append(i)

print (max(dup), min(dup))

rawDescription: Find maximum and minimum value of a matrix


code:
with open("file.txt", "r") as myfile:
    for line in myfile:
        if "Hello" in line:
            break
    for line in myfile:
        for word in mylist:
            if word in line:
                print(word + "found")

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


rawDescription: validate rows before computing values using python/pandas DataFrame

description: Validate rows before computing values using python/pandas DataFrame


code:
from scipy.interpolate import splev, splint, splrep
tck = splrep(x, y, s=0)
splint(0, 1, tck)

rawDescription: Integral function of a interpolating polynomial in python


rawDescription: How to make equivalency in Python?

description: Make equivalency in Python


code: int.bit_length() + 2

rawDescription: Python character length of a binary value


code:
def combinations(input_list, acc='', from_idx=0):

    if len(input_list) <= from_idx:
        yield acc
        return

    next_val = input_list[from_idx]

    yield from combinations(input_list, acc, from_idx + 1)
    acc += next_val
    yield from combinations(input_list, acc, from_idx + 1)

rawDescription: What's the most memory efficient way to generate the combinations of a set in python?


code:
import numpy as np

a = np.empty(100)
b = np.arange(1, 4, 0.25)
ind = np.arange(len(a))
np.put(a, ind, b)
print(a)

rawDescription: Python: How do I fill an array with a range of numbers?


code:
import itertools

# Make groups based on the first two elements.
groups = itertools.groupby(a, key=lambda x: (x[0], x[1]))

# Iterate over the groups collecting the third elements.
result = []
for group in groups:
    this_set = []
    print(group)
    for i in group[1]:
        this_set.append(i[2])
    result.append([i[0], i[1], np.mean(this_set)])

rawDescription: Find average in a 2D array

description: Find average in a 2D array


code: allnouns = [x for x in wn.all_synsets('n')]

rawDescription: Extract word from a list of synsets in NLTK for Python


code:
subq = session.query(A.a_property_special).where(A.id == B.a_id).correlate(B).as_scalar()
session.query(B).filter(subq > 3.0)

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


code: ''.join(n for n in phone_str if n.isdigit())

rawDescription: Convert string (without any separator) to list


code:
user.social_auth.get(
    provider='steam'
).extra_data.player.avatarfull

rawDescription: How do I pull information from a field in the admin panel?

description: Pull information from a field in the admin panel


code:
import itertools

zipped = itertools.izip(*list2)
result = [min(zipped.next()) for _ in range(3)] + [max(zipped.next()) for _ in range(3)]

rawDescription: Compare elements of a list of lists and return a list


code:
def sumColumns1(columnfile):
    import csv
    with open(columnfile) as csvfile:
        r = csv.reader(csvfile)
        names = next(r)
        Int = lambda x: 0 if x=='' else int(x)
        sums  = reduce(lambda x,y: [ Int(a)+Int(b) for a,b in zip(x,y) ], r)
        return dict(zip(names,sums))

rawDescription: python 3: Adding .csv column sums in to dictionaries with header keys

description: Python 3: Adding .csv column sums in to dictionaries with header keys


code:
9 == 4 * 2 + 1

9 // 4 == 2    # integer divison
9 % 4 == 1     # remainder

rawDescription: Can someone please explain to me the way to calculate the number of bills and coins of change in python?


code:
import tkinter.messagebox

answer=tkinter.messagebox.askquestion('Question','what is your name?')
if answer=='yes':
    print('I am King')

rawDescription: tKinter dialog button not responding

description: TKinter dialog button not responding


rawDescription: Create Dictionary Of Lists from List of Dictionaries in Python


Samsung Galaxy Z1 (Black)

salient_feature:
Screen: 10.16 cm (4")
Camera: 3.1 MP Rear/VGA Front
RAM: 768 MB
ROM: 4 GB
Dual-core 1.2 GHz Cortex-A7
Battery: 1500 mAh/Li-Ion

url_type: product

vertical_label: Mobile

merchant_name: SMARTBUY

brand: Samsung

tag: +5% Cashback

product_tag: +5% Cashback

rawDescription: Scraping hidden elements using BeautifulSoup


rawDescription: Inequality Filters on a date and a number


code:
import re

conf = '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"'
regex = ''.join(
    '(?P<' + g + '>.*?)' if g else re.escape(c)
    for g, c in re.findall(r'\$(\w+)|(.)', conf))

rawDescription: How to generate regex to match access.log acording to its format config?

description: Generate regex to match access.log acording to its format config


code:
countdf = df.groupby('VID').count()
result = df.loc[df['VID'].isin(countdf[countdf['value'] > 3].index)]

rawDescription: Keeping rows in Pandas where the same ID appears more than n times and convert to list per ID


code:
import unittest

class ConvertImageTest(unittest.TestCase):

    def test_convert_image(self):

        # Test version of check_call to do the assertion
        def assert_check_call(args):
            expected = ['convert', '/tmp/myimage.png', '-quality', 100, '/tmp/myimage.jpg']
            self.assertEquals(expected, args)

        # Replace check_call with our test version
        my.module.check_call = assert_check_call

        # Perform the test
        convert_image('/tmp/myimage.png')

rawDescription: How would you test this function?

description: How would you test this function


code:
def create_guest(self):
    db.session.add(self)
    db.session.commit()
    self.guest_id = 'guest{}'.format(self.id)

rawDescription: Generate user ids in a sequence using sqlalchemy in sqllite databse.


code:
df.apply(pd.to_numeric, errors='coerce')
df.apply(pd.to_numeric, errors='coerce').fillna(0)
np.linalg.eigvals(df.apply(pd.to_numeric, errors='coerce').fillna(0))

rawDescription: Find the eigenvalues of a subset of Dataframe in Python


rawDescription: Python format output in concise manner

description: Python format output in concise manner


code:
result = analyse(log)
v = result['values']

rawDescription: Best approach for extensible return object in python


code:
class Node(object):
    """Rather silly example of a nested node.

    The children are actually stored in a list,
    so the generator is actually not needed.

    But simply assume that returning a children
    requires a lazy evaluation.

    """
    counter = 0 # Counter for node identification

    def __init__(self):
        self.children = [] # children list
        self.node_number = Node.counter # identifies the node
        Node.counter += 1

    def __repr__(self):
        return 'I am node #%d' % self.node_number

    def get_children_generator(self):
        """Returns a generator over children"""
        return VerboseListIterator(self.children, self)

def traverse_nodes(start_node):
    """Traverses nodes in breadth first manner.

    First returns the start node.

    For simplicity we require that
    there are no cycles in the data structure,
    i.e. we are dealing with a simple tree.

    """
    node_queue = iter([start_node])
    while True:
        try:
            next_node = next(node_queue)
            yield next_node

            # Next get the children
            child_gen = next_node.get_children_generator()

            # The next code line is the one I am worried about
            # is it a good idea to make a chain of chains?
            node_queue = chain(node_queue, child_gen)
        except StopIteration:
            # There are no more nodes
            break

rawDescription: Chaining of Python generators to traverse a nested data structure; best practices


rawDescription: grouping lines from a file with regular expression

description: Grouping lines from a file with regular expression


code:
try:
    import xmlrpclib  # Python 2
except ImportError:
    import xmlrpc.client as xmlrpclib  # Python 3

pypi = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')

packages = pypi.browse([
    "Topic :: Software Development",
    "Topic :: Scientific/Engineering",
])

rawDescription: Searching PyPI by topic

description: Searching PyPI by topic


code:
class NewUserAdmin(UserAdmin):
    form = NewUserChangeForm
    add_form = NewUserCreationForm

    list_display = ('username', 'newField', 'first_name', 'last_name', 'last_login',)       # few example fields and new one: newField
    fieldsets = (
        (None, {'fields': ('username', 'email', 'first_name', 'last_name', 'newField', 'last_login', 'is_staff')}), # few example fields and new one: newField
)

    add_fieldsets = (
        (None, {
        'classes': ('wide',),
        'fields': ('username', 'newField', 'password1', 'password2')}   # here are fields you want to have in django-admin AddUser view
    ),           # one of the most important place above
)

admin.site.register(NewUser, NewUserAdmin)

rawDescription: New field in django-admin Add User

description: New field in django-admin Add User


code:
data = dset['sea_ice_cover'][:]  # data is a numpy array
data[data < 0] = -1

rawDescription: Python : Replacing Values in netcdf file using netCDF4


code:
input = (0.1, 0.2, 0.7)
list(build_ranges(input))

rawDescription: Building ranges using python set-builder notation


code:
a = ['spam', 'eggs', 100, 1234]
[item if item != 'spam' else [item, 'devon'] for item in a]

rawDescription: Python list manipulation: Add an item to a string element to make it a 2 item list


code:
s = "The boy is about to win"
''.join(c for i, c in enumerate(s) if not (c in 'aeiou' and i>1 and s[i-1].isalpha()))

rawDescription: Remove vowels except if it the starting of the word


code:
# Scanning the entire keyspace to find biggest keys as well as
# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec
# per 100 SCAN commands (not usually needed).

rawDescription: Find out largest string value size for keys in Redis database


code:
self.StatusTextVar.set("Success")
self.StatusTextVar.set("Wrong input. Retry")

rawDescription: Python 2.7: updating Tkinter Label widget content


code:
def dispatch(self):
    # Get a session store for this request.
    self.session_store = sessions.get_store(request=self.request)

    if not self.session['username'] and self.request.get('path') != '/login':
        return redirect('/login')

rawDescription: Creating restricted pages in google app engine


rawDescription: List polymorphic inheritance choices and create an instance based on that choice


code:
# create aliases for each pair of relations that must exist
AB = aliased(Following)
BA = aliased(Following)
AC = aliased(Following)
CB = aliased(Following)
CA = aliased(Following)

triads = (
    session.query(
        AB.follower_id.label("a_id"),
        AB.followee_id.label("b_id"),
        AC.followee_id.label("c_id"),
    )
    # .select_from(AB)  # @note: this is implied, so not really required
    .join(BA, and_(AB.followee_id == BA.follower_id,
                   AB.follower_id == BA.followee_id))
    .join(AC, AB.follower_id == AC.follower_id)
    .join(CB, and_(AC.followee_id == CB.follower_id,
                   AB.followee_id == CB.followee_id))
    # exclude C following A using LEFT JOIN + WHERE IS NULL)
    .outerjoin(CA, and_(AC.followee_id == CA.follower_id,
                        AC.follower_id == CA.followee_id))
    .filter(CA.follower_id == None)
)

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

rawDescription: SQLAlchemy: directed relationships within triads


rawDescription: Writing files only once

description: Writing files only once


code:
if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Tkinter adding line number to text widget


rawDescription: Python adding values in Tuples

description: Python adding values in Tuples


code:
with infile:
    obj = json.load(infile)
with outfile:
    json.dump(obj, outfile, sort_keys=True,
              indent=4, separators=(',', ': '))

rawDescription: How to execute a python module (python -m json.tool) programatically?

description: Execute a python module (python -m json.tool) programatically


code: listbox.insert(END, i, dic[i][0], dic[i][1], dic[i][2])

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


code:
import sys

def palindrome(limit):
    for i in range(limit):
        istring = str(i*i)
        if istring == istring[::-1]:
            print(istring,end=" ")
    print()

palindrome(int(sys.argv[1]))

rawDescription: python - print squares of numbers which are palindromes : improve efficiency

description: Python - print squares of numbers which are palindromes : improve efficiency


code: print('This object is pretty: {:pretty}'.format(obj))

rawDescription: what is the Pythonic way to implement a __str__ method with different format options?

description: What is the Pythonic way to implement a __str__ method with different format options


rawDescription: Python - Combine number of dictionaries with conditional concatenation


code:
OUTPUT
2 , 2

rawDescription: Quiver vector from high value toward low value


code:
images = [wood, brick, wheat, image4, image5, image6, image7]

for i, image in enumerate(images):
    screen.blit(image, spots[i])

rawDescription: How can i use the value of one variable to call another in python?

description: Use the value of one variable to call another in python


rawDescription: fast way to transpose and concat csv files in python?

description: Fast way to transpose and concat csv files in python


code:
import sys

image.write(phone_number, sys.stdout)

rawDescription: HTML set an image's content to content generated by a server-side script


code:
def testFunc(characterObject):
    #Print the value of the "player" key
    print(characterObject["player"])
    #call some other function
    otherFunc(characterObject["arrow"])

testFunc(characterObject)

rawDescription: Python - Use object as parameter to function


code:
import cmd
cmd.Cmd().cmdloop()

rawDescription: Sending curses application's output to tty1


code:
results = (evaluate(polynomial,index) for index in count(0))
pairsToCompare = itertools.izip(results, terms)
mismatches = (pair for pair in pairsToCompare if pair[0] != pair[1])

first_mismatch = mismatches.next()

rawDescription: Python converting nested loops to simple line


code:
funcList = [lambda m: m[0] < 2,
            lambda m: m[1] < 2,
            lambda m: m[2] < 2]

rawDescription: Split data into sub cubes in numpy

description: Split data into sub cubes in numpy


code: text = re.sub("\w*", " ", text)

rawDescription: Delete HTML Tags from string Python

description: Delete HTML Tags from string Python


rawDescription: how to set bounds for the x-axis in one figure containing multiple matplotlib histograms and create just one column of graphs?

description: Set bounds for the x-axis in one figure containing multiple matplotlib histograms and create just one column of graphs


rawDescription: In Python NumPy what is a dimension and axis?


code:
import numpy
import cv2

contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)]

drawing = numpy.zeros([100, 100],numpy.uint8)
for cnt in contours:
    cv2.drawContours(drawing,[cnt],0,(255,255,255),2)

cv2.imshow('output',drawing)
cv2.waitKey(0)

rawDescription: Creating your own contour in opencv using python


code: form = SomeForm(bar)

rawDescription: Flask forms. How to make variable from views visible in forms.py


code: map(''.join, zip(*[iter(myl)]*2))

rawDescription: List Slicing python

description: List Slicing python


code: import t

rawDescription: How do I iterate over all imported functions

description: Iterate over all imported functions


code: groups = MembershipSerializer(source='membership_set', many=True)

rawDescription: Include intermediary (through model) in responses in Django Rest Framework


code:
B.objects.create(a=some_a)
if some_a.hidden and some_a.b_set.count() > 1:
    A.objects.filter(id=some_a.id).update(hidden=False)

...

some_a = b.a
some_b.delete()
if not some_a.hidden and some_a.b_set.count() < 2:
    A.objects.filter(id=some_a.id).update(hidden=True)

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


code:
minus_from_10 = functools.partial(operator.sub, 10)
minus_from_10(7)

rawDescription: Python callback function placeholders?

description: Python callback function placeholders


code:
class MyClass(object):
    Popen = staticmethod(subprocess.Popen)
    def call(self):
        return self.Popen(...).communicate(...)

rawDescription: How to do dependency injection python-way?

description: Do dependency injection python-way


code:
from scipy.sparse import coo_matrix
c = coo_matrix((values, (row, col)), shape=(row.max()+1, col.max()+1))
c
c.A

rawDescription: Convert row-column-value data to an array - numpy


rawDescription: lxml and xml namespaces - Using find and findall to get XML Tag Value

description: Lxml and xml namespaces - Using find and findall to get XML Tag Value


code:
def reduce(self):
    gcd = self.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


code:
from curses import wrapper
def main(stdscr):
    stdscr.clear()  # clear above line.
    for r, c in zip(range(5,10),range(10, 20)) :
      stdscr.addstr(r, c, '#')
    stdscr.addstr(11, 0, 'Press Key to exit: ')
    stdscr.refresh()
    stdscr.getkey()

wrapper(main)

rawDescription: What's the short way to add same symbol at the specified place in ncurses?


rawDescription: simplest mergesort implementation in Python, having type troubles

description: Simplest mergesort implementation in Python, having type troubles


code:
n = 3
list(combinations(range(len(sent)), n-1))

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
import sys
import os
import re
import shutil

tf = open('tmp', 'a+')

with open('test1.txt') as f:
    for line in f.readlines():
        build = re.sub ('This is.*','This is a second string',line)
        tf.write(build)
tf.close()
f.close()
shutil.copy('tmp', 'test1.txt')
os.remove('tmp')

rawDescription: Replace string with wildcard in a .txt file with Python


code:
Dog.intro(dizzy)
Animal.intro(dizzy)

rawDescription: Call a method on the parent class of an initialized object


rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code:
import numpy as np
import scipy
a=np.array([1,1,1,1,1])
scipy.integrate.simps(a)
scipy.integrate.simps(a,np.array([0,10,20,30,40]))

rawDescription: Using scipy to perform discrete integration of the sample


rawDescription: Remove letter duplicates that are in a row


code:
name: mike
age: 26

done

rawDescription: Searching Python Dictionary by key value is returning multiple, consecutive results, not just 1


code:
#!/usr/bin/env python3
import os
import sys
from subprocess import check_output

script_path = os.path.join(get_script_dir(), 'a.py')
output = check_output([sys.executable, script_path],
                      input='\n'.join(['query 1', 'query 2']),
                      universal_newlines=True)

rawDescription: Call python script with input with in a python script using subprocess


code:
computer = System(1, 1, '192.168.100.101')
System.ping_system('192.160.100.101') # works
computer.type_of_system # "Base system"
computer.description # "Site 1, Device 1 @ 192.168.100.101"
new_description = [1, 2, '192.168.100.102']
computer.description = new_description
# invokes description.setter
computer._devicenum # is 2 after the setter does its magic.

rawDescription: python classes getters and setters static method and class method

description: Python classes getters and setters static method and class method


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

rawDescription: Two sums from one list

description: Two sums from one list


code:
rows = json.loads(x)
fieldnames = ['longitude', 'latitude']
with open('test.csv', 'wb+') as f:
    dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
    dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
    dict_writer.writerows(rows)

rawDescription: Convert JSON to CSV using Python (Idle)

description: Convert JSON to CSV using Python (Idle)


code:
s.get_value()
g(1)
s.get_value()
g(10)
s.get_value()

rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


rawDescription: Organizing code for Testing with Constants from a Configuration File


code: enroute(triangle)

rawDescription: Finding the Maximum Route in a given input


rawDescription: Django MPTT get related objects

description: Django MPTT get related objects


code:
def gen(maxlen):
    pattern = "{{:0{}b}}".format(maxlen)
    for i in range(0, 2**maxlen, 2):
        if i ^ i*2 == i*3:
            yield pattern.format(i)

rawDescription: Generate all strings of length X that end with '0' and have no adjacent '1's


code:
import dill
def foo(x):
  return x*x

class Blah(object):
  def bar(self, x):
    self.x = (lambda x:foo(x)+self.x)(x)
  x = 2

b = Blah()
b.x
b.bar(3)
b.x
# the one line
dill.dump_session('foo.pkl')

rawDescription: Pickle python class instance plus definition


code:
plt.legend([p1,p2,p3,(p5,p4)],["Primary", "Secondary", "XYZ", "This Work"],
           handler_map={p4:HandlerLine2D(numpoints=2), p5:HandlerLine2D(numpoints=1)})

rawDescription: Two unique marker symbols for one legend


code: np.add.reduceat(a, [0, 25, 50], axis=0)

rawDescription: NumPy sum along disjoint indices

description: NumPy sum along disjoint indices


code:
with open('input.txt') as f:
    lines = f.readlines()
f.close()

rawDescription: Script/regex for log file editing

description: Script/regex for log file editing


code:
def system_execute(self, command, path, out_file):
    params_list = command.split(' ')
    file_path = os.path.join(path, out_file)
    f = open(file_path, "w")
    sp = subprocess.Popen(params_list, stdout=f)
    sp.wait()
    f.close()

rawDescription: Python subprocess.Popen and asynchronous output


code:
def loadmodule(modpath, modname=''):

    if not modpath.endswith('.py'):
        modpath += '.py'

    # generate a random name for the module
    if not modname:
        modpathbase = os.path.basename(modpath)
        modname, _ = os.path.splitext(modpathbase)

    version = (sys.version_info[0], sys.version_info[1])

    if version < (3, 3):
        mod, e = loadmodule2(modpath, modname)
    else:
        mod, e = loadmodule3(modpath, modname)

    return mod, e

def loadmodule2(modpath, modname):
    import imp

    try:
        mod = imp.load_source(modname, modpath)
    except Exception as e:
        return (None, e)

    return (mod, None)

def loadmodule3(modpath, modname):
    import importlib.machinery

    try:
        loader = importlib.machinery.SourceFileLoader(modname, modpath)
        mod = loader.load_module()
    except Exception as e:
        return (None, e)

    return (mod, None)

rawDescription: Extend the functionality of a compiled Python script


code:
char_list = [''.join(set((a, b))) for a, b in zip('apfelbaum', 'appletree')]
char_list

rawDescription: Add specific columns to a single row list (might be a little basic)


code:
import cherrypy

from webapp1 import WebApp1
from webapp2 import WebApp2

cherrypy.tree.mount(WebApp1, '/WebApp1')
cherrypy.tree.mount(WebApp2, '/WebApp2')
cherrypy.engine.start()
cherrypy.engine.block()

rawDescription: Apache mod_rewrite with multiple web apps


code:
outfile1 = open(r'C:\pythontmp\numpyArray.pkl', 'w+b')
pickle.dump(numpyArray.tolist(), outfile1)
outfile1.close()

rawDescription: Is there an alternative to numpy.save(file, arr) that will work with pypy?


code:
@property
def X(self):
    return self.B
@x.setter
def X(self, value):
    self.B = value
@x.deleter
def X(self):
    del self.B

rawDescription: Two classes with a structurally identical method but one differently named variable


code: derefrenced_spams = prefetch_refprops(Spams, models.Spam.eggs)

rawDescription: List of References in Google App Engine for Python


rawDescription: sorting integers in lists into bins

description: Sorting integers in lists into bins


code:
def collide_widget(self, wid):
    if self.right < wid.x:
        return False
    if self.x > wid.right:
        return False
    if self.top < wid.y:
        return False
    if self.y > wid.top:
        return False
    return True

rawDescription: collide_widget with negative size

description: Collide_widget with negative size


code: Region = ["Marrakech","London"]

rawDescription: How to Crawl Multiple pages/cities from a website (BeautifulSoup,Requests,Python3)


rawDescription: Python - Remove accents from all files in folder


code:
def foo(**kwargs):
    pass

rawDescription: Method signature for variable length of arguments


code:
def load_sample_movies():

    base_dir = join(dirname(__file__), 'data/')

    #Read data
    data_m = np.loadtxt(base_dir + 'sample_movies.csv',
            delimiter=';', dtype=str)
    item_ids = []
    user_ids = []
    data_songs = {}
    for user_id, item_id, rating in data_m:
        if user_id not in user_ids:
            user_ids.append(user_id)
        if item_id not in item_ids:
            item_ids.append(item_id)
        u_ix = user_ids.index(user_id) + 1
        i_ix = item_ids.index(item_id) + 1
        data_songs.setdefault(u_ix, {})
        data_songs[u_ix][i_ix] = float(rating)

    data_t = []
    for no, item_id in enumerate(item_ids):
        data_t.append((no + 1, item_id))
    data_titles = dict(data_t)

    data_u = []
    for no, user_id in enumerate(user_ids):
        data_u.append((no + 1, user_id))
    data_users = dict(data_u)

    fdescr = open(dirname(__file__) + '/descr/sample_movies.rst')

    return Bunch(data=data_songs, item_ids=data_titles,
                 user_ids=data_users, DESCR=fdescr.read())

rawDescription: How to load the datset using scikits

description: Load the datset using scikits


code:
sentence = "foo bar @match don't match @somereallylongnamehere @success;"
re.findall('(@[a-zA-Z0-9_]{1,15}[:;, ])', sentence)

rawDescription: Matching @user with regex

description: Matching @user with regex


code:
import csv
source= csv.reader( open("some file","rb") )
dest= csv.writer( open("another file","wb") )
for row in source:
    result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
    dest.writerow( result )

rawDescription: How can I merge fields in a CSV string using Python?

description: Merge fields in a CSV string using Python


rawDescription: Why list created by code does not include values greater than 99,999 (Python)


code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from numpy.ma import masked_array
import numpy as np

df = pd.read_clipboard() # just copied your example

# define masked arrays to mask all but the given column
c1 = masked_array(df, mask=(np.ones_like(df)*(df.values[0]!=df.values[0][0])))
c2 = masked_array(df, mask=(np.ones_like(df)*(df.values[0]!=df.values[0][1])))
c3 = masked_array(df, mask=(np.ones_like(df)*(df.values[0]!=df.values[0][2])))

fig,ax = plt.subplots()
ax.matshow(c1,cmap=cm.Reds) # You can change the colormap here
ax.matshow(c2,cmap=cm.Greens)
ax.matshow(c3,cmap=cm.Blues)
plt.xticks(range(3), df.columns)
plt.yticks(range(4), df.index)

rawDescription: Plotting of 2D data : heatmap with different colormaps


code:
activity_set = Activity.objects.extra(
  tables=['myapp_user'],
  where=[
    "myapp_activity.user_id=myapp_user.user_id",
    "myapp_activity.date - myapp_user.install_time > '2 days'"
    ])

rawDescription: Check ID across tables using Django Queryset


rawDescription: How to aggregate data in django?

description: Aggregate data in django


code:
listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}]
[{r["section"]: r["title"]} for r in listofdict]

rawDescription: Difference between Python dictionary comprehension and loop


code:
def setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

rawDescription: Access python nested dictionary items via a list of keys


code:
config.add_route('name_with_optional', '/required/{optional}/{str}')
config.add_route('name', '/required/{str}')

rawDescription: Pyramid: Routing schemas and restraints

description: Pyramid: Routing schemas and restraints


code:
months=['January', 'February', 'March', 'April', 'May' 'June', 'July', 'August', 'September', 'October', 'Novemeber', 'December']
pat=re.compile("|".join([r"\b{}\b".format(m) for m in months]), re.M)

rawDescription: Regular expressions from a list previously specified


code:
import lxml.etree as ET
tree = ET.parse(tempXmlExportPath)
root = tree.getroot()

rawDescription: updating metadata for feature classes programatically using arcpy

description: Updating metadata for feature classes programatically using arcpy


rawDescription: noob python regex all [A-Za-z] not inside '( )'

description: Noob python regex all [A-Za-z] not inside '( )'


rawDescription: create and insert randomly duplicates

description: Create and insert randomly duplicates


rawDescription: First, Last, Next ordering in exporting CSV, Python


code:
results = {}
for name, pos, cost, pts in listOfPlayers:
    if pos in results:
        #position already filled
        continue
    results[pos] = (name, pos, cost, pts)

rawDescription: Python Sorting lists by value

description: Python Sorting lists by value


code: '%f' % your_var

rawDescription: supress scientific notation when writing python floats to files

description: Supress scientific notation when writing python floats to files


code:
class Tenant(models.Model):
    name = models.CharField(max_length=100)

class Room(models.Model):
    owner = models.ForeignKey(User, related_name='owns')
    maintainer = models.ForeignKey(User, related_name='maintains')
    tenant = models.ForeignKey(Tenant)

rawDescription: How to perform queries in Django following double-join relationships (or: How to get around Django's restrictions on ManyToMany "through" models?)

description: Perform queries in Django following double-join relationships (or: How to get around Django's restrictions on ManyToMany "through" models?)


code: [json.loads(item) for item in strdata]

rawDescription: Not about to deserialize json kept as string in Python using json.load


rawDescription: Python script executes another script and resumes after second script completes its job


code:
from __future__ import print_function
import matplotlib
import numpy as np

matplotlib.use("TkAgg")

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation

import Tkinter as tk
import ttk

x = np.linspace(0, 2*np.pi, 1024)

class TransientAnalysis(tk.Tk):

    pages = ((1, 'Switch to "-"', '-', '+', 'orange'),
             (-1, 'Switch to "+"', '+', '-', 'olive'))

    def __init__(self, *args, **kwargs):
        self._running_anim = None
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, "Transient Analysis GUI: v1.0")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for (direction, text, other_key, my_key, color) in self.pages:

            frame = MovingSinGraphPage(direction, text, other_key,
                                       my_key, color,
                                       container, self)

            self.frames[my_key] = frame

            frame.grid(row=0, column=0, sticky="nsew")

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()
        frame.canvas.draw_idle()

class MovingSinGraphPage(tk.Frame):

    def __init__(self, move_dir, text, other_key, my_key,
                 color, parent, controller):
        self._sgn = np.sign(move_dir)

        tk.Frame.__init__(self, parent)

        button1 = ttk.Button(self, text=text,
                             command=(
                                 lambda: controller.show_frame(other_key)))
        button1.grid(row=1, column=0, pady=20, padx=10, sticky='w')

        # make mpl objects
        a = Figure(figsize=(4, 4))
        plot_a = a.add_subplot(111)
        # set up the axes limits and title
        plot_a.set_title(my_key)
        plot_a.set_xlim([0, 2*np.pi])
        plot_a.set_ylim([-1, 1])
        # make and stash the plot artist
        lna, = plot_a.plot([], [], color=color, lw=5)
        self._line = lna

        # make the canvas to integrate with Tk
        canvasA = FigureCanvasTkAgg(a, self)
        canvasA.show()
        canvasA.get_tk_widget().grid(
            row=1, column=1, pady=20, padx=10, sticky='nsew')

        # stash the canvas so that we can use it above to ensure a re-draw
        # when we switch to this page
        self.canvas = canvasA
        # create and save the animation
        self.anim = animation.FuncAnimation(a, self.update,
                                            interval=100)

    def update(self, i):
        self._line.set_xdata(x)
        self._line.set_ydata(np.sin(x + self._sgn * i * np.pi / 10))

app = TransientAnalysis()
app.geometry("800x600")

app.mainloop()

rawDescription: Using FigureCanvasTkAgg in two TKinter "pages" with python


code:
import __builtin__
import collections
import contextlib
import sys

@contextlib.contextmanager
def replace_import_hook(new_import_hook):
    original_import = __builtin__.__import__
    __builtin__.__import__ = new_import_hook
    yield original_import
    __builtin__.__import__ = original_import

def clone_modules(patches, additional_module_names=None):
    """Import new instances of a set of modules with some objects replaced.

    Arguments:
      patches - a dictionary mapping `full.module.name.symbol` to the new object.
      additional_module_names - a list of the additional modules you want new instances of, without
          replacing any objects in them.

    Returns:
      A dictionary mapping module names to the new patched module instances.
    """

    def import_hook(module_name, *args):
        result = original_import(module_name, *args)
        if module_name not in old_modules or module_name in new_modules:
            return result
        # The semantics for the return value of __import__() are a bit weird, so we need some logic
        # to determine the actual imported module object.
        if len(args) >= 3 and args[2]:
            module = result
        else:
            module = reduce(getattr, module_name.split('.')[1:], result)
        for symbol, obj in patches_by_module[module_name].items():
            setattr(module, symbol, obj)
        new_modules[module_name] = module
        return result

    # Group patches by module name
    patches_by_module = collections.defaultdict(dict)
    for dotted_name, obj in patches.items():
        module_name, symbol = dotted_name.rsplit('.', 1)  # Only allows patching top-level objects
        patches_by_module[module_name][symbol] = obj

    try:
        # Remove the old module instances from sys.modules and store them in old_modules
        all_module_names = list(patches_by_module)
        if additional_module_names is not None:
            all_module_names.extend(additional_module_names)
        old_modules = {}
        for name in all_module_names:
            old_modules[name] = sys.modules.pop(name)

        # Re-import modules to create new patched versions
        with replace_import_hook(import_hook) as original_import:
            new_modules = {}
            for module_name in all_module_names:
                import_hook(module_name)
    finally:
        sys.modules.update(old_modules)
    return new_modules

rawDescription: Making a copy of an entire namespace?

description: Making a copy of an entire namespace


code:
SUFFIXES = {".md", ".markdown"}

def suffix_filter(event):
    # return True to stop processing of event (to "stop chaining")
    return os.path.splitext(event.name)[1] not in SUFFIXES

processevent = ProcessEvent(pevent=suffix_filter)

rawDescription: python pyinotify to monitor the specified suffix files in a dir

description: Python pyinotify to monitor the specified suffix files in a dir


rawDescription: create intersection from two or more 2d numpy arrays based on common value in one column

description: Create intersection from two or more 2d numpy arrays based on common value in one column


rawDescription: Declare array of matrix in python

description: Declare array of matrix in python


code:
class Bunch(object):
  def __init__(self, adict):
    self.__dict__.update(adict)

rawDescription: Python: load variables in a dict into namespace


code:
for x, x_next in pairwise(the_list):
    ...

rawDescription: Consecutive indices of a Python list in for loop, without specifying indices


code:
db.tweet.insert([
    {
        "retweet_count" : 23,
        "user" : {
            "time_zone" : "Brasilia",
            "statuses_count" : 2475,
            "screen_name" : "Catherinemull",
            "followers_count" : 169,
            "id" : 37486277
        },
        "id" : NumberLong("22819398300")
    },
        {
        "retweet_count" : 7,
        "user" : {
            "time_zone" : "Lisbon",
            "statuses_count" : 4532,
            "screen_name" : "foo",
            "followers_count" : 43,
            "id" : 37486278
        },
        "id" : NumberLong("22819398301")
    },
        {
        "retweet_count" : 12,
        "user" : {
            "time_zone" : "Brasilia",
            "statuses_count" : 132,
            "screen_name" : "test2",
            "followers_count" : 4,
            "id" : 37486279
        },
        "id" : NumberLong("22819398323")
    },
        {
        "retweet_count" : 4235,
        "user" : {
            "time_zone" : "Brasilia",
            "statuses_count" : 33,
            "screen_name" : "test4",
            "followers_count" : 2,
            "id" : 37486280
        },
        "id" : NumberLong("22819398308")
    },
    {
        "retweet_count" : 562,
        "user" : {
            "time_zone" : "Kenya",
            "statuses_count" : 672,
            "screen_name" : "Kiptot",
            "followers_count" : 169,
            "id" : 37486281
        },
        "id" : NumberLong("22819398374")
    },
    {
        "retweet_count" : 789,
        "user" : {
            "time_zone" : "Brasilia",
            "statuses_count" : 5263,
            "screen_name" : "test231",
            "followers_count" : 8282,
            "id" : 37486
        },
        "id" : NumberLong("22819398331")
    }
]);

rawDescription: Nothing happens when trying to use $project


code: findWidget = self.tabWidget.widget(self.tab_index).findChild(QtGui.QPushButton, "tabButton")

rawDescription: How to see signals from QWidgets inside dynamically created QTabWidget pages?

description: See signals from QWidgets inside dynamically created QTabWidget pages


code:
while True:
     if condition:
         break
     do_stuff()  #this line may not ever be reached

rawDescription: Is there a specific way of creating a REPEAT_UNTIL loop in python?


code:
def main():
    application = webapp.WSGIApplication([
         ('/rechnungsdatencontainer/([a-z0-9_-]+)', RechnungsdatencontainerHandler),
         ('/empfaenger/([A-Za-z0-9_-]+)/rechnungen/([A-Za-z0-9_-]+)\.?(json|pdf|xml|invoic|html)?', RechnungslisteHandler),
         ('/admin/credentials', CredentialsHandler),
         ('/', Homepage)],
        debug=True)
    util.run_wsgi_app(application)

rawDescription: GAE: what are the args of webapp.RequestHanderls get(*args)


code:
class Foo(object):
    __slots__ = ('spam',)
    def __init__(self):
        self.spam = 'eggs'

class Bar(object):
    def __init__(self):
        self.spam = 'eggs'

import timeit
timeit.timeit('t.spam', 'from __main__ import Foo; t=Foo()')
timeit.timeit('t.spam', 'from __main__ import Bar; t=Bar()')

rawDescription: How does __slots__ avoid a dictionary lookup?


code:
def foo():
    pass        # This function does nothing

rawDescription: calling function of one class from other class in python

description: Calling function of one class from other class in python


code:
self.root.grid_rowconfigure(1, weight=1)
self.root.grid_columnconfigure(1, weight=1)

rawDescription: Tkinter: grid or pack inside a grid?

description: Tkinter: grid or pack inside a grid


code:
Columns = 7
Rows = 6

def new_game_board() -> [[str]]:
   board = [ ''.join('%3i' % i for i in range(1, 1 + Columns))  ]
   board += Rows*[ Columns*'  *' ]
   return board

gb = new_game_board()

for item in gb:
   print(item)

rawDescription: Printing list of list formating

description: Printing list of list formating


code: [zip(m4c[0][i], m4c[1][i]) for i in range(len(m4c[0]))]

rawDescription: Transposing a 3d list (Python)

description: Transposing a 3d list (Python)


code:
class ResponseIterator:

  def __init__(self, iterator, on_finish=None):
      self.iterator = iterator
      self.on_finish = on_finish

  def __iter__(self):
      return self

  def next(self):
      return next(self.iterator)

  def close(self):
      if self.on_finish is not None:
         self.on_finish()

rawDescription: Implementing a WSGI Streaming Service: (how to detect client disconnects)


code:
{Name: Jim, Age: 24, inSubset: true}
{Name: Bill, Age: 38, inSubset: false}
{Name: Mary, Age: 55, inSubset: true}

rawDescription: Filter map reduce to records that match a different collection


code:
d = { "foo": 4, "bar": 2, "quux": 3 }
sorted(d.items(), key=lambda item: item[1])

rawDescription: Sorted Word frequency count using python


code:
import dis
dis.dis(square.func_code)  # disassemble the function's bytecode
square.func_code.co_names

rawDescription: Query on local frame and global frame in python Environment


rawDescription: Better replacement for a huge "if x==2 / if x==3 / if x==4" chain adding prefixes and suffixes?


code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from scipy import interp

# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]

# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
                                                    random_state=0)

# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
                                 random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)

# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
    roc_auc[i] = auc(fpr[i], tpr[i])

# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

##############################################################################
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()

##############################################################################
# Plot ROC curves for the multiclass problem

# Compute macro-average ROC curve and ROC area

# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))

# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
    mean_tpr += interp(all_fpr, fpr[i], tpr[i])

# Finally average it and compute AUC
mean_tpr /= n_classes

fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

# Plot all ROC curves
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
         label='micro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["micro"]),
         linewidth=2)

plt.plot(fpr["macro"], tpr["macro"],
         label='macro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["macro"]),
         linewidth=2)

for i in range(n_classes):
    plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
                                   ''.format(i, roc_auc[i]))

plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()

rawDescription: How to Plot ROC curve in pyhton

description: Plot ROC curve in pyhton


code:
for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]/arg'):
    # so you don't need another inner loop to access <arg> elements
    if node.get('key') == 'Type A':
        node.set('value', 'false')
    # ... if 'Type B' ...

rawDescription: XML <arg> value Replacement in Python

description: XML <arg> value Replacement in Python


code:
@gen2func
def long_running_function_in_generator_form(x, y, z):
    # do something expensive with x, y, and z, producing result
    while True:
        yield result
        result += 1    # for example

rawDescription: Function which computes once, caches the result, and returns from cache infinitely (Python)


code:
import os

def listfiles(folder):
    for root, folders, files in os.walk(folder):
        for filename in folders + files:
            yield os.path.join(root, filename)

rawDescription: Simplest way to get the equivalent of "find ." in python?


code:
import numpy as np

S = np.random.rand(1000, 2, 1)
c = np.random.rand(1000, 2, 2)
U = np.random.rand(1000, 2, 2)

Y = np.zeros_like(U)
for k in range(1000):
    for jj in range(2):
        for ii in range(k+1):
            Y[k,jj,0] += S[ii,jj,0] * c[k-ii,jj,jj] * U[ii,jj,jj]

Yx = np.zeros_like(Y)
for jj in range(2):
    Yx[:,jj,0] += np.convolve(S[:,jj,0] * U[:,jj,jj], c[:,jj,jj], mode='full')[:Yx.shape[0]]

print(abs(Y - Yx).max())
# -> 3.12638803734e-13

rawDescription: Struggling With Python For-Loop Speed

description: Struggling With Python For-Loop Speed


code:
urlpatterns = [
    url(r'^login/$', views.login, name='login'),
    url(r'^logout/$', views.logout, name='logout'),
    ...
]

rawDescription: How to properly get url for the login view in template?

description: Properly get url for the login view in template


code: df['col3'] = pd.DataFrame(map(lambda k: df[k]==di[k], di)).all()

rawDescription: pandas: select all rows matching multiple conditions

description: Pandas: select all rows matching multiple conditions


code:
def intersect(a, b):
    if len(b) < len(a):  # iff b is shorter than a
        a, b = b, a      # swap the lists.
    b = b[:]  # To prevent modifying the lists
    return [b.pop(b.index(i)) for i in a if i in b]

rawDescription: How can I form a list of matching elements in two lists, including duplicates?

description: Form a list of matching elements in two lists, including duplicates


code:
import os

os.system(r'"C:/Documents and Settings/flow_model/flow.exe"')

rawDescription: How to run/execute exe file in python?

description: Run/execute exe file in python


code:
import re

def make_pattern(template, wildcard="n"):
    replacement_pattern = r"\b{0}\b(?:\s+{0}\b)*".format(wildcard)
    def replacement_func(match):
        return "(" + re.sub(wildcard, r"\w+", match.group()) + ")"
    return re.sub(replacement_pattern, replacement_func, template)

rawDescription: Group m groups with regex

description: Group m groups with regex


code:
class tupledict(dict):

    class node(dict):
        def __repr__(self):
            if self:
                if hasattr(self, "value"):
                    return repr(self.value) + ", " + dict.__repr__(self)
                return dict.__repr__(self)
            else:
                return repr(self.value)

    def __init__(self):
        pass

    def __setitem__(self, key, value):
        if not isinstance(key, tuple):   # handle single value
            key = [key]
        d = self
        for k in key:
            if k not in d:
                dict.__setitem__(d, k, self.node())
            d = dict.__getitem__(d, k)
        d.value = value

    def __getitem__(self, key):
        if not isinstance(key, tuple):
            key = [key]
        d = self
        for k in key:
            try:
                d = dict.__getitem__(d, k)
            except KeyError:
                raise KeyError(key[0] if len(key) == 1 else key)
        try:
            return d.value
        except AttributeError:
            raise KeyError(key[0] if len(key) == 1 else key)

rawDescription: Nested dictionaries in python with error when accessing non-existent key


code: {k: p[k] - m[k]**2 for k in m}

rawDescription: Pythonic way to calculate the mean and variance of values in Counters


code:
import png
import numpy
rows = numpy.zeros((256, 256, 4), dtype = 'int') # eassier format to deal with each individual pixel
rows[:, :] = [255, 0, 0, 255] # Setting the color red for each pixel
rows[10:40, 10:40] = [0, 255, 255, 255] #  filled squared starting at (10,10) to (40,40)
locs = numpy.indices(rows.shape[0:2])
rows[(locs[0] - 80)**2 + (locs[1] - 80)**2 <= 20**2] = [255, 255, 0, 255] # yellow filled circle, with center at (80, 80) and radius 20
png_writer = png.Writer(width = 256, height = 256, alpha = 'RGBA') # create writer
png_writer.write(open('colors_panel.png', 'wb'), rows.reshape(rows.shape[0], rows.shape[1]*rows.shape[2])) # we have to reshape or flatten the most inner arrays so write can properly understand the format

rawDescription: PyPNG to draw a simple filled box

description: PyPNG to draw a simple filled box


code:
xmlDocument = '''<?xml version="1.0" encoding="ISO-8859-1"?> \
<Root> \
<Messages> \
<Message id='12345'> \
   <status>Active</status> \
   <priority>Low</priority> \
   <Area> \
    <Streets> \
     <Street> \
      <name>King Street</name> \
      <length>Short</length> \
       <Link> \
        <id>75838745</id> \
        <direction>North</direction> \
       </Link> \
       <Link> \
        <id>168745</id> \
        <direction>South</direction> \
       </Link> \
       <Link> \
        <id>975416</id> \
        <direction>North</direction> \
       </Link> \
     </Street> \
     <Street> \
      <name>Queen Street</name> \
      <length>Long</length> \
       <Link> \
        <id>366248</id> \
         <direction>West</direction> \
       </Link> \
       <Link> \
        <id>745812</id> \
         <direction>East</direction> \
       </Link> \
     </Street> \
    </Streets> \
   </Area> \
</Message> \
<Message id='54321'> \
   <status>Inactive</status> \
   <priority>High</priority> \
   <Area> \
    <Streets> \
     <Street> \
      <name>Princess Street</name> \
      <length>Mid</length> \
       <Link> \
        <id>744154</id> \
        <direction>West</direction> \
       </Link> \
       <Link> \
        <id>632214</id> \
        <direction>South</direction> \
       </Link> \
       <Link> \
        <id>654785</id> \
        <direction>East</direction> \
       </Link> \
     </Street> \
     <Street> \
      <name>Prince Street</name> \
      <length>Very Long</length> \
       <Link> \
        <id>1022444</id> \
         <direction>North</direction> \
       </Link> \
       <Link> \
        <id>4474558</id> \
         <direction>South</direction> \
       </Link> \
     </Street> \
    </Streets> \
   </Area> \
</Message> \
</Messages> \
</Root>'''

rawDescription: Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy


code:
settings=QtCore.QSettings(iniFile, QtCore.QSettings.IniFormat)
splitterSettings=settings.value("splitterSettings").toByteArray()
if splitterSettings:
    splitter.restoreState(splitterSettings)

rawDescription: How to get QSplitter index and position

description: Get QSplitter index and position


code:
site_info = Makesite.objects.get(sitename=site).siteinfo.get(description=name)
site_info.description = "new description"
site_info.save()

rawDescription: How to delete a many to many object without deleting all objects within the relationship?

description: Delete a many to many object without deleting all objects within the relationship


rawDescription: sort a YAML block mapping sequence in python

description: Sort a YAML block mapping sequence in python


rawDescription: List comprehension to create list of strings from two lists


code:
hexstr = '003de70fc98a'
':'.join([hexstr[i:i+2] for i in range(0, len(hexstr), 2)])

rawDescription: Format hex string to MAC string

description: Format hex string to MAC string


code:
dct = {'a':'vala', 'b':'valb'}
','.join('{}={!r}'.format(k, v) for k, v in dct.items())

rawDescription: How to convert a dict to string?

description: Convert a dict to string


rawDescription: Binary bit flip generator in python

description: Binary bit flip generator in python


code:
import sys
from PySide.QtGui import *
from QtSingleApplication import QtSingleApplication

appGuid = 'F3FF80BA-BA05-4277-8063-82A6DB9245A2'
app = QtSingleApplication(appGuid, sys.argv)
if app.isRunning(): sys.exit(0)

w = QWidget()
w.show()
app.setActivationWindow(w)
sys.exit(app.exec_())

rawDescription: QtSingleApplication for PySide or PyQt

description: QtSingleApplication for PySide or PyQt


code:
for tweet in tweets: #contains list of dictionaries
    matches = re.findall(r"#(\w+)", tweet.get('text', ''))
    if matches:
        tweet_text.append(matches)

rawDescription: Iterating over list and appending value to new list


code:
def test():
  pd.merge(d0,d1, on=[0,1])
timeit.timeit(test, number=1000)

rawDescription: Inner join two list of list given indices


code:
timeit.timeit('way1(listOfRandomInts,dictionaryOfRandomInts)', setup=setup, number=1000)
timeit.timeit('way5(listOfRandomInts,dictionaryOfRandomInts)', setup=setup, number=1000)
timeit.timeit('way6(listOfRandomInts,dictionaryOfRandomInts)', setup=setup, number=1000)
timeit.timeit('way7(listOfRandomInts,dictionaryOfRandomInts)', setup=setup, number=1000)

rawDescription: Finding all keys in a dictionary from a given list QUICKLY


rawDescription: Python list filtering: remove subsets from list of lists


code:
with open(config_file.get(options.env), 'r') as ymlfile:
    config = yaml.load(ymlfile)

config = replace_values(config)

rawDescription: Python YAML parameter reference (get value from other parameter)


rawDescription: Django settings based on IP or hostname

description: Django settings based on IP or hostname


code:
from django.conf.urls import url
from tastypie.utils import trailing_slash

class MyResource(Resource):
    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<%s>.*?)/user%s$" % (self._meta.resource_name, self._meta.detail_uri_name, trailing_slash()), self.wrap_view('group_user'), name="api_group_user"),
        ]

    def group_user(self, request, **kwargs):
        # Your API view.
        return self.create_response(request, {})

rawDescription: How does tastypie handle comlex url?

description: How does tastypie handle comlex url


rawDescription: rpy2, copula, How to import parameters? Python

description: Rpy2, copula, How to import parameters? Python


code:
def almost_equals(one, two):
    one = one.replace('"', '').replace("'", "")
    two = two.replace('"', '').replace("'", "")
    return one == two

def create_data(year, data, text_content):
    """ This function returns new dictionary. """
    content = [line.split(',') for line in text_content.split('\n')]
    res = {}

    for key in data.keys():
        for one_list in content:
            if year == one_list[0] and almost_equals(key, one_list[1]):
                res[one_list[2]] = data[key]

    return res

teams_txt = """1901,'BRO','LAD'
1901,'CHA','CHW'
1901,'WS1','MIN'"""

year = '1901'
data = { '"WS1"': 1475.9778073075058, '"BRO"': 1554.1437268304624, '"CHA"': 1552.228925324831 }
result = create_data(year, data, teams_txt)

rawDescription: python - Looking up a dictionary key in another file with two criteria

description: Python - Looking up a dictionary key in another file with two criteria


code: [i for tup in zip(A,B) for i in tup]

rawDescription: Concatenate two list based on the same index


code:
dfs = pd.read_sql(..., chunksize=100000)
store = pd.HDF5Store("store.h5")
for df in dfs:
    clean_df = ...  # whatever munging you have to do
    store.append("df", clean_df)

rawDescription: Looking for a python datastructure for cleaning/annotating large datasets


rawDescription: How to keep PsychoPy object visual.Window the topmost (active) window on Windows 7?

description: Keep PsychoPy object visual.Window the topmost (active) window on Windows 7


code:
# Get indices at which such diff>15 occur
cut_idx = np.where(np.diff(A[:,1]) > 15)[0]

# Initiaize output array
out = np.zeros((A.shape[0]+len(cut_idx),2),dtype=A.dtype)

# Get row indices in the output array at which rows from A are to be inserted.
# In other words, avoid rows to be kept as zeros. Finally, insert rows from A.
idx = ~np.in1d(np.arange(out.shape[0]),cut_idx + np.arange(1,len(cut_idx)+1))
out[idx] = A

rawDescription: Inserting rows of zeros at specific places along the rows of a NumPy array


code:
import wx

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)

        # create the labels
        lblOne = wx.StaticText(panel, label="labelOne", size=(60,-1))
        lblTwo = wx.StaticText(panel, label="lblTwo", size=(60,-1))
        lblThree = wx.StaticText(panel, label="lblThree", size=(60,-1))

        # create the text controls
        txtOne = wx.TextCtrl(panel)
        txtTwo = wx.TextCtrl(panel)
        txtThree = wx.TextCtrl(panel)

        # create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        lineOneSizer = wx.BoxSizer(wx.HORIZONTAL)
        lineTwoSizer = wx.BoxSizer(wx.HORIZONTAL)
        lineThreeSizer = wx.BoxSizer(wx.HORIZONTAL)

        # add widgets to sizers
        lineOneSizer.Add(lblOne, 0, wx.ALL|wx.ALIGN_LEFT, 5)
        lineOneSizer.Add(txtOne, 0, wx.ALL, 5)
        lineTwoSizer.Add(lblTwo, 0, wx.ALL|wx.ALIGN_LEFT, 5)
        lineTwoSizer.Add(txtTwo, 0, wx.ALL, 5)
        lineThreeSizer.Add(lblThree, 0, wx.ALL|wx.ALIGN_LEFT, 5)
        lineThreeSizer.Add(txtThree, 0, wx.ALL, 5)

        mainSizer.Add(lineOneSizer)
        mainSizer.Add(lineTwoSizer)
        mainSizer.Add(lineThreeSizer)

        panel.SetSizer(mainSizer)

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: wxPython GUI BoxSizers

description: WxPython GUI BoxSizers


code: datetime.datetime = old_datetime_class

rawDescription: Dictionaries with volatile values in Python unit tests?


rawDescription: Creating matrix from dataframe

description: Creating matrix from dataframe


code: pairs = dict([match.split(':', 1) for match in matches])

rawDescription: Regex: How to match sequence of key-value pairs at end of string


code:
for plotname, ((x, y, marker), kwargs) in plots.items():
    plt.plot(x, y, marker, label=plotname, **kwargs)

rawDescription: Exchange the x axis for the y axis in python


rawDescription: Python: dumping dictionaries to columns of a csv file in a table-like format


code:
def RealAppending(the_str):
    lock.acquire()
    try:
        the_file = open("test.txt", "a")
        try:
            the_file.write(the_str) # write
        finally:
            the_file.close()
    finally: # if an error occurs
        lock.release()

rawDescription: Is this a thread-safe module, and actually how do you write one?


code:
def make_great(l):
    return ['The great ' + magician for magician in l]

magicians = ['Tom']
magicians = make_great(magicians)
print(magicians)

rawDescription: Modifying a list in python by passing it to a function


rawDescription: Matrix Approximation and Predicting Timeseries in Python/R with SVD


code:
def toeach_category(subf):
    result = subf[['Time']].applymap(percentage)

rawDescription: Customizing rolling_apply function in Python pandas


code:
for ch in s:
    if ch not in sort_fmt:  # <--- "in" requires a linear search. O(n*m)
        sorted_str += ch    # <--- Ouch! Concatenation! O(n^2)

rawDescription: String Sort based on some Format

description: String Sort based on some Format


code:
import re

def with_re_search():
    a = ['452 04','45204','455 04','88804']
    for i,e in enumerate(a):
        if re.search(r"\s", e):
            a[i] = e.replace(' ','')

def with_in():
    a = ['452 04','45204','455 04','88804']
    for i,e in enumerate(a):
        if ' ' in e:
            a[i] = e.replace(' ','')

def without_search():
    a = ['452 04','45204','455 04','88804']
    for i,e in enumerate(a):
        a[i] = e.replace(' ','')

def with_translate():
    a = ['452 04','45204','455 04','88804']
    for i, e in enumerate(a):
        a[i] = e.translate(None,'')

from timeit import timeit as t
n = 1000000
t('f()', setup='from __main__ import with_re_search as f', number=n) # 5.37417006493
t('f()', setup='from __main__ import with_in as f',        number=n) # 1.04646992683
t('f()', setup='from __main__ import without_search as f', number=n) # 1.2475438118
t('f()', setup='from __main__ import with_translate as f', number=n) # 1.56214690208

rawDescription: Is it faster to check if a subtring exists before removing it?


code:
import requests

s = requests.Session()
url = 'http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber'
response = s.get(url)

rawDescription: about redirect in python crawling and extracting data from a webpage

description: About redirect in python crawling and extracting data from a webpage


code:
from sqlalchemy.types import String, Date, DateTime
df.to_sql(table_name, engine, if_exists='append', dtype={'mydatecol': DateTime})

rawDescription: Pandas and SQL Alchemy: Specify Column Data Types


rawDescription: Collating timestamped events into date ranges with pandas


code:
lst = range(10)
lst
lst[2] = "new value"
lst

rawDescription: Change the value of a list's element

description: Change the value of a list's element


code:
my_list = [2,9,10,15,21,30,33,45]

my_new_list = [x for x in my_list if x % 3 == 0]
print(my_new_list)

rawDescription: Lambda Within Filter Function?

description: Lambda Within Filter Function


rawDescription: Reading and running a mathematical expression in Python


rawDescription: sorting the quintile output from qcut in pandas python

description: Sorting the quintile output from qcut in pandas python


code:
def send_email(fun):
    @wraps(fun)
    def outer(self, *args, **kwargs):
        print('decorated and task is {0!r}'.format(self))
        return fun(self, *args, **kwargs)

    return outer

@task(bind=True)
@send_email
def any_function(self):
    print('inside the function')

rawDescription: Decorator after @task decorator in celery


code:
def item_extra_kwargs(self, obj):
    return { 'featured': val}

rawDescription: Django RSS add attribute into item

description: Django RSS add attribute into item


code:
import operator
operator.eq(x, y)
operator.eq(x, z)

rawDescription: Equality without using operator

description: Equality without using operator


code:
with open('filename') as f:
    query_dict = {line.strip():next(f).strip() for line in f}

rawDescription: python dictionary, make every odd number line to key and even number line to value from a file

description: Python dictionary, make every odd number line to key and even number line to value from a file


rawDescription: replacing node text using lxml.objectify while preserving attributes

description: Replacing node text using lxml.objectify while preserving attributes


code:
from worker import Worker

w = Worker(iserver,login,password,proxyUser,proxyPass,proxyServer,service)
w.version_check()
w.version_get()
w.version_send()

rawDescription: Best approach to pass and handle arguments to function


code:
class Cheese():
    def __init__(self, *args, **kwargs):
        #args -- tuple of anonymous arguments
        #kwargs -- dictionary of named arguments
        self.num_holes = kwargs.get('num_holes',random_holes())

rawDescription: What is a clean, pythonic way to have multiple constructors in Python?


rawDescription: Python: check if list is contained in another list


code:
newbuf = libc.strdup(mybuf)
with freeing(newbuf):
    do_stuff(newbuf)
    do_more_stuff(newbuf)
# automatically freed before you get here
# (or even if you don't, because of an exception/return/etc.)

rawDescription: Memory leaks in Python when using an external C DLL


code:
def quantize(total, limit):
    i, step = 0.0, float(total) / float(limit)
    while i < total:
        yield int(round(i))
        i += step

rawDescription: bash evenly choose 10 numbers

description: Bash evenly choose 10 numbers


rawDescription: cython prange not so fast than single thread

description: Cython prange not so fast than single thread


rawDescription: Searching for a word pattern in a Python dataset


code:
from pyspark.ml.feature import VectorAssembler, VectorIndexer
from pyspark.ml import Pipeline

pipeline = Pipeline(stages=[
    VectorAssembler(inputCols=df.columns, outputCol="features_raw"),
    VectorIndexer(
        inputCol="features_raw", outputCol="features", maxCategories=10)])

transformed = pipeline.fit(df).transform(df)
transformed.schema.fields[-1].metadata

## {'ml_attr': {'attrs': {'nominal': [{'idx': 1,
##      'name': 'x2',
##      'ord': False,
##      'vals': ['0.0', '1.0', '2.0']},
##     {'idx': 2,
##      'name': 'x4',
##      'ord': False,
##      'vals': ['0.0', '1.0', '2.0', '3.0', '4.0']}],
##    'numeric': [{'idx': 0, 'name': 'x1'}]},
##   'num_attrs': 3}}

rawDescription: How can I declare a Column as a categorical feature in a DataFrame for use in ml

description: Declare a Column as a categorical feature in a DataFrame for use in ml


rawDescription: Converting one Spark dataframe to another with a different schema


code:
def computeDeltaTimes(L):
    answer = []
    a, b = itertools.tee(L)
    next(B, None)
    fmt = "%m/%d/%Y %H:%M"
    for start, end in zip(a,b):  # or itertools.izip in python2
        answer.append((dt.strptime(end, fmt) - dt.strptime(start, fmt)).total_seconds())
    return answer

rawDescription: Saving the amount of time between each time stamp in an array


code:
l = [True, False, None, True, None]

# first get indices of None/Undefined elements in the input list
indexes = [i for i,v in enumerate(l) if v is None]

# for each index, generate new list using True and False
# as substitutes.
for idx in indexes:
    for sub in [True, False]:
        new_l = l[:]
        new_l[idx] = sub
        print(new_l)

rawDescription: Generate Truth Table but leave some variables undefined in python


code:
import string
inp = raw_input('what character sets do you want? ')
chars = ''.join(getattr(string, i) for i in inp.split('+'))
chars

rawDescription: Getting function as string then run it

description: Getting function as string then run it


rawDescription: Parsing facebook oauth access_token string


code:
dic = fancy_dict((range(10), 'hello'), (range(100,125), 'bye'))
dic[1]
dic[9]
dic[100]

rawDescription: Is there a way to have a dictionary key be a range?


rawDescription: Numpy.array indexing question

description: Numpy.array indexing question


rawDescription: Python: how to make a function visible throughout a program


rawDescription: Overwrite field values based on membership in a set


code:
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Test>:
    TabbedPanelHeader
        color: (0,0,1,1)
        text:'blaaaaaaa'
        background_color: (0, 0, 1, 1)
        background_normal: 'atlas://data/images/defaulttheme/tab_btn'
''')
class Test(BoxLayout):pass
runTouchApp(Test())

rawDescription: Changing color TabbedPannelHeader in Kivy


code:
import weakref

class FileHandler:
    def __init__(self, dbf, caller = None):
        if caller is not None:
            self._ref = weakref.ref(caller, self.close)
        self.thefile = open(dbf, 'rb')
    def __enter__(self):
        return self
    def __exit__(self, ext_type, exc_value, traceback):
        self.close()
    def close(self, *args):
        print('closing file')
        self.thefile.close()

class Foo:
    def __init__(self):
        self.fh = FileHandler('/tmp/testfile', caller = self)

def autoclosing_file():
    foo = Foo()

def demo_callback():
    with open('/tmp/testfile', 'w'): pass
    autoclosing_file()

if __name__ == '__main__':
    demo_callback()

rawDescription: How do you use weakref or contextlib to close open files?

description: Use weakref or contextlib to close open files


rawDescription: Look up value from row and column headers


code:
model = FPGrowth.train(transactions, minSupport=0.2, numPartitions=10)
freqItemsets = model.freqItemsets()

rawDescription: python 2.7 : create dictionary from list of sets

description: Python 2.7 : create dictionary from list of sets


code:
#!/usr/bin/python2

import matplotlib.pyplot as plt

hax = plt.subplot(1,2,1)
plt.yscale('log')
plt.xscale('log')
plt.ylim((1e-20,1e-10))
plt.xlim((1e-12,1))

hax2 = plt.subplot(1,2,2)
plt.arrow(0.1, 1, 0, 1, length_includes_head=True)

hax.set_position([0.1, 0.1, 0.8, 0.8])
hax2.set_position([0.1, 0.1, 0.8, 0.8])

hax2.set_axis_off()

plt.savefig('test.pdf')

rawDescription: Matplotlib: Draw a vertical arrow in a log-log plot


rawDescription: Python 3.4 JSON sort by key as int

description: Python 3.4 JSON sort by key as int


code:
from Crypto.Cipher import AES
import struct

class MyCounter:

  def __init__(self, nonce):
    """Initialize the counter object.

    @nonce      An 8 byte binary string.
    """
    assert(len(nonce)==8)
    self.nonce = nonce
    self.cnt = 0

  def __call__(self):
    """Return the next 16 byte counter, as binary string."""
    righthalf = struct.pack('>Q',self.cnt)
    self.cnt += 1
    return self.nonce + righthalf

cipher_ctr = AES.new(key, mode=AES.MODE_CTR, counter=MyCounter(nonce))
plaintext = cipher_ctr.decrypt(ciphertext)

rawDescription: Include nonce and block count in PyCrypto AES MODE_CTR


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

rawDescription: How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

description: Remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)


code:
tick_locations_plot=( [vmin]
                  + [-(10.0**x) for x in range(minlog-1,-logthresh-1,-1)]
                  + [0.0]
                  + [(10.0**x) for x in range(-logthresh,maxlog-1)]
                  + [vmax] )

rawDescription: Equidistant ticks on colorbar using SymLogNorm in matplotlib


rawDescription: paramiko stdout show nothing with regular expression?

description: Paramiko stdout show nothing with regular expression


code:
def old_callback(*args):
    wx.MessageBox("Whatever","blah")
def callback(*args):
    wx.CallAfter(old_callback,*args)

watch.bind(callback) # or however

rawDescription: Simultaneous Message Boxes

description: Simultaneous Message Boxes


code:
n2=node(2)
n3=node(3)
n1=node(1)
n0=node(0)

n0.l=n1
n0.r=n3
n3.l=n2

(depth,position,max_depth,match)=recurse(n0,3)
if match:
   answer = (position, max_depth - depth )

rawDescription: How to find position of nodes in binary tree?

description: Find position of nodes in binary tree


code: for i in range (len(lister)): hell.brick_list[i].start_pos = lister[i]

rawDescription: Accessing attributes of a list of objects in python


code:
class Enum(object):
    __metaclass__ = EnumMeta

    def __init__(self, value):
        super(Enum, self).__init__()

        self.value, self.repr, self.klass = value[0], value[1], value[2]

    def __repr__(self):
        return str(self.repr)

rawDescription: Refactoring if statements in python

description: Refactoring if statements in python


rawDescription: Why doesn't numpy.power act element-wise on arrays when the exponent is negative?


code:
num1 = randint(1,20)
num2 = randint(1,20)
print(num1, "+", num2)
answer = int(input("What is the answer to the question: "))

if  answer ==  num1 + num2:
    print("Correct")

rawDescription: How to print "correct" after user answers something correctly in python version 3.4.3

description: Print "correct" after user answers something correctly in python version 3.4.3


code: get_or_create(MyClass, session, MyClass.attribute == "foo", MyClass.attribute_other > 2)

rawDescription: How to make a get_or_create using OR with SQLAlchemy?

description: Make a get_or_create using OR with SQLAlchemy


code:
import numpy as np
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

img = mpimg.imread('Paw03.png')
pixels = img.shape[0]*img.shape[1]
channels = 3
data = np.reshape(img[:, :, :channels], (pixels, channels))

histo_rgb, _ = np.histogramdd(data, bins=256)
histo_rg = np.sum(histo_rgb, 2)
levels = np.arange(256)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for g in levels:
    ax.bar(levels, histo_rg[:, g], zs=g, zdir='y', color='r')
ax.set_xlabel('Red')
ax.set_ylabel('Green')
ax.set_zlabel('Number of pixels')
plt.show()

rawDescription: How to extract RGB from a image and plot only RG as a graph? R for X and G for Y

description: Extract RGB from a image and plot only RG as a graph? R for X and G for Y


code: [round(x) if x > 0.5 else x for x in lst]

rawDescription: Convert a list of floats to the nearest whole number if greater than x in Python


code:
b = a[..., newaxis]
b.shape

rawDescription: How to make a 2d numpy array a 3d array?

description: Make a 2d numpy array a 3d array


rawDescription: Split lists within list

description: Split lists within list


rawDescription: trying to get reasonable values from scipy powerlaw fit

description: Trying to get reasonable values from scipy powerlaw fit


code:
def generate_student_dict(self, **kwargs):
     return kwargs

rawDescription: Python keyword arguments unpack and return dictionary


code:
def example_templatetag():
  def get_something():
    return get_want_you_want_from_db()
  return dict(get_something=get_something)

rawDescription: Flask and jinja2 include tag

description: Flask and jinja2 include tag


code:
l = range(10)
for i in l:
    if i in [2, 3, 5, 6, 8, 9]:
        l.remove(i)

l
[i for i in range(10) if not i in [2, 3, 5, 6, 8, 9]]

rawDescription: python remove element from list while traversing it

description: Python remove element from list while traversing it


code:
import re
[re.findall(r'^\t(.*)\t.*: (.*)$',i) for i in my_list]

rawDescription: Use regex backreferences to create array


code:
def make_special_dog_class(class_name, *classes):
    return type(class_name, tuple(classes), {})

rawDescription: Duck Typing, isinstance(), __subclasshook__() overriding, and types.MethodType() working together?


code:
#UNTESTED
def get_values_from_file(filename):
    winpat = re.compile(r"Matches:\s*\d+\s*\(([\d\.]+)\%\)")
    xinpat = re.compile(r"Score:\s*([\d]+)")

    values = []
    scores = []

    # Note: "with open() as f" automatically closes f
    with open(filename) as f:
        # Note: "for line in f" more memory efficient
        # than "for line in f.readlines()"
        for line in f:
           win = winpat.match(line)
           xin = xinpat.match(line)
           if win: values.append(float(win.group(0)))
           if xin: scores.append(float(xin.group(0)))
    return (scores,values)

rawDescription: Comparing multiple file items using re

description: Comparing multiple file items using re


rawDescription: Sending Hex data

description: Sending Hex data


code:
from swampy.Lumpy import Lumpy
lump = Lumpy()
x = ["one","two",3,5.0]
y = x[:]
lump.draw_object()
lump.object_diagram()

rawDescription: Equal strings auto updating (List object reference)


code: z = [key for key, value in b.iteritems() if value not in {"Supplementary", "Assignment", "Smith", "Bowen"}]

rawDescription: Python; Dictionary iteration

description: Python; Dictionary iteration


code:
def get_value(mapping, keys):
    for key in keys:
        mapping = mapping[key]
    return mapping

rawDescription: Get a value from multidimensional, with variable number of dimensions, dictionary in python