code:
def get(d, keys):
    for key in keys:
        d = d[key]
    return d

def set(d, keys, value):
    d = get(d, keys[:-1])
    d[keys[-1]] = value

rawDescription: How to dynamically move inside a nested dict in Python

description: Dynamically move inside a nested dict in Python


code:
result = set(u for u in users if users[u]['Location'] == 'Boston'
                              or users[u]['Type'] == 'Primary')

rawDescription: Small Tables in Python?

description: Small Tables in Python


code: from sage.all import *

rawDescription: Using Sage Math library within Python

description: Using Sage Math library within Python


rawDescription: Finding the closest date given a date in a groupby dataframe (Python)


code:
array=[]
array_elem=['0.0']
for i in range(3):
    array.append(array_elem[:])  # <--- [:] makes a copy of the full list

rawDescription: Python list processing issue

description: Python list processing issue


rawDescription: Find index of item with duplicates

description: Find index of item with duplicates


code:
alist = []
alist.append(1) is None
alist

rawDescription: Adding a item into a a dictionary in Python


code:
count = None
with open(filename) as file:
     for line in file:
         if 'Rank' in line:
             if count is None: # found the start of the 1st block
                count = 1
             else: # found the start of the 2nd block
                break
         elif count is not None: # inside the 1st block
             count += 1
print(count) # -> 4

rawDescription: Counting jump(no of lines) between first two 'String' occurrences in a file


code:
import random
a = [random.randint(1, 10) for i in range(10)]
b = [random.randint(1, 10) for i in range(10)]
a
b

rawDescription: Remove item from Object set that doesn't exist in query set


code:
number_of_inputs = ...
inputs = []
dictionary = {...}

def print_diff():
    for i in range(number_of_inputs + 1):
        inputs.append(str(input("enter pitch {}".format(i + 1))))
    if inputs[-1] == 'Done':
        del inputs[-1]
        diff = dictionary.difference(set(inputs))
        print('The complement is ')
        for element in diff:
            print(element)

rawDescription: Check variables against a dictionary, and print the dictionary contents remaining


code:
with patch('base.Base.assignment', new_callable=PropertyMock) as a:
    a.return_value = {'a': 1}

rawDescription: Better way to mock class attribute in python unit test


code:
mylst = []
d1[1] = mylst         # this is a reference, not a copy!
mylst.append('Joe')   # modify the object...
d1[1]                 # => ['Joe'] !

rawDescription: python variable length values in dictionary

description: Python variable length values in dictionary


rawDescription: Function editing lists in Python

description: Function editing lists in Python


rawDescription: How to replace unicode characters in string with something else python?

description: Replace unicode characters in string with something else python


code:
a=r""""And",'b',"W,B'" """
ast.literal_eval(a)    # gives the expected and correct
('And', 'b', "W,B'")

rawDescription: Reading a string of data (with a particular format) into a list, in Python


code:
from mock import patch
from StringIO import StringIO

# create a dog and test its speak action
@patch("sys.stdout", new_callable=StringIO)
def test_dog(mock_stdout):
    from farm.animals.dog import Dog
    d = Dog("Allen")
    d.speak()
    assert mock_stdout.getvalue() == "woof\n"

@patch("sys.stdout", new_callable=StringIO)
def test_cat(mock_stdout):
    from farm.animals.cat import Cat
    c = Cat("Micy")
    c.speak()
    assert mock_stdout.getvalue() == "mnau\n"

@patch("sys.stdout", new_callable=StringIO)
def test_rabbit(mock_stdout):
    from farm.animals.rabbit import Rabbit
    r = Rabbit("BB")
    r.speak()
    assert mock_stdout.getvalue() == "Playboy, Playboy\n"

rawDescription: Running python scripts within a subpackage of my package


code:
def pairs(li):
    # Python 2 -- use izip instead of zip
    from itertools import islice
    for this_item, next_item in zip(li, islice(li, 1, None)):
        yield this_item, next_item

rawDescription: Getting a sub-list containing list[i+1] where list[i] is a specific value


code:
c = '\u00BD' # ½
c.isdecimal()
c.isdigit()
c.isnumeric()

rawDescription: str.isdecimal() and str.isdigit() difference example

description: Str.isdecimal() and str.isdigit() difference example


code:
class LoggerWrapper(object):

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

    def debug(self, *args, **kwargs):
        if self.logger is None:
            return
        self.logger.debug(*args, **kwargs)

my_wrapper = LoggerWrapper(logger)
my_wrapper.debug('message')

rawDescription: Avoid check if logger exists

description: Avoid check if logger exists


code: reader = unicodecsv.reader(f, delimiter=b',', skipinitialspace=True, quoting=csv.QUOTE_MINIMAL, quotechar=b'"', lineterminator="\n")

rawDescription: Python Unicode CSV with newline between quotes


code:
import webbrowser

webbrowser.open(magnet_link)

rawDescription: download content torrent files point to in python3

description: Download content torrent files point to in python3


code:
from optparse import OptionParser, Option

# Complete hack.
Option.ALWAYS_TYPED_ACTIONS += ('callback',)

def dostuff(*a):
    pass

parser = OptionParser()
parser.add_option("-c",
                  "--callback",
                  dest="filename",
                  action="callback",
                  callback=dostuff,
                  metavar='LIST',
                  help='do stuff',
                  )

(options, args) = parser.parse_args()

rawDescription: Optparse: Usage on variable arg callback action does not indicate that extra params are needed


rawDescription: Caesar Cipher Python - Additional Features


code:
try:
    row[2] = name_to_abbr[row[1].upper()]
except KeyError:
    pass

rawDescription: Translating State Names in Python

description: Translating State Names in Python


code:
def primeList(n, i=2, acc=None):
    return i > n and (acc or []) or primeList(n, i+1, (acc or []) + (isPrime(i) and [i] or []))

rawDescription: Python recursive function error: "maximum recursion depth exceeded"


code:
# myscript.py

from myproject import mysocket
import sys
sys.modules['socket'] = mysocket

# ... the rest of your code
import requests
...

rawDescription: How can I overload a built-in module in python?

description: Overload a built-in module in python


code:
mapping = {
    'hi':       'dog',
    'friend':   'crazy',
}

# Add to mapping dog->hi and friend->crazy automatically.
mapping.update({v:k for k, v in mapping.items()})

# Convert using mapping.
print(' '.join([mapping.get(w, w) for w in raw_input().split()]))

rawDescription: I was trying to make it so something would equal something else Python 2.7.3


code: {'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}

rawDescription: Copying a key/value from one dictionary into another


code:
import re
re.sub(r"\bMr(?:\.|\b)", "Mister", "a rMr. Nobody Mr. Nobody is Mr Nobody and Mra Nobody.")

rawDescription: Optional dot in regex

description: Optional dot in regex


rawDescription: Selecting rows from an HDFStore given list of indexes


rawDescription: Python's .format() minilanguage and Unicode


code:
myTup
index = bisect.bisect(myTup, (threshold, None))
del myTup[:index]
myTup

rawDescription: Smart way to delete tuples

description: Smart way to delete tuples


code:
def BinPreOrder(T):
    if Is_EmptyBinTree(T): return []
    return [BinRoot(T)] + BinPreOrder(Left(T)) + BinPreOrder(Right(T))

rawDescription: returns the preorder list of a tree in python

description: Returns the preorder list of a tree in python


rawDescription: How to evaluate line of data in python

description: Evaluate line of data in python


code:
def postloop(self):
    user = 'lilith'
    return user

rawDescription: I need help understanding why the return value is different from what I expected. I am using the cmd module


rawDescription: How to save stock data to csv file using python

description: Save stock data to csv file using python


code:
class Wrapper:
    def __init__(self, o, context):
        self._o = o
        self._context = context
    def __getattr__(self, name):
        return getattr(self._o, "get_" + name)(self._context)

rawDescription: Extra arguments for __str__ and __format__


code:
for line in open('bowlingscores.txt', 'rb'):
    line = line.strip()
    if line.isalpha():
        name = line.strip()
    elif line.isdigit():
        score = int(line)
        bowler_scores[name] = score

...

total = sum(bowler_scores.values())
num_scores = len(bowler_scores.values())

...

output = open('output.txt','wb')
for name, score in bowler_scores.items():
    if score == 300:
       output.write('{0} {1} Perfect\r\n'.format(name, score))
    elif score > total_avg:  #8
        output.write('{} {} Above average\r\n'.format(name, score))
    elif score < total_avg:
        output.write('{} {} Below average\r\n'.format(name, score))
output.close()

rawDescription: having trouble outputting an answer to a text file

description: Having trouble outputting an answer to a text file


code:
# change `date` from index to normal column
#g2 = g.reset_index()

# merge by `date` columns
#new_df = pd.merge(left=df, right=g2, on='date', suffixes=('_df','_group') )
new_df = pd.merge(left=df, right=g2, left_on='date', right_index=True, suffixes=('_df','_group') )

rawDescription: Add multi year average column to each row


code: df1 = pd.read_csv(files, names=column, sep='|', header=None, usecols=[1])

rawDescription: merging columns from other files into one file

description: Merging columns from other files into one file


code:
L = [(x0,y0), (x1,y1), ...]
X = numpy.array(L).T
# Equivalently (but less generally):
# X = [[P[0] for P in L], [ P[1] for P in L ]]

t,X = enumerate(L) # here t[0]==0 and X[0]==(x0,x1,..), X[1]==(y0,y1,..)
# or to name in a more confusing manner but match the docs: x,y = enumerate(L)

rawDescription: Spline of curve (python)

description: Spline of curve (python)


code:
import gzip, shutil

src = open('executable', 'rb')
dest = gzip.open('executable.gz.jpg', 'wb')

shutil.copyfileobj(src, dest)

src.close()
dest.close()

rawDescription: Python: binary file to gz file and then to jpg extension and finally return again to the original binary file


code:
i = slices_start.searchsorted(8)
a[slices[i-1].start:slices[i].stop+1]
Out: array(['', '', '', 'B', ''],
  dtype='|S1')

rawDescription: Python - slice array until certain condition is met


code:
class X: pass

type(X)
X.__class__
x = X()
x.__class__
type(x)

rawDescription: Python type() or __class__, == or is

description: Python type() or __class__, == or is


rawDescription: Setting the domain of a function in Python SymPy


code:
def neighbors(code, N=3):
  num = int(code, 2)
  return [num ^ (1 << (N-i-1)) for i in range(N)]

rawDescription: Binary string comparison

description: Binary string comparison


code:
def to_base_5(n):
    s=[]
    while n:
        s.append(str(n%5))
        n=n/5
    return ''.join(s[::-1])

rawDescription: How can I work with base 5 numbers in Python?

description: Work with base 5 numbers in Python


code:
cursor.execute("SELECT user_id FROM round WHERE state = -1 OR state = 2")
numrows = cursor.rowcount

rawDescription: Python MySQLdb iterate through table

description: Python MySQLdb iterate through table


code: name, = (name for name in ('fred','joe') if name=='bob')

rawDescription: select single item from a collection : Python

description: Select single item from a collection : Python


rawDescription: performing outer addition with numpy

description: Performing outer addition with numpy


code: file1.reset_index().merge(file2.reset_index(), on=['acc_id', 'rel_id', 'timestamp']).set_index('timestamp')

rawDescription: Python merge two csv files on multiple columns and nearest datetime


code:
@task()
def add(a, b):
    time.sleep(5) # simulate long time processing
    return a + b

rawDescription: Python+Celery: Chaining jobs?

description: Python+Celery: Chaining jobs


code:
sqlite3.register_adapter(bool, int)
sqlite3.register_converter("BOOLEAN", lambda v: bool(int(v)))

rawDescription: Storing bools in SQLite database

description: Storing bools in SQLite database


rawDescription: python:use a function to remove a list element,I get confused with the result

description: Python:use a function to remove a list element,I get confused with the result


code:
class StateCodeMidleware(object):

   def process_request(self, request):
        bits = request.META['HTTP_HOST'].split('.')
        if len(bits) == 3 and len(bits[0]) == 2:
            request.state_code = bits[0]
        else:
            request.state_code = None
            # Or a redirect to the default state.

rawDescription: wildcard subdomains in a django project

description: Wildcard subdomains in a django project


rawDescription: sorting a list of two columns based on one column python

description: Sorting a list of two columns based on one column python


code: len(str1) == len(str2) and sorted(str1) == sorted(str2)

rawDescription: How can I check if a string has the same characters? Python

description: Check if a string has the same characters? Python


rawDescription: Fastest way to modify list values with condition python


code:
def firstOccur(key, string):
    for i, c in enumerate(string):
        if key == c:
            return i
    return -1

rawDescription: How to make a function that detects a character in a string and returns it's position in the string? Python 3.2

description: Make a function that detects a character in a string and returns it's position in the string? Python 3.2


code:
def intersect(*lists):
    return list(set.intersection(*map(set, lists)))

rawDescription: Intersection of variable number of lists


code:
#!usr/bin/python
import csv

DATA = "data.txt"

class Sequence:
    def __init__(self, row):
        self.qseqid   =       row[0]
        self.sseqid   =       row[1]
        self.pident   = float(row[2])
        self.length   =   int(row[3])
        self.mismatch =   int(row[4])
        self.gapopen  =   int(row[5])
        self.qstart   =   int(row[6])
        self.qend     =   int(row[7])
        self.sstart   =   int(row[8])
        self.send     =   int(row[9])
        self.evalue   = float(row[10])
        self.bitscore = float(row[11])

    def __str__(self):
        return (
            "{qseqid}\t"
            "{sseqid}\t"
            "{pident}\t"
            "{length}\t"
            "{mismatch}\t"
            "{gapopen}\t"
            "{qstart}\t"
            "{qend}\t"
            "{sstart}\t"
            "{send}\t"
            "{evalue}\t"
            "{bitscore}"
        ).format(**self.__dict__)

def entries(fname, header_rows=1, dtype=list, **kwargs):
    with open(fname) as inf:
        incsv = csv.reader(inf, **kwargs)

        # skip header rows
        for i in range(header_rows):
            next(incsv)

        for row in incsv:
            yield dtype(row)

def main():
    bestseq = {}
    for seq in entries(DATA, dtype=Sequence, delimiter="\t"):
        # see if a sequence with the same sseqid already exists
        prev = bestseq.get(seq.sseqid, None)

        if (
            prev is None
            or seq.evalue < prev.evalue
            or (seq.evalue == prev.evalue and seq.bitscore > prev.bitscore)
        ):
            bestseq[seq.sseqid] = seq

    # display selected sequences
    keys = sorted(bestseq)
    for key in keys:
        print(bestseq[key])

if __name__ == "__main__":
    main()

rawDescription: Python selecting items by comparing values in a table using dictionary


code:
def foo():
    pass

foo() # calling

another_function(foo) # passing foo

rawDescription: Python naming convention for variables that are functions


code:
class SrcFile(object):
  def __init__(self, which):
    self.name = which
    self.terminals = set([])

rawDescription: Why is attribute being inherited across classes in Python?


code:
def some_func():
  some_expr_using(lambda args: 42)

# becomes:

def some_func():
  def unique_name(args):
    return 42
  some_expr_using(unique_name)

rawDescription: Translating a lambda to a normal function in Python


code: objectArrray = [ c() for c in classArray ]

rawDescription: How to use "map" function in Python? (How to rewrite a for loop?)

description: Use "map" function in Python? (How to rewrite a for loop?)


code: return len( word ) <= 3 or word not in words and any( w.startswith( word ) for w in words )

rawDescription: Python Logic Help:

description: Python Logic Help:


rawDescription: Python binary operators and word splitting


code: t = tuple(reader)

rawDescription: Python - Import file into NamedTuple

description: Python - Import file into NamedTuple


code: answer = t_sec + (float(t_nsec) / 10**9)

rawDescription: Optimize conversion to decimal representation


code: #pragma omp for lastprivate(x)

rawDescription: cython.parallel: variable assignment without thread-locality

description: Cython.parallel: variable assignment without thread-locality


rawDescription: Django Query Optimization - Using Itertools


rawDescription: Mean value by equality of rows

description: Mean value by equality of rows


code:
foo = 1
_bar = 2

rawDescription: _func() , any functional use of underscore? (Python)


code:
[{'final_count': 14,
  'medication_name': 'Actemra IV',
  'total_prescriptions': 4},
 {'final_count': 14,
  'medication_name': 'Actemra IV',
  'total_prescriptions': 3},
 {'final_count': 14,
  'medication_name': 'Actemra IV',
  'total_prescriptions': 1},
 {'final_count': 14,
  'medication_name': 'Actemra IV',
  'total_prescriptions': 6},
 {'final_count': 12,
  'medication_name': 'Actemra SC',
  'total_prescriptions': 8},
 {'final_count': 12,
  'medication_name': 'Actemra SC',
  'total_prescriptions': 1},
 {'final_count': 12,
  'medication_name': 'Actemra SC',
  'total_prescriptions': 3}]

rawDescription: Summing values for a particular key in a list of dicts in python


rawDescription: Questions about different string, int, and hex types


code:
setup(name="name",
      # console based executables
      console=[],

      # windows subsystem executables (no console)
      windows=[myapp],

      # py2exe options
      zipfile = "myapp.lib", # this is the detached zip library code
      data_files = DATA,
      options={"py2exe": py2exe_options},
      )

rawDescription: How to digitally sign a binary produced with py2exe?

description: Digitally sign a binary produced with py2exe


code:
for node in path[1:]:
    n_spaths[node] += 1

rawDescription: Python: how to compute the number of shortest paths passing through one node?


rawDescription: change column values in CSV using python

description: Change column values in CSV using python


code:
class MyModel(models.Model):
    """My Custom Model Class"""
    def save(self, *args, **kwargs):
        super(self.__class__, self).save(*args, **kwargs)
        if not self.item_id:
            self.item_id = '%s%s' % (self.__class__.__name__[0], self.pk)
            self.save()
    # Must make the parent Model abstract to avoid table creation
    class Meta:
        abstract = True

class Series(MyModel):
    item_id = models.CharField(max_length=60, unique=True, blank=True)
    name = models.CharField(max_length=600, blank=True)

rawDescription: How to add same save method to all models

description: Add same save method to all models


rawDescription: How to POST - API in thingspeak.comusing urllib in Python


code:
import heapq
heapq.nlargest(3, m, key=itemgetter(2))

rawDescription: top 5 or N lists from nested lists "using one of the element" from nested list (little bit complex)

description: Top 5 or N lists from nested lists "using one of the element" from nested list (little bit complex)


code:
inputs = {input1, input2}
found = next((i for i, c in enumerate(combinations(items, 2))
                if set(c) == inputs), None)

rawDescription: Comparing Permutation and Combinations

description: Comparing Permutation and Combinations


code:
def binary_search(predicate, lo, hi):
    while lo + 1 < hi:
        mid = (lo + hi) / 2
        if predicate(mid):
            lo = mid
        else:
            hi = mid
    return lo

def is_small_int(n):
    p = n + 1
    q = n + 1
    return (p - 1) is (q - 1)

def min_neg_small_int():
    p, q = -1, -1
    if p is not q:
        return 0
    while p is q:
        p += p
        q += q
    return binary_search(is_small_int, p / 2, p) - 1

def max_pos_small_int():
    p, q = 1, 1
    if p is not q:
        return 0
    while p is q:
        p += p
        q += q
    return binary_search(is_small_int, p / 2, p)

def small_int_bounds():
    return (min_neg_small_int(), max_pos_small_int())

rawDescription: Python variable allocation and `id` keyword


code:
df = pd.read_csv("sample.csv", names="date time price mag signal".split())
df.set_index(["date", "time"], inplace=True)

rawDescription: List Comprehension Loop

description: List Comprehension Loop


code:
timeit.timeit('math_way("4321234123541234")', setup='from __main__ import math_way', number=10000)
timeit.timeit('str_way("4321234123541234")', setup='from __main__ import str_way', number=10000)

rawDescription: How to add numbers in an integer

description: Add numbers in an integer


code:
# Perform all our computations using standard floats.
results = compute_huge_numbers(42)
# Switch to prettyfloats for printing.
print(map(prettyfloat, results))

rawDescription: subclassing float to force fixed point printing precision in python

description: Subclassing float to force fixed point printing precision in python


code: NewByte = chr(ord(LastByte) ^ x)

rawDescription: Altering the Last Byte of a String

description: Altering the Last Byte of a String


code:
for k, v in PointsOfInterest.iteritems():
    if k in mypkt.Text:
        v[1].append(mykt.Text)

rawDescription: Python incrementing a Dictionary value entry held within a list


code:
def decorator(f):
    f.decorated = True
    return f

class DecoMeta(type):

    def __new__(cls, name, bases, attrs):
        decorated_functions = []
        for v in attrs.values():
            if getattr(v, 'decorated', None):
                decorated_functions.append(v)
        attrs['decorated_functions'] = decorated_functions
        return super(DecoMeta, cls).__new__(cls, name, bases, attrs)

class Parent(object):
    __metaclass__ = DecoMeta

rawDescription: Inheritable Tracking Decorator

description: Inheritable Tracking Decorator


code:
from collections import defaultdict

invert_dict = defaultdict(set)
for k, v in orig_dict.items():
    invert_dict[v].add(k)
# Optionally convert back to regular dict to avoid lookup auto-vivification in the future:
# invert_dict = dict(invert_dict)

rawDescription: Python printing single key/value pairs from a dict


code:
s
''.join(bins)

rawDescription: Python write string "1001101" as binary stream to file


code:
import re
regex, phrases = (r'why (.*) i (.*)\?',
( "You %s %s?",
"Perhaps you only think you %s %s"))
phrase1, phrase2 = phrases
groups = re.search(regex, 'why am i dumb?')
phrase1 % (groups.group(1), groups.group(2))
phrase2 % (groups.group(1), groups.group(2))

rawDescription: Explain what this is for me?

description: Explain what this is for me


code:
view.settings().set('auto_complete', False)
pos = view_sel[0].end()
next_char = view.substr(sublime.Region(pos - 1, pos))

if next_char in (' ', '\n'):
    view.run_command('hide_auto_complete')
    return

view.run_command('hide_auto_complete')
self._show_auto_complete(view)
self._fill_completions(view, pos)

rawDescription: Sublime Text 3 Stop Auto-Complete From Committing on 'Space'


rawDescription: Is there a pandas function to display the first/last n columns, as in .head() & .tail()?


code:
import sys
import os

assert os.path.isdir(sys.argv[1])
listing = os.listdir(sys.argv[1])

for filename in listing:
    with open(sys.argv[1]+"/"+filename,'r') as f:

        for line in f:
            #do something
            pass

rawDescription: calling python script that requires an input from within bash for loop

description: Calling python script that requires an input from within bash for loop


code: rules = [lambda t,a=a: a for a in range(2)]

rawDescription: Python for loop initialization of reference to function


code:
from itertools import groupby
L= ['v1_A', 'v1_B', 'v1_C', 'V2_A', 'V2_B', 'V2000_A']
[list(g) for k, g in groupby(L, lambda s: s.partition('_')[0])]
grouped = {}
for elem in L:
    key = elem.partition('_')[0]
    grouped.setdefault(key, []).append(elem)

grouped.values()

rawDescription: Split list into sublist based on part of value


code:
d = {'t1': 'm1', 'year': '2003'}
fmt = "select * from records where year = #{year} and t1 = #{t1}"
import re
re.sub(r'#\{(.*?)\}', lambda m: d[m.group(1)], fmt) # m -> match object

rawDescription: how to do a complex replace in python using regex?

description: Do a complex replace in python using regex


code:
import re
inputString = 'According to some, dreams express "profound aspects of personality" (Foulkes 184), though others disagree.'
re.findall(r'"([^"]*)"', inputString)

rawDescription: Extract a string between double quotes

description: Extract a string between double quotes


code:
for result in messages:
    times.append(result.group('time'))

rawDescription: Navigating Callable-Iterators

description: Navigating Callable-Iterators


code:
def callback():
     running = False

if playerHealth <= 0: # If the player dies
     expl = Explosion(hit.rect.center, 'lg', callback())
     all_sprites.add(expl) # Show animation of him blowing up

rawDescription: Trying to do animation but the program would close before it


code:
image = pygame.image.load("logo.png")
image = image.convert()

rawDescription: how to use pygame set_alpha() on a picture

description: Use pygame set_alpha() on a picture


code:
import networkx as nx
import matplotlib.pyplot as plt

G = nx.cycle_graph(12)
pos = nx.spring_layout(G)

cf = plt.figure(1, figsize=(8,8))
ax = cf.add_axes((0,0,1,1))

for n in G:
    G.node[n]['draw'] = nx.draw_networkx_nodes(G,pos,nodelist=[n], with_labels=False,node_size=200,alpha=0.5,node_color='r')
for u,v in G.edges():
    G[u][v]['draw']=nx.draw_networkx_edges(G,pos,edgelist=[(u,v)],alpha=0.5,arrows=False,width=5)

plt.ion()
plt.draw()

sp = nx.shortest_path(G,0,6)
edges = zip(sp[:-1],sp[1:])

for u,v in edges:
    plt.pause(1)
    G.node[u]['draw'].set_color('r')
    G.node[v]['draw'].set_color('r')
    G[u][v]['draw'].set_alpha(1.0)
    G[u][v]['draw'].set_color('r')
    plt.draw()

rawDescription: Animating a network graph to show the progress of an algorithm


code:
#start spin
bets = self.spin(bets)
# payount bets

rawDescription: Roulette program will not recognize correct guess. Why?


code: INSTALLED_APPS = ("myproject.someapp", )

rawDescription: Why do I have to put the project name when importing tasks when using Django with Celery?


code:
@contextlib.contextmanager
def patch_select(*, loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()
    old_select = loop._selector.select
    # Define the new select method, used as a context
    def new_select(timeout):
        if timeout == 0:
            return old_select(timeout)
        start = time.time()
        result = old_select(timeout)
        total = time.time() - start
        new_select.iotime += total
        return result
    new_select.iotime = 0.0
    # Patch the select method
    try:
        loop._selector.select = new_select
        yield new_select
    finally:
        loop._selector.select = old_select

rawDescription: How to measure Python's asyncio code performance?

description: Measure Python's asyncio code performance


rawDescription: Parsing the result of ping using regex with python


code:
import os
import sys
import inspect
# Get the current folder, which is the input folder
current_folder = os.path.realpath(
    os.path.abspath(
        os.path.split(
            inspect.getfile(
                inspect.currentframe()
            )
     )[0]
   )
)
folder_parts = current_folder.split(os.sep)
previous_folder = os.sep.join(folder_parts[0:-1])

sys.path.insert(0, current_folder)
sys.path.insert(0, previous_folder)

# Rest of main

rawDescription: Absolute vs Relative Imports in Python 2


code: array([ True, False], dtype=bool)

rawDescription: How do I install numpy/core/numeric.py file on my machine; I want isclose()

description: Install numpy/core/numeric.py file on my machine; I want isclose()


code: lst = [[0 for _ in range(5)] for _ in range(5)]

rawDescription: How to multiply lists and set a single variable?

description: Multiply lists and set a single variable


code:
user_details = [{'name':x, 'rank':i} for i,x in enumerate(ranked_users)]
user_details

rawDescription: Getting index of item while processing a list using map in python


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

fig = plt.figure()
gs = gspec.GridSpec(2, 2)
gs.update(hspace=0.7, wspace=0.7)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[1, 0])
ax3 = plt.subplot(gs[0, 1])
ax4 = plt.subplot(gs[1, 1])

x1 = np.linspace(1,10,10)

ax1.plot(x1, x1**2)
ax1.set_xlabel('ax1 x')
ax1_2 = ax1.twinx()
ax1_2.plot(x1, x1**3)
ax1_2.set_ylabel('ax1_2 y')
ax1.set_ylabel('ax1 y')

# To save time I left the other cells blank, but it should work fine.

plt.show()

rawDescription: matplotlib - No xlabel and xticks for twinx axes in subploted figures

description: Matplotlib - No xlabel and xticks for twinx axes in subploted figures


code:
randomwalk
plt.plot(randomwalk)

rawDescription: Plotting in Python?

description: Plotting in Python


code: props = my_rel.__metadata__["data"]

rawDescription: py2neo: performance and return values of various commands

description: Py2neo: performance and return values of various commands


rawDescription: How can I access a custom section in a Pyramid .ini file?

description: Access a custom section in a Pyramid .ini file


code:
logA = numpy.log10(a)
logB = numpy.log10(b)

rawDescription: Fitting a straight line to a log-log curve in matplotlib


code:
from itertools import product
A = "dog bit dog null".split()
B = "hund bet hund".split()
product(A, repeat=3)
len(list(product(A, repeat=3)))
list(product(A, repeat=3))[:5]

rawDescription: Possible alignments of two lists using Python


code:
class Comment(Base):
    __tablename__ = 'comments'

    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('a.id'), nullable=True)
    b_id = Column(Integer, ForeignKey('b.id'), nullable=True)
    text = Column(UnicodeText, nullable=False)

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

rawDescription: How to construct different-type-ones-to-many relationship?

description: Construct different-type-ones-to-many relationship


rawDescription: Python compresses entire directory rather than the sole files


code:
values = (300.0, 200.0, 100.0)
fout.write(struct.pack('<3f',*values))

rawDescription: How to write a REAL32 value to a file in Python?

description: Write a REAL32 value to a file in Python


code: [v for key in yourdict for v in key]

rawDescription: How to get all values from Python tuple keys from dictionaries into one list?

description: Get all values from Python tuple keys from dictionaries into one list


code:
...
st = os.stat(file)
...
os.utime(outputfile, (st.st_atime, st.st_mtime))
...

rawDescription: Compresse file with preserve modified time stamp


code:
def generate_neighbors(key, alphabet):
    for i in range(len(key)):
        left, right = key[:i], key[i+1:]
        for char in alphabet:
            if char != key[i]:
                yield left + char + right

rawDescription: Faster alternative to for loop in for loop


code:
sum_image = new0.data + new1.data
# put it into an pyfits HDU (primary fits extension)
hdu = pyfits.PrimaryHDU(data=sum_image)

rawDescription: How does one update a FITS data array with PyFITS?

description: Update a FITS data array with PyFITS


code: min(t, key=lambda i: (i[1], -i[2]))

rawDescription: Finding tuple in the list of tuples (sorting by multiple keys)


code:
def f():
    a = 1
    def func():
        print(a)
    return func

rawDescription: How to make super() work by manually filling the __class__ cell?

description: Make super() work by manually filling the __class__ cell


code:
import os
os.system("bash so.sh < abc")

rawDescription: Automate Input Into Python Prompts

description: Automate Input Into Python Prompts


code:
class Topic(models.Model):
    master_topic = models.ForeignKey('self',
                     null=True,
                     blank=True,
                     related_name="sub_topics")

rawDescription: Django, topic model with subtopics

description: Django, topic model with subtopics


code:
dict1
dict2

rawDescription: Creating lists and dictionaries from JSON data in Python


code: counters = counters.reshape( len(peptides), 16, 5 )

rawDescription: Generate a three dimensional array in python by iterating through a list


code:
target = min(x[1] for x in lists if x[0] > 10000)
matches = [x for x in lists if (x[1] == target) and (x[0] > 10000)]

rawDescription: minimum of list of lists

description: Minimum of list of lists


code:
True
True
False

rawDescription: Create python functions from expression trees


code:
def length():
    return randrange(5,71)

def x():
    return randrange(-280,281)

def y():
    return randrange(-200,201)

rawDescription: Drawing Stars with turtle in python

description: Drawing Stars with turtle in python


rawDescription: Conditionally grabbing column headings in pandas dataframe


code: M.data *= 3

rawDescription: How do I get a scipy.csr sparse-matrix as a normal dense matrix without toDense()?

description: Get a scipy.csr sparse-matrix as a normal dense matrix without toDense()


code:
# Simple Progress Bar:
import sys  # for progress bar (sys.stdout)

for i in range(1,1000):
    # your loop's complicated code here
    sys.stdout.write('.'); sys.stdout.flush();  # print a small progress bar

rawDescription: How can I view the progress of a program run in spyder IDE?

description: View the progress of a program run in spyder IDE


code:
from django.core.servers.basehttp import FileWrapper
import StringIO

def aux_pizarra(request):

    myfile = StringIO.StringIO()
    myfile.write("hello")
    myfile.flush()
    myfile.seek(0) # move the pointer to the beginning of the buffer
    response = HttpResponse(FileWrapper(myfile), content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=prueba.txt'
    return response

rawDescription: File downloaded always blank in Python, Django


code:
counts = Person.objects.filter(pk=object.pk).aggregate(
                  num_groups=Count('group_set'), num_items=Count('item_set'))
object.num_groups = counts['num_groups']
object.num_items = counts['num_items']

rawDescription: Use get_object() and aggregate() in DetailView in Django


code:
valid_screen_pixels = screen_width*screen_height - rect_width * rect_height
prob_left = float(rect_x * screen_height) / valid_screen_pixels
prob_right = float((screen_width - rect_x - rect_width) * screen_height) / valid_screen_pixels
prob_above_rect = float(rect_y) / (screen_height-rect_height)
def generate_rand():
    ymin, ymax = 0, screen_height-1
    xrand = random.random()
    if xrand < prob_left:
        xmin, xmax = 0, rect_x-1
    elif xrand > (1-prob_right):
        xmin, xmax = rect_x+rect_width, screen_width-1
    else:
        xmin, xmax = rect_x, rect_x+rect_width-1
        yrand = random.random()
        if yrand < prob_above_rect:
            ymax = rect_y-1
        else:
            ymin=rect_y+rect_height
    x = random.randrange(xmin, xmax)
    y = random.randrange(ymin, ymax)
    return (x, y)

rawDescription: Generate random number outside of range in python


rawDescription: How to efficiently match regex in python

description: Efficiently match regex in python


code:
from PySide import QtGui, QtCore
import math
import sys
import weakref
from numpy import *
from PySide.QtGui import *
from PySide.QtCore import *

class Node(QGraphicsItem):
    Type = QGraphicsItem.UserType+1

    def __init__(self, graphWidget, line):

        super(self.__class__, self).__init__()
        self.line = line
        self.radius = 8

        if graphWidget != None:
            self.graph = weakref.ref(graphWidget)

        self.newPos = QPointF()
        self.setCacheMode(self.DeviceCoordinateCache)
        self.setZValue(-1)

    def boundingRect(self):
        adjust = 10.0
        x,y = array(self.line).transpose()
        rect = [min(x)-self.radius, min(y)-self.radius, max(x)-min(x)+2*self.radius, max(y)-min(y)+2*self.radius]

        return QRectF(*rect)

    def shape(self):
        path = QPainterPath()
        path.setFillRule(Qt.WindingFill)

        radius =  self.radius
        rotation = array( [[0,-1],[1,0]])

        points = zip(self.line[0:-1], self.line[1:])

        for p0, pn in points:
            (x0,y0),(xn,yn) = p0,pn
            dx,dy = array(pn) - array(p0)

            dV = array([dx,dy])
            mag_dV = linalg.norm(dV)

            v = dot(rotation, dV) * radius / mag_dV

            #starting circle
            path.addEllipse(QRectF(x0-radius, y0-radius, 2*radius, 2*radius))
            #rectangular part
            path.moveTo(QPointF(*p0-v))
            path.lineTo(QPointF(*pn-v))
            path.lineTo(QPointF(*pn+v))
            path.lineTo(QPointF(*p0+v))

        path.moveTo(QPointF(*pn))
        path.addEllipse(QRectF(xn-radius, yn-radius, 2*radius, 2*radius))

        return path.simplified()

    def paint(self, painter, option, widget):
        painter.setPen(Qt.black)
        painter.setBrush(Qt.darkGray)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawPath(self.shape())

    def setGraph(self, graph):
        self.graph = weakref.ref(graph)

class GraphWidget(QGraphicsView):
    def __init__(self):
        super(self.__class__, self).__init__()

        self.timerId = 0

        scene = QGraphicsScene(self)
        scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        scene.setSceneRect(0,0,880,880)
        self.setScene(scene)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setRenderHint(QPainter.Antialiasing)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorViewCenter)

        self.centerNode = Node(self, [[50,50],[200,100], [500, 100], [700,700]])
        scene.addItem(self.centerNode)

        self.centerNode.setPos(0,0)
        self.setGeometry(100,100,900,900)
        self.setWindowTitle(self.tr("Elastic Nodes"))

    def addItem(self, item):
        self.item = item
        self.scene().addItem(item)
        item.setGraph(self)
        item.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    qsrand(QTime(0,0,0).secsTo(QTime.currentTime()))

    widget = GraphWidget()
    widget.show()

    sys.exit(app.exec_())

rawDescription: Simplifying a QPainterPath to an outline


code:
from scipy import sparse
import numpy as np

def fast_efreqs(m):

    col_total = np.array(m.sum(axis=0)).ravel()
    row_total = np.array(m.sum(axis=1)).ravel()

    # I'm casting this to an int for consistency with your version, but it's
    # not clear to me why you would want to do this...
    grand_total = int(col_total.sum())

    ridx, cidx = m.nonzero()            # indices of non-zero elements in m
    efreqs = row_total[ridx] * col_total[cidx] / grand_total

    return sparse.coo_matrix((efreqs, (ridx, cidx)))

rawDescription: Faster way to build a matrix of expected frequencies from a sparse matrix of counts


code:
headers = ['Host: www.perdu.com', 'Connection: keep-alive', 'Cache-Control: max-age=0', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8', 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36', 'DNT: 1', 'Accept-Encoding: gzip,deflate,sdch', 'Accept-Language: en-US,en;q=0.8,es;q=0.6,fr;q=0.4', '']
headers = [i.split(': ') for i in headers]

rawDescription: Split list with colon seperated items into list of tuples


code:
_map = {
    '\\\\': '\\',
    "\\'": "'",
    '\\"': '"',
    '\\a': '\a',
    '\\b': '\b',
    '\\f': '\f',
    '\\n': '\n',
    '\\r': '\r',
    '\\t': '\t',
}

def unescape_string(s):
    output = []
    i = 0
    while i < len(s):
        c = s[i]
        i += 1
        if c != '\\':
            output.append(c)
            continue
        c += s[i]
        i += 1
        if c in _map:
            output.append(_map[c])
            continue
        if c == '\\x' and i < len(s) - 2:  # hex escape
            point = int(s[i] + s[i + 1], 16)
            i += 2
            output.append(chr(point))
            continue
        if c == '\\0':  # octal escape
            while len(c) < 4 and i < len(s) and s[i].isdigit():
                c += s[i]
                i += 1
            point = int(c[1:], 8)
            output.append(chr(point))
    return ''.join(output)

rawDescription: How to convert a python string

description: Convert a python string


code:
import re
p = re.compile(r'^Sequence:[^|]*\|(?P<hitsid>[^|]*)\|\S*\s*(?P<protein>[^][]*?)\s*\[(?P<organism>[^][]*)][\s\S]*?\nE-value:\s*(?P<evalue>.*)', re.MULTILINE)
s = "****ALIGNMENT****\nSequence:  gi|86755972|gb|ABD15130.1| cold acclimation protein COR413-PM1 [Chimonanthus praecox]\nLength:  201\nE-value:  2.66576e-82\nKYLAMKTDQLAVANMIDSDINELKMATMRLINDASMLGHYGFGTHFLKWLACLAAIYLLILDRTNWRTNMLTSLL...\n+YLAMKTD+ +   +I +D+ E+  A  +L+ DA+ LG  G GT  LKW+A  AAIYLLILDRTNW+TNMLT+LL...\nEYLAMKTDEWSAQQLIQTDLKEMGKAAKKLVYDATKLGSLGVGTSILKWVASFAAIYLLILDRTNWKTNMLTALL..."
res = [m.groupdict() for m in p.finditer(s)]
for x in res:
    print(x['hitsid'])
    print(x['protein'])
    print(x['organism'])
    print(x['evalue'])

rawDescription: Filter information of a txt file by regular expressions


code:
s = 'fo0'
rand_print(s, 5, 5)
rand_print(s, 5, 5)
rand_print(s, 5, 5)

rawDescription: Printing a random amount of characters a random amount of times in one line


code:
from django.core.cache import cache
cache.set('foo', 'bar')

rawDescription: Django connection to Redis

description: Django connection to Redis


code: lst = anything

rawDescription: List assignment with [:]

description: List assignment with [:]


rawDescription: get slice from multi-dimensions in python

description: Get slice from multi-dimensions in python


rawDescription: how to implement a list of paragraph word lengths using a for loop

description: Implement a list of paragraph word lengths using a for loop


code:
Write('Hello, World!', speed=3)
Press('ENTER')

rawDescription: Simulating a key press event in Python 2.7


code: a = np.dot(D, L)

rawDescription: Is there any fastest way to execute For loops in python?


code:
res = {}
t = df - df.shift(1)
for col in df.columns:
    res[col] = t[col][t[col] != 0]

rawDescription: Filtering for row-wise patterns in columns with a sequence of 0 and 1


code:
def closest(seq, *args):
    # Cache information about `seq`.
    # We only really need to change one sequence.
    sm = SequenceMatcher(b=seq)
    def _ratio(x):
        sm.set_seq1(x)
        return sm.ratio()
    return max(args, key=_ratio)

rawDescription: compare lists with a list to get the list which is closest match to the list we are comparing

description: Compare lists with a list to get the list which is closest match to the list we are comparing


rawDescription: xpath search attribute with part of string

description: Xpath search attribute with part of string


code:
def speed(self, max, now=0):
    self.min = 0
    self.max = max
    self.now = now
    return self.max, self.now

rawDescription: Optional Argument for Function in Python


code:
def runTests(target = None, source = None, env = None) :
    # fill args
    retCode = subprocess.call(args, env = env['ENV'], cwd = cwd, shell = True)
    Exit(retCode)

rawDescription: Call nosetests as a scons task.

description: Call nosetests as a scons task.


code:
type(data0[()])
data0[()][0]
data0[()]['start date']
#There is also an item() method, which however returns the element as python type
type(data0.item())

rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code: next((d[searchtitle] for d in lst if searchtitle in d), None)

rawDescription: How to find dict value by Key in list

description: Find dict value by Key in list


code: df.ix[df.A==0, 'B'] = np.nan

rawDescription: Modifying a subset of rows in a pandas dataframe


code:
import re
line = "(comparative of `good') changed for the better in health or fitness"
match = re.search(r"`(.*?)'", line)
print(match.group(1))

rawDescription: How to get a word bounded between `word' with regex? python

description: Get a word bounded between `word' with regex? python


rawDescription: Check a generated string against a preset string in python


code:
compare( "Carpool" , "prlo")
compare("elephant", "xph")

rawDescription: string recursion problems

description: String recursion problems


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

fnx = lambda : np.random.randint(5, 50, 10)
y = np.row_stack((fnx(), fnx(), fnx()))
x = np.arange(10)

# Make new array consisting of fractions of column-totals,
# using .astype(float) to avoid integer division
percent = y /  y.sum(axis=0).astype(float) * 100

fig = plt.figure()
ax = fig.add_subplot(111)

ax.stackplot(x, percent)
ax.set_title('100 % stacked area chart')
ax.set_ylabel('Percent (%)')
ax.margins(0, 0) # Set margins to avoid "whitespace"

plt.show()

rawDescription: Create a 100 % stacked area chart with matplotlib


code:
if cmds.window("GE_ui_window", exists=True): #If the window exists
    cmds.deleteUI("GE_ui_window") #Delete it
cmds.window("GE_ui_window", title="My custom Graph Editor") #Create your custom win

cmds.frameLayout("GE_ui_frameLayout", p="GE_ui_window", lv=False, bv=False )

if cmds.scriptedPanel("GE_ui_scriptedPanel", exists=True): #If the scriptel panel already exists
    cmds.deleteUI("GE_ui_scriptedPanel") #Delete it
cmds.scriptedPanel("GE_ui_scriptedPanel", unParent=True, type="graphEditor")
cmds.scriptedPanel( "GE_ui_scriptedPanel", e=True, parent="GE_ui_window|GE_ui_frameLayout") #parent the scripted panel to your frame layout

cmds.showWindow("GE_ui_window")

channelLayout = cmds.formLayout("GE_ui_scriptedPanelOutlineEdForm", query=True, ca=True)[0] #Get the channel box's layout
filterLayout = cmds.formLayout("GE_ui_scriptedPanelOutlineEdForm", query=True, ca=True)[1] #Get the filter's layout

myRowLayout=cmds.rowLayout(numberOfColumns=3, p="GE_ui_scriptedPanelOutlineEdForm") #Create a row layout
cmds.button(label="Café", h=100, p=myRowLayout) #Add some buttons
cmds.button(label="Clope", p=myRowLayout)
cmds.button(label="Caca", p=myRowLayout)

#This will reorder the content of the left formLayout
cmds.formLayout("GE_ui_scriptedPanelOutlineEdForm", edit=True, af=[ \
            (channelLayout, "bottom", 0), \
            (channelLayout, "right", 0),  \
            (filterLayout, "top", 0),  \
            (myRowLayout, "left", 0),  \
            (myRowLayout, "right", 0)],  \
            ac=[(myRowLayout, "top", 0, filterLayout), \
            (channelLayout, "top", 0, myRowLayout)])

rawDescription: How do I parent new, user-created buttons inside the Graph Editor window?

description: Parent new, user-created buttons inside the Graph Editor window


code:
iterator = (x for x in ('a', 'b', 'c', 'd', 'e'))
tuple(next(iterator) for _ in range(3))

rawDescription: Assign next n iterations to tuple

description: Assign next n iterations to tuple


code:
result = {}
for key, value in file1.iteritems():
    if value in file2:
        result[key] = file2[value]

rawDescription: Text processing with two files

description: Text processing with two files


code:
def add_len(strlist):
    new_list = []
    for s in strlist:
        new_list.append((s, len(s)))
    return new_list

rawDescription: Append length of string for each string in list


code:
store = Pool(phone_number = phone_number.phone_number,
             un_answered=x, answered=0)

rawDescription: Django Views Incrementing Variables

description: Django Views Incrementing Variables


rawDescription: drawing a line on an image with PIL

description: Drawing a line on an image with PIL


code:
import sqlite3

conn = sqlite3.connect('data.db')
conn.execute("""
    CREATE TABLE IF NOT EXISTS matches (
        id    integer primary key autoincrement not null,
        team1  text,
        team2 text,
        score text
    )""")

cursor = conn.cursor()
cursor.executemany("""
    INSERT INTO
        matches (team1, team2, score)
    VALUES
        (:team1, :team2, :score)""", data)
conn.commit()
conn.close()

rawDescription: BeautifulSoup data scrapping and database


code:
def cube(a):
    for x in a:
        return x**3

rawDescription: For loops clarity

description: For loops clarity


code:
patterns = ['AA', 'AB', 'AC', 'BA', 'BB', 'BC']
filenames = ['file_{}.dat'.format(pattern) for pattern in patterns]
filenames

rawDescription: python read -> analyze -> print multiple files

description: Python read -> analyze -> print multiple files


code: 'd' in [elem for sublist in mylist for elem in sublist]

rawDescription: What is the most efficient way to search nested lists in python?


code:
def overlap_split_list(l,s):
    l1 = []
    l2 = []
    for i in l:
        if i in s:
            l1.append(l2)
            l2 = []
        l2.append(i)
    if l2: l1.append(l2)
    return l1

rawDescription: split a list in python

description: Split a list in python


code:
class MyStdout(object):
    def __init__(self,textwidget):
        self.textwidget = textwidget
    def write(self,txt):
        self.textwidget.insert(END,txt)

sys.stdout = MyStdout(mytextwidget)

rawDescription: subprocess.call() interacting with GUI (Tkinter)

description: Subprocess.call() interacting with GUI (Tkinter)


code: f = re.compile('|'.join( '(^'+p+'$)' for p in pat ))

rawDescription: How to check a string matched with multiple patterns?

description: Check a string matched with multiple patterns


code:
import stat
import os.stat

def disk_exists(path):
     try:
             return stat.S_ISBLK(os.stat(path).st_mode)
     except:
             return False

rawDescription: Python: Check if a /dev/disk device exists


rawDescription: Make python __doc__ property display correctly in a Windows CMD window?


code:
for keyphrase, url in links:
    content = re.sub('(%s)' % keyphrase, r'\1' % url, content, flags=re.IGNORECASE)

rawDescription: Convert phrases in HTML to links with Python


code:
p = Person("Nick")
p2 = Person("Paul")
p.friend1 = p2
p.friend1 = p2
p.friend1.name

rawDescription: Initializing values that point to uninitiated classes. Python @property to control setting of elements within a collection


code:
dimension = 8
for r in range(dimension):
    for c in range(dimension):
         print(int(c==r), end=" ")
    print()

rawDescription: How to create a diagonal within a nested for loop?

description: Create a diagonal within a nested for loop


code: indices = tree.query_ball_point(p, 0.33)

rawDescription: Search neighboring points using k-d trees


code:
self.editFields = [angle1Edit, angle2Edit, len1Edit, len2Edit]

clearBtn.clicked.connect(self.clearAll)

def clearAll(self, checked=False):
    for field in self.editFields:
        field.clear()

rawDescription: PySide: how to clean `QLineEdit` field with a button click?


code:
from django.utils import timezone

def available(self):
    return not self.purchases_set.filter(data=timezone.now().date()).exists()

rawDescription: How to check if object has partner

description: Check if object has partner


code:
import gtk
import webkit

class App(object):
    def __init__(self):
        win = gtk.Window()
        win.connect("destroy", self.destroy)
        web = webkit.WebView()
        web.open("http://www.google.com")
        win.add(web)
        web.show()
        win.show()
    def destroy(self, widget, data = None):
        gtk.main_quit()
app = App()
gtk.main()

rawDescription: Different behaviour between python console and python script


code:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from customauth.models import MyUser

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email', 'date_of_birth')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    """
    A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ['email', 'password', 'date_of_birth', 'is_active', 'is_admin']

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

class MyUserAdmin(UserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'date_of_birth', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('date_of_birth',)}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'date_of_birth', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, MyUserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

rawDescription: Django Abstract BaseUser

description: Django Abstract BaseUser


code: start = indeces.index(i)

rawDescription: Lists, conditionals and loops don't give the result expected


code:
regex = re.compile(r'src="(.+)" alt')
[regex.search(img).group(1) for img in p]

rawDescription: Python Regex over list of strings

description: Python Regex over list of strings


code: sorted(list_of_objects, key=lambda o: o.lowest_z)

rawDescription: Python, sort a list of objects by lowest sub-object attribute


code:
from collections import OrderedDict

tups = OrderedDict([
    ('narrative', narrative),
    ('subject', subject),
    ('activity', activity),
    ('filer', filer)
])

# The result is ['subject', 'subject, filer', 'filer', 'subject, activity']

rawDescription: Filter a tuple with another tuple in Python


code:
import pandas as pd
df = pd.read_csv('many_cols.csv')
df.col1.drop_duplicates().tolist()
df['col2'].drop_duplicates().tolist()
df['col3'].drop_duplicates().tolist()

rawDescription: Is there a in built method from python csv module to enumerate all possible value for a specific column?


rawDescription: Numpy.unique - getting output with consistent depth


code:
instance = DataGen()

print(instance.first_name) # Storm8
print(instance.last_name) # Trooper6
print(instance.email) # xOy37zF@bR68DdLr36mq.net
print(instance.empid) # JhPGpnwUQlm9tCaWbW3F
print(instance.ssn) # 370469583

rawDescription: Getting Python to Create a new instance every time


code:
from datetime import datetime
a = datetime(2011,11,24,0,0,0)
b = datetime(2011,11,17,23,59,59)
a-b
(a-b).days

rawDescription: Days between two dates in Python

description: Days between two dates in Python


code:
for row in range(0, 10):
    for col in range(0, 10):
        num = row * col
        if num < 10:
            empty = "  "
        else:
            if num < 100:
                empty  = " "
        if col == 0:
            if row == 0:
                print("    ", end = '')
            else:
                print("  ", row, end='')
        elif row == 0:
            print("  ", col, end='')
        else:
            print(empty, num, end = '')
    print()

rawDescription: How to print multiplication table using nested for loops

description: Print multiplication table using nested for loops


code:
for item in tails:
    ( xposition, yposition ) = item[1:]  # tuple assignment
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

rawDescription: Getting a specific value from a tuple within a list


code:
import flask
from flask.ext.sqlalchemy import SQLAlchemy
from celery import Celery

class FlaskCelery(Celery):

    def __init__(self, *args, **kwargs):

        super(FlaskCelery, self).__init__(*args, **kwargs)
        self.patch_task()

        if 'app' in kwargs:
            self.init_app(kwargs['app'])

    def patch_task(self):
        TaskBase = self.Task
        _celery = self

        class ContextTask(TaskBase):
            abstract = True

            def __call__(self, *args, **kwargs):
                if flask.has_app_context():
                    return TaskBase.__call__(self, *args, **kwargs)
                else:
                    with _celery.app.app_context():
                        return TaskBase.__call__(self, *args, **kwargs)

        self.Task = ContextTask

    def init_app(self, app):
        self.app = app
        self.config_from_object(app.config)

celery = FlaskCelery()
db = SQLAlchemy()

rawDescription: How to use Flask-SQLAlchemy in a Celery task

description: Use Flask-SQLAlchemy in a Celery task


code:
W = nmf_model.fit_transform(A);
H = nmf_model.components_;

rawDescription: Nonnegative matrix factorization in Sklearn


code:
class DataSet:
    def __init__(self, path_to_set, path_to_db, train_set=False, path_to_labels=None, label_dict=None,
                 custom_name=None):
        self._train_set = train_set
        # ...

rawDescription: Accessing SQLalchemy from a class

description: Accessing SQLalchemy from a class


code:
import subprocess
command = [
    r'C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\wish84.exe',
    r'C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\IxiaWish.tcl'
]
p = subprocess.Popen(commands,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

rawDescription: TCL in Python: can't find package

description: TCL in Python: can't find package


code:
import numpy as np
data = np.array( [0, 2, 7, 6, 3, 1, 4, 5] )
shape = ( 2, 4 )
data.reshape( shape )

rawDescription: Read flat list into multidimensional array/matrix in python


rawDescription: Storing list element address into dictionary


rawDescription: Calculate value relative to another value


code: loc_x_curve = fc.find('scale', index=0)

rawDescription: How Can I Set the Interpolation of a F-Curve via Python? (Blender)


code: result = getattr(foo, 'bar')()

rawDescription: Calling a function of a module from a string with the function's name in Python


rawDescription: How to find and order duplicates in data sets

description: Find and order duplicates in data sets


rawDescription: What is the most efficient way to create a pandas dataframe that combine two unrelated series?


code:
from SimpleCV import *
image = Image('image.png')
binarized = image.binarize(220).invert()
binarized.show()

rawDescription: How do I locate the rabbit?

description: Locate the rabbit


code:
def self_compose (cb, n):
    def __worker (val):
        for _ in range (n):
            val = cb (val)
        return val

    return __worker

rawDescription: Python lambda self composing function: How to return a function that is repeated n amount of times?


code: s.reset_index().drop(1, axis=1)

rawDescription: Pandas reset index on series to remove multiindex


code:
import numpy as np

def cartesian(arrays, out=None):
    """
    Generate a cartesian product of input arrays.

    Parameters
    ----------
    arrays : list of array-like
        1-D arrays to form the cartesian product of.
    out : ndarray
        Array to place the cartesian product in.

    Returns
    -------
    out : ndarray
        2-D array of shape (M, len(arrays)) containing cartesian products
        formed of input arrays.

    Examples
    --------
    >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
    array([[1, 4, 6],
           [1, 4, 7],
           [1, 5, 6],
           [1, 5, 7],
           [2, 4, 6],
           [2, 4, 7],
           [2, 5, 6],
           [2, 5, 7],
           [3, 4, 6],
           [3, 4, 7],
           [3, 5, 6],
           [3, 5, 7]])

    """

    arrays = [np.asarray(x) for x in arrays]
    dtype = arrays[0].dtype

    n = np.prod([x.size for x in arrays])
    if out is None:
        out = np.zeros([n, len(arrays)], dtype=dtype)

    m = n / arrays[0].size
    out[:,0] = np.repeat(arrays[0], m)
    if arrays[1:]:
        cartesian(arrays[1:], out=out[0:m,1:])
        for j in xrange(1, arrays[0].size):
            out[j*m:(j+1)*m,1:] = out[0:m,1:]
    return out

rawDescription: Numpy equivalent of itertools.product

description: Numpy equivalent of itertools.product


code:
#!/usr/bin/env python
import yaml

def float_representer(dumper, value):
    text = '{0:.4f}'.format(value)
    return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
yaml.add_representer(float, float_representer)

print(yaml.safe_dump([1 / 11, 1 / 13, 1 / 17, 'some more text']))
print(yaml.dump([1 / 11, 1 / 13, 1 / 17, 'some more text']))

rawDescription: How to round numeric output from yaml.dump, in Python?

description: Round numeric output from yaml.dump, in Python


rawDescription: How to round to zero decimals if there is no decimal value with Jinja2?

description: Round to zero decimals if there is no decimal value with Jinja2


code:
def divvy_up(lst, lengths):
    pos = 0
    for length in lengths:
        yield tuple(lst[pos:pos + length])
        pos += length

rawDescription: create lists of tuples from two lists

description: Create lists of tuples from two lists


code:
class Knapsack(object):
    def __init__(self, seq, target):
        self.seq = seq
        self.target = target
        self.solution = None
    def solveIt(self):
        if self.target == 0 or self.target in self.seq:
            self.solution = (target,)
            return True, self.solution
        for r in range(len(self.seq),1,-1):
            for subset in combinations(self.seq, r):
                if sum(subset) == self.target:
                   self.solution = subset
                   return True, self.solution
        return False, ()

rawDescription: Turning my function into a class

description: Turning my function into a class


code:
# highly simplified cancellation token
# probably needs synchronization
class CancellationToken:
     cancelled = False
     def isCancelled(self):
         return cancelled
     def cancel(self):
         cancelled = True

# iterates a collection with cancellation support
def withCancellation(collection, cancelToken):
     for element in collection:
         if cancelToken.isCancelled():
             break
         yield element

progressCollection = withProgress(collection, RealProgressBar())
cancellableCollection = withCancellation(progressCollection, cancelToken)
bigIteration(cancellableCollection)

# meanwhile, on another thread...
cancelToken.cancel()

rawDescription: Separating Progress Tracking and Loop Logic


code:
valid_test = sc.parallelize([(2, 5), (1, 4), (3, 5)])
valid_test
## ParallelCollectionRDD[434] at parallelize at PythonRDD.scala:423

model.predictAll(valid_test).count()
## 3

rawDescription: Spark ALS predictAll returns empty

description: Spark ALS predictAll returns empty


code:
import fileinput
import sys
import re

_hex_colour = re.compile(r'#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b')

def replace(match):
    value = match.group(1)
    if len(value) == 3:  # short group
        value = [str(int(c + c, 16)) for c in value]
    else:
        value = [str(int(c1 + c2, 16)) for c1, c2 in zip(value[::2], value[1::2])]
    return 'rgb({})'.format(', '.join(value))

for line in fileinput.input(inplace=True):
    line = _hex_colour.sub(replace, line)
    sys.stdout.write(line)

rawDescription: Change all hex colors values to rgb

description: Change all hex colors values to rgb


rawDescription: Most efficient way to use the django ORM when comparing elements from two lists


rawDescription: Scan through row elements whose classname is identical


opt2: text

rawDescription: Parsing a lightweight language in Python


code: re.sub(r'(\d+)', lambda m: str(int(m.group()) + 2), s)

rawDescription: How to evaluate replacement part in re.sub?

description: Evaluate replacement part in re.sub


code:
from simple_salesforce import Salesforce
def getAFreshContactList(sfSession):
    if isinstance(sfSession, Salesforce):
        return sfSession.query("SELECT Id, Name, Email FROM Contact LIMIT 2")['records']

rawDescription: Python Function Encapsulation (to avoid accidental invocations without proper context)


code: ["{}{}".format(i1, i2) for i1 in l1 for i2 in l2]

rawDescription: Concat each element of list with each element of second list


code:
a = [1,-2,3,4,45]
print(isEveryNumberPositiveIn(a))

rawDescription: Python-Recursion-New To Programming

description: Python-Recursion-New To Programming


code:
def parse(self, response):
    for table in response.xpath('//table[@class="table-stats"]'):
        date = table.xpath('./preceding-sibling::h2[1]/text()').extract()[0]
        for match in table.xpath('.//tr[@class="preview" and @id]'):
            home_team = match.xpath('.//span[@class="team-home teams"]/a/text()').extract()[0]
            away_team = match.xpath('.//span[@class="team-away teams"]/a/text()').extract()[0]

            item = MyItem()
            item['date'] = date
            item['home_team'] = home_team
            item['away_team'] = away_team
            yield item

rawDescription: How to scrape contents from multiple tables in a webpage

description: Scrape contents from multiple tables in a webpage


code: import Common.Package

rawDescription: Python Project with Multiple Modules with the same Name


code: d = pq(filename=path_to_html_file)

rawDescription: Find words in a file then grab the x,y coordinates next to the text


rawDescription: Concatenate a list with a list of lists

description: Concatenate a list with a list of lists


code:
a = ['spam']
b = a
b
a is b

rawDescription: How to copy boost python list or his reference with "=" operator

description: Copy boost python list or his reference with "=" operator


code:
characters = {}
characters['warrior'] = {}
characters['warrior']['orc'] = {}
characters['warrior']['orc']['strength'] = 5
characters['warrior']['orc']['intelligence'] = 2
characters
characters['warrior']['orc']['strength'] += 3
characters

rawDescription: How to add to dictionaries, but not dictionaries - Python

description: Add to dictionaries, but not dictionaries - Python


code:
def struct():
    pass
record = struct
record.number = 2
struct.__dict__
class Struct:
    pass
record = Struct()
record.number = 3
record.__dict__
record=set()
record.__dict__
pow.__dict__

rawDescription: Why do Python's empty classes and functions work as arbitrary data containers, but not other objects?


code:
from collections import namedtuple

Wall = namedtuple('Wall', 'pos height')

def max_water_heldover(heights):
    """Find the maximum amount of water held over skyscrapers with *heights*."""
    stack = []
    water_held = 0 # the total amount of water held over skyscrapers
    for pos, height in enumerate(heights):
        while True:
            if not stack or height < stack[-1].height: # downhill
                stack.append(Wall(pos + 1, height)) # push possible left well wall
                break
            else: # height >= stack[-1].height -- found the right well wall/bottom
                bottom = stack.pop().height
                if stack: # if there is the left well wall
                    well_height = min(stack[-1].height, height) - bottom
                    if well_height:
                        water_held += (pos - stack[-1].pos) * well_height
    return water_held

rawDescription: Algorithm to solve for water accumulation given building heights


code:
import re
matcher = re.compile("(-?[\d*#]+)\s*-\s*([\d*#][\d*#])\s*-\s*([\d*#][\d*#])")

datetuples = [matcher.match(daterange).groups() for daterange in dateranges]

rawDescription: Specific data conversion in python

description: Specific data conversion in python


code:
class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('brand', 'name',)}

rawDescription: How do I customize a slug field in Django?

description: Customize a slug field in Django


code:
def join(self, other, on=None, how='left', lsuffix='', rsuffix='',
         sort=False):
    return self._join_compat(other, on=on, how=how, lsuffix=lsuffix,
                             rsuffix=rsuffix, sort=sort)

def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
                 sort=False):
    from pandas.tools.merge import merge, concat

    if isinstance(other, Series):
        if other.name is None:
            raise ValueError('Other Series must have a name')
        other = DataFrame({other.name: other})

    if isinstance(other, DataFrame):
        return merge(self, other, left_on=on, how=how,
                     left_index=on is None, right_index=True,
                     suffixes=(lsuffix, rsuffix), sort=sort)
    else:
        if on is not None:
            raise ValueError('Joining multiple DataFrames only supported'
                             ' for joining on index')

rawDescription: mapping dataframes not series pandas

description: Mapping dataframes not series pandas


code: f, pathname, desc = imp.find_module('logging', [path for path in sys.path if path and path[0] != '.'])

rawDescription: Importing a file with the same name as the file you're in


code:
from pygame import *
from pygame.locals import *
from math import *

#----------------------------------------------------------------------

class Clock(object):

    def __init__(self, hours, minutes, seconds, cx, cy, r):

        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
        self.cx = cx
        self.cy = cy
        self.r = r

        self.hours_dx = self.cx
        self.hours_dy = self.cy - self.r*.75
        self.minutes_dx = self.cx
        self.minutes_dy = self.cy - self.r
        self.seconds_dx = self.cx
        self.seconds_dy = self.cy - self.r

    def update(self):

        self.seconds_ang = 270 + 6 * self.seconds

        self.seconds_dx = self.cx + int(cos(radians(-self.seconds_ang))*self.r)
        self.seconds_dy = self.cy - int(sin(radians(-self.seconds_ang))*self.r)

        self.minutes_ang = 270 + 6 * (self.minutes + self.seconds/60.)

        self.minutes_dx = self.cx + int(cos(radians(-self.minutes_ang))*self.r)
        self.minutes_dy = self.cy - int(sin(radians(-self.minutes_ang))*self.r)

        self.hours_ang = 270 + 30 * (self.hours + self.minutes/60.)

        self.hours_dx = self.cx + int(cos(radians(-self.hours_ang))*self.r*.75)
        self.hours_dy = self.cy - int(sin(radians(-self.hours_ang))*self.r*.75)

        self.seconds += 1

        if self.seconds == 60:
            self.seconds = 0
            self.minutes += 1

            if self.minutes == 60:
                self.minutes = 0
                self.hours += 1

                if self.hours == 12:
                    self.hours = 0

    def draw(self, screen):
        draw.circle(screen, (255,255,255), (self.cx,self.cy), self.r, 3)
        draw.line(screen, (0,255,255), (self.cx,self.cy), (self.hours_dx, self.hours_dy), 5)
        draw.line(screen, (255,255,0), (self.cx,self.cy), (self.minutes_dx, self.minutes_dy), 2)
        draw.line(screen, (255,0,255), (self.cx,self.cy), (self.seconds_dx, self.seconds_dy), 1)

#----------------------------------------------------------------------

init()

screen = display.set_mode((800,600))

clock = time.Clock()

clock1 = Clock(5, 59, 0, 400, 300, 200)
clock2 = Clock(5, 59, 0, 100, 100, 100)
clock3 = Clock(3, 9, 0, 700, 100, 100)
clock4 = Clock(7, 24, 0, 100, 500, 100)
clock5 = Clock(11, 30, 0, 700, 500, 100)

CLOCK1 = USEREVENT+1
CLOCK2 = USEREVENT+2
CLOCK3 = USEREVENT+3
CLOCK4 = USEREVENT+4
CLOCK5 = USEREVENT+5

timer1 = time.set_timer(CLOCK1, 1000)
timer2 = time.set_timer(CLOCK2, 100)
timer3 = time.set_timer(CLOCK3, 100)
timer4 = time.set_timer(CLOCK4, 10)
timer5 = time.set_timer(CLOCK5, 10)

running=True
while running:

    # events

    for e in event.get():
        if e.type == QUIT:
            running = False

        elif e.type == CLOCK1:
            clock1.update()
        elif e.type == CLOCK2:
            clock2.update()
        elif e.type == CLOCK3:
            clock3.update()
        elif e.type == CLOCK4:
            clock4.update()
        elif e.type == CLOCK5:
            clock5.update()

    # (variable) modifications

    # draw

    screen.fill((0,0,0))

    clock1.draw(screen)
    clock2.draw(screen)
    clock3.draw(screen)
    clock4.draw(screen)
    clock5.draw(screen)

    # flip

    display.flip()

    # FPS (Frames Per Seconds)

    clock.tick(60)

quit()

rawDescription: Clock in Python

description: Clock in Python


code:
import datetime

stuff = '''
actions = [{u'action': 'visit_testing', u'timestamp': datetime.datetime(2016, 2, 12, 13, 32, 14)}, {u'action': 'visit_foo', u'timestamp': datetime.datetime(2016, 2, 12, 13, 37, 50)}]
'''

exec(stuff)
print(actions)
print(actions[0]['timestamp'])

rawDescription: Python convert string to list (No .split())


rawDescription: Thread designed to delete Tkinter Text Widget Content does not operate.


code:
s = 'please answer my question'
len(s)  # number of characters in s

rawDescription: How to get the size of a string in Python?

description: Get the size of a string in Python


code: {{ lines|linebreaks }}

rawDescription: How can display the lines from linux log file in browser


code:
from collections import namedtuple

class Verb(namedtuple("_Verb",  # arbitrary class name/tag
                      ["singular1", "singular2", "singular3",
                       "plural1", "plural2", "plural3"])):
    @property
    def singular(self):
        return (self.singular1, self.singular2, self.singular3)

    # similarly for plural

    @property
    def first_person(self):
        return (self.singular1, self.plural1)

    # similarly for 2nd and 3rd person

rawDescription: Represent a table as object

description: Represent a table as object


rawDescription: Efficiently re-indexing one level with "forward-fill" in a multi-index dataframe


rawDescription: Python Regex for alpha(alpha|digit)*

description: Python Regex for alpha(alpha|digit)*


code:
merged_data = data.replace("\n", " ")
single_list = merged_data.split()

rawDescription: Efficient way to organise data file in columns with Python


rawDescription: Check if there are values other than a certain value exists in a list


code:
# These are our data points
x_vals = [0, 1./6, 1./3, 1./2, 7./12, 2./3, 3./4, 5./6, 11./12, 1]

# Set up the domain
x_domain = arange(0,2, 1e-2)

fx = zeroV(10)

# Defines the function so we can get our fx values
def sine_func(x):
    return(1.6*e**(-2*x)*sin(3*pi*x))

for i in range(len(x_vals)):
    fx[i] = sine_func(x_vals[i])

# Run cubic_spline interpolant.
cubic_spline(10,x_vals,fx)

rawDescription: Cubic Spline Python code producing linear splines


code:
from collections import Counter
d = {1301: Counter({'total': 18,
                  "ongoing" : 3})}
list(reduce(lambda a,b:a|b, d.values()))

rawDescription: counterdict unique values Python

description: Counterdict unique values Python


code:
from pyad import *
pyad.set_defaults(ldap_server="dc1.domain.com", username="service_account", password="mypassword")
ou = ADContainer.from_dn("ou=users, dc=domain, dc=com")
new_user = ADUser.create("Daniel", ou, password="Secret")

rawDescription: Create users on Microsoft Active Directory using a Scripting Language


code: df[cols] = df[cols].astype('category')

rawDescription: Change a list of DataFrame object columns into categories with keeping their names


code:
from __future__ import absolute_import

from django.db import models

from .fields import LongListAsTextField

class Record(models.Model):
    parent_list = LongListAsTextField()

rawDescription: I have a list of long integers that I assign to a django model charfield. The list of longs get converted to list of unicodes


rawDescription: Implementing Google's DiffMatchPatch API for Python 2/3


code:
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.PhantomJS()
driver.get("http://www.funimation.com/shows/assassination-classroom/videos/episodes")

wait = WebDriverWait(driver, 10)

links = []
while True:
    # wait for the page to load
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.item-title")))

    # wait until the loading circle becomes invisible
    wait.until(EC.invisibility_of_element_located((By.ID, "loadingCircle")))

    links.extend([link.get_attribute("href") for link in driver.find_elements_by_css_selector("a.item-title")])

    print("Parsing page number #" + driver.find_element_by_css_selector("a.jp-current").text)

    # click next
    next_link = driver.find_element_by_css_selector("a.next")
    if not next_link.is_displayed():
        break

    next_link.click()
    time.sleep(1)  # hardcoded delay

print(len(links))
print(links)

rawDescription: Checking the clickability of an element in selenium using python


code:
# a.get_name()           # atom name (spaces stripped, e.g. 'CA')
# a.get_id()             # id (equals atom name)
# a.get_coord()          # atomic coordinates
# a.get_vector()         # atomic coordinates as Vector object
# a.get_bfactor()        # isotropic B factor
# a.get_occupancy()      # occupancy
# a.get_altloc()         # alternative location specifier
# a.get_sigatm()         # std. dev. of atomic parameters
# a.get_siguij()         # std. dev. of anisotropic B factor
# a.get_anisou()         # anisotropic B factor
# a.get_fullname()       # atom name (with spaces, e.g. '.CA.')

rawDescription: Extract Columns from a Protein Data Bank (PDB) Text File


rawDescription: How to make my SWIG extension module work with Pickle?

description: Make my SWIG extension module work with Pickle


code:
MatchObject = type(re.search('', ''))
isinstance(re.search('', ''), MatchObject)

rawDescription: Python : using isinstance on C based type MatchObject


code:
from bs4 import BeautifulSoup

data = """

I am
 not  doing a great job

"""

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

result = []
for text in soup.p.find_all(text=True):
    parent = text.parent
    parent_class = parent["class"][0] if "class" in parent.attrs else ""
    for word in text.split():
        result.append([word, parent_class])

print(result)

rawDescription: Beautifulsoup: get class name for each word


code:
m = pd.concat([df1, df2],axis=1)
m["b"] = m.pop("b").sum(axis=1)
m

rawDescription: pandas concat/merge and sum one column

description: Pandas concat/merge and sum one column


rawDescription: Assigning subvectors to multidimensional arrays in Numpy


code:
def get_squares():
    yield from (num ** 2 for num in range(10))

list(get_squares())

rawDescription: Is there any shorthand for 'yield all the output from a generator'?


code:
class SpriteOrange():

    def __init__(self, image):
        self.image = pygame.image.load(image)
        self.x = 0
        self.y = 0

    def draw(self, screen):
        screen.blit(self.image, self.x, self.y)

    def update(self):
        self.x = random.randrange(0,400)
        self.y = random.randrange(0,400)

rawDescription: how to make a list of images and draw them in random position in pygame?

description: Make a list of images and draw them in random position in pygame


rawDescription: Use dictionary in a variable as a set of arguments to a function


code:
import zmq
from multiprocessing import Process

def calculate(data):
    return {"output": data['ok']}

def handle_request(url):
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.connect(url)
    while True:
        data = socket.recv_json()
        print("received {}".format(data))
        out = calculate(data)
        socket.send_json(out)

def server():
    context = zmq.Context()
    # Set up socket for clients to connect to.
    clients = context.socket(zmq.ROUTER)
    clients.bind('tcp://*:{}'.format(5556))

    # Set up ipc socket for workers to connect to
    url_worker = 'ipc:///tmp/workers'
    workers = context.socket(zmq.DEALER)
    workers.bind(url_worker)

    # Start 4 worker processes
    for _ in range(4):
        p = Process(target=handle_request, args=(url_worker,))
        p.start()

    # Forward requests from clients to the workers via a Queue
    zmq.device(zmq.QUEUE, clients, workers)

if __name__ == "__main__":
    server()

rawDescription: Multi core ZeroMQ?

description: Multi core ZeroMQ


code:
from piston.emitters import Emitter
from piston.utils import Mimer

class TextEmitter(Emitter):
    def render(self, request):
        return self.construct()
Emitter.register('text', TextEmitter)
Mimer.register('text', None, ('text/plain',))

rawDescription: How do I use Django piston to return a response in text/plain?

description: Use Django piston to return a response in text/plain


rawDescription: How may I resolve python path strings with Django?


rawDescription: How to randomly change positions of non-zero entries of an array where certain rows are excluded

description: Randomly change positions of non-zero entries of an array where certain rows are excluded


code:
chunks = gen_chunks()
next(chunks)
(chunks)

rawDescription: How to return nested list elements and use them in order in python?

description: Return nested list elements and use them in order in python


code:
from BeautifulSoup import BeautifulSoup, Tag

# ....

soup = BeautifulSoup(data)
for a in soup.findAll('a'):
    a.parent.insert(a.parent.index(a)+1, Tag(soup, 'br'))

rawDescription: Search and Replace in HTML with BeautifulSoup


rawDescription: Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?


code:
for year in os.listdir('.'):
    for month in os.listdir(year):
        for day in os.listdir(os.path.join(year, month)):
            date = datetime.date(int(year), int(month), int(day))

rawDescription: Python: Recusively remove file folders greater than x days old


rawDescription: Natural Naming Scheme for a dynamic set of members


code:
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict

# dependencies can be any iterable with strings,
# e.g. file line-by-line iterator
dependencies = [
  'Werkzeug>=0.6.1',
  'Flask>=0.9',
]

# here, if a dependency is not met, a DistributionNotFound or VersionConflict
# exception is thrown.
pkg_resources.require(dependencies)

rawDescription: How to check if my Python has all required packages?

description: Check if my Python has all required packages


code:
def square_sum_difference(n):
    return int(n*(n+1)*(2*n+1)/6 - (n*(n+1)/2)**2)

rawDescription: Function to calculate the difference between sum of squares and square of sums


code:
import os
import sys
import inspect
this_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
src_dir = os.path.join(this_dir, '..')
sys.path.insert(0, src_dir)

rawDescription: Importing from another directory

description: Importing from another directory


rawDescription: Access dictionary from a list

description: Access dictionary from a list


code:
[

    JSON.stringify({
        "size":"2",
        "color":"1",
        "colorNumber":"1",
        "barCode":"1234567890",
        "barCodePic":"",
    }),
    JSON.stringify({
        "size":"3",
        "color":"1",
        "colorNumber":"2",
        "barCode":"0987654321",
        "barCodePic":"",
    })

]

rawDescription: Unable to retrieve an Array of objects posted to Django from jQuery


code:
with open("test.txt", "r") as Spenn,open("test.txt", "r") as table:
    reader = csv.reader(Spenn, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

rawDescription: Python: Searching a specific columns of a table for not matching items


code:
s = '!@#yourname!@#'
while not s[0].isalpha(): s = s[1:]
print(s)

rawDescription: Most Pythonic was to strip all non-alphanumeric leading characters from string


code: sentence = sentence[8:12].replace(' ', '*')

rawDescription: Going character by character in a string and swapping whitespaces with python


code:
quickElement("a", quickElement("li", time_list, ""), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + time_format + "'));");
quickElement("a", quickElement("li", time_list, ""), gettext("07:00"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,7,0,0,0).strftime('" + time_format + "'));");
quickElement("a", quickElement("li", time_list, ""), gettext("12:00"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,12,0,0,0).strftime('" + time_format + "'));");
quickElement("a", quickElement("li", time_list, ""), gettext("12:30"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,12,30,0,0).strftime('" + time_format + "'));");
quickElement("a", quickElement("li", time_list, ""), gettext("16:00"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,16,0,0,0).strftime('" + time_format + "'));");
quickElement("a", quickElement("li", time_list, ""), gettext("16:30"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,16,30,0,0).strftime('" + time_format + "'));");

...

rawDescription: Changing the default times in the Django TimeInput


code:
import pandas as pd
df = pd.DataFrame([
    'must watch. Good acting',
    'average movie. Bad acting',
    'good movie. Good acting',
    'pathetic. Avoid',
    'avoid'], columns=['description'])

rawDescription: How to find ngram frequency of a column in a pandas dataframe?

description: Find ngram frequency of a column in a pandas dataframe


code:
c = u'96.9%'
float(c.rstrip(u'%'))
float(c.rstrip(u'% \n\t\r\xa0'))
c = u'96.9%  \n   '
float(c.rstrip(u'%'))
float(c.rstrip(u'% \n\t\r\xa0'))

rawDescription: Most efficient way to strip a % from u'96.9%' and return a float


code:
sys.path.insert(0, path_to_plugindir)
for folder in dirArray:
    __import__(folder)

rawDescription: Multiple imports of the same file name

description: Multiple imports of the same file name


rawDescription: How to find a prime number with an upperbound and store in an array?

description: Find a prime number with an upperbound and store in an array


code:
def quickSelect(lines,k):
    if len(lines)!=0:
        pivot=lines[(len(lines)//2)]
        smallerlist=[]
        for i in lines:
            if i<pivot:
                smallerlist.append(i)
        largerlist=[]
        for i in lines:
            if i>pivot:
                largerlist.append(i)
        m=len(smallerlist)
        count=len(lines)-len(smallerlist)-len(largerlist)
        if k >= m and k<m + count:
            return pivot
        elif m > k:
            return quickSelect(smallerlist,k)
        else:
            return quickSelect(largerlist, k - m - count)

rawDescription: Python quickselect sorting

description: Python quickselect sorting


code:
product = functools.partial(functools.reduce, operator.mul)

x = product(b for a, b in items)

rawDescription: Pythonic way of multiplying contents of list by one another in Python3


code:
import os.path
import glob
import re
import itertools
from collections import namedtuple, deque
from operator import attrgetter

R_PREFIX_VALUE = re.compile(r'^(?P<prefix>[A-Z]+)(?P<suffix>\d+)\s+(?P<value>\d+)\s*$')

getvalue  = attrgetter('value')

def interleave(seq, val):
    return itertools.chain.from_iterable(itertools.izip(seq, itertools.repeat(val)))

class Fileline(namedtuple('Fileline', 'filename prefix suffix value')):
    @classmethod
    def _fromstr(cls, s, filename=None, rematch=R_PREFIX_VALUE.match):
        m = rematch(s)
        if not m:
            raise ValueError('No valid line found in %r' % s)
        d = m.groupdict()
        d['value'] = int(d['value'])
        d['filename'] = filename
        return cls(**d)

    def _asstr(self):
        return '{}{} {}'.format(self.prefix, self.suffix, self.value)

def max_value_with_prefix(lineseq, prefix, getvalue=getvalue):
    withprefix = (line for line in lineseq if line.prefix==prefix)
    return max_value(withprefix)

def filter_lt_line(lineseq, maxline):
    for line in lineseq:
        if line.prefix != maxline.prefix or line.value >= maxline.value:
            yield line

def extreme_value(fn, lineseq, getvalue=getvalue):
    try:
        return fn((l for l in lineseq if l is not None), key=getvalue)
    except ValueError:
        return None

def max_value(lineseq):
    return extreme_value(max, lineseq)

def min_value(lineseq):
    return extreme_value(min, lineseq)

def read_lines(fn, maker=Fileline._fromstr):
    with open(fn, 'rb') as f:
        return deque(maker(l, fn) for l in f)

def write_file(fn, lineseq):
    lines = (l._asstr() for l in lineseq)
    newlines = interleave(lines, '\n')
    with open(fn, 'wb') as f:
        f.writelines(newlines)

def write_output_file(fn, lineseq):
    lines = ("{} {}".format(l.filename, l.value) for l in lineseq)
    newlines = interleave(lines, "\n")
    with open(fn, 'wb') as f:
        f.writelines(newlines)

def filter_max_returning_min(fn, prefix):
    lineseq = read_lines(fn)
    maxvalue = max_value_with_prefix(lineseq, prefix)
    filteredlineseq = deque(filter_lt_line(lineseq, maxvalue))
    write_file(fn, filteredlineseq)
    minline = min_value(filteredlineseq)
    return minline

def main(fileglob, prefix, outputfile):
    minlines = []
    for fn in glob.iglob(fileglob):
        minlines.append(filter_max_returning_min(fn, prefix))
    write_output_file(outputfile, minlines)

rawDescription: Finding minimum value of word from a lot of files in python?


code:
if os.path.isfile( success_flag ) :
    os.remove( success_flag )
else :
    return

rawDescription: Making sure a Python script with subprocesses dies on SIGINT


rawDescription: python list of tuples to javascript array of arrays

description: Python list of tuples to javascript array of arrays


code:
import re
from datetime import date

user_string = input('Enter something')  # use raw_input() in Python 2.x

pattern = re.compile(r'(\d{2})/(\d{2})/(\d{4}|\d{2})')  # 4 digits match first!
match = re.search(pattern, user_string)

if not match:
    d = None
else:
    month, day, year = map(int, match.groups())
    try:
        d = date(year, month, day)
    except ValueError:
        d = None  # or handle error in a different way

print(d)

rawDescription: Python: Parse String as Date with Formatting


rawDescription: Pretty printing a list of list of floats?


code:
from jinja2 import Template
fields = ["operating revenue", "gross operating profit", "EBITDA", "operating profit after depreciation", "EBIT", "date"]
template_file = '''\
{%- for field in fields %}
-
  name: {{field}}
  type: string
{%- endfor -%}
'''
template = Template(template_file)
html_rendered = template.render(fields=fields)
print(html_rendered)

rawDescription: newline and dash not working correctly in jinja

description: Newline and dash not working correctly in jinja


code:
# you can simply pass the valid sets as `test` set
return X_train, y_train, X_val, y_val, X_val, y_val

rawDescription: numpy array from csv file for lasagne

description: Numpy array from csv file for lasagne


code:
subject---marks
english---42
maths---48
science---49

rawDescription: how to create a table using python

description: Create a table using python


rawDescription: Sum while in Python?

description: Sum while in Python


code:
ab
0
bc
1
cd
2
de
3
ef
4
fg
5
gh
6

rawDescription: Python string slicing, special case if end of string included?


code: transpose(transpose(m) + [baz])

rawDescription: Does anyone have a better solution for 'iteratively' applying zip in Python?


code:
def noWhitespace(source, locn, tokens):
    if not source[locn:].startswith('.'.join(tokens)):
        raise ParseException("found whitespace between fields")
table_name.addParseAction(noWhitespace)

rawDescription: Optional string segment in pyparsing

description: Optional string segment in pyparsing


code:
zip([source.data['xvals'][i] for i in inds],
    [source.data['yvals'][i] for i in inds])

rawDescription: Get selected data contained within box select tool in Bokeh


code:
import numpy as np
import scipy.ndimage.filters
A = np.zeros((5,5))
A[2,2] = 1
B = scipy.ndimage.filters.laplace(A)
A
B

rawDescription: What is the Laplacian mask/kernel used in the scipy.ndimage.filter.laplace()?


rawDescription: Python - List of unique dictionaries

description: Python - List of unique dictionaries


code:
from gmpy import mpz
a=mpz(7)
bin(a)
a=a.setbit(48)
bin(a)

rawDescription: getting 64 bit integer in python

description: Getting 64 bit integer in python


code:
def split_input(user_string, chunk_size):
    output = []
    words = user_string.split(" ")
    total_length = 0

    while (total_length < len(user_string) and len(words) > 0):
        line = []
        next_word = words[0]
        line_len = len(next_word) + 1

        while  (line_len < chunk_size) and len(words) > 0:
            words.pop(0)
            line.append(next_word)

            if (len(words) > 0):
                next_word = words[0]
                line_len += len(next_word) + 1

        line = " ".join(line)
        output.append(line)
        total_length += len(line)

    return output

rawDescription: How would one limit characters per line when printing a raw_input to a text file?


code:
def plus_five(num):
    my_other_number = num + 5
    return my_other_number

rawDescription: I'm struggling on functions, for example def a (...). What goes in the brackets?


code:
def fullname(self):
    return fmt("{mod}.{name}", self)

rawDescription: Using instance variables as named format substitutions


code:
#if int values
print (df['returns'].str[:-1].astype(int))

#if flaot values
print (df['returns'].str[:-1].astype(float))

rawDescription: How to remove % symbol for particular column in dataframeusing python pandas?

description: Remove % symbol for particular column in dataframeusing python pandas


code:
def permNums(inp, N=4):
    newInp = []
    for i in inp:
        for j in range(N):
            if j not in i: newInp.append( i+[j] )
    return newInp

rawDescription: How to write a lot of nested 'for' loops (Recursively)

description: Write a lot of nested 'for' loops (Recursively)


code: wj_df.to_hdf('test.h5', 'key')

rawDescription: large filesize difference between `pandas to_json` and `read_json`

description: Large filesize difference between `pandas to_json` and `read_json`


code:
start_stop = [slice(int(start), int(stop)) for c, start, stop in a]
#if you need to conserve resources or time, use a generator expression
#start_stop = (slice(int(start), int(stop)) for c, start, stop in a)

rawDescription: Writing python chunking loops with reference to another txt


code: timeit.timeit('math.e**2', 'import math', number=1000000)

rawDescription: Two very different but very consistent results from Python timeit


code:
lst = ['Aden', u'abe1']
sorted(lst)
sorted(lst, key=lambda s: s.lower())

rawDescription: case-insensitive list sorting, without lowercasing the result?

description: Case-insensitive list sorting, without lowercasing the result


code:
def on_event_method(f):
    f.__observer__ = True
    return f

rawDescription: How to use decorator in observer pattern for Python 2.7

description: Use decorator in observer pattern for Python 2.7


code:
def curry_f(A):
    def f_curried(x):
        return f(x, A)  # using your definition from above
    return f_curried

f2 = np.vectorize(curry_f(P))
f2(X)

rawDescription: Numpy vectorize, using lists as arguments


code:
import datetime
import time

target_date = datetime.datetime(2017, 1, 11)
timedelta_zero = datetime.timedelta(0)

while True:
    diff = target_date - datetime.datetime.now()
    if diff <= timedelta_zero:
        break
    print(diff)
    time.sleep(1)
print('Takeoff!!!')

rawDescription: Countdown timer giving me negative numbers


code: joint = [[x + y for x, y in zip(*row)] for row in zip(outgoing, incoming)]

rawDescription: Python - List comprehension with 2 for loops & a ADD AND operand


rawDescription: Turn a hex string into a percent encoded string in Python


code:
# in file apptime.py (for example)
import time as _time

class MyTimeService(object):
    def __init__(self, get_time=None):
        self.get_time = get_time or _time.time

    def __call__(self):
        return self.get_time()

time = MyTimeService()

rawDescription: How to change the date/time in Python for all modules?

description: Change the date/time in Python for all modules