code:
class Browse(generic.ListView):
    template_name = 'app/browse.html'
    paginate_by = 25

    # Modifying the get_context_data method

    def get_context_data(self, **kwargs):
        context = super(Browse, self).get_context_data(**kwargs)
        q = self.request.GET.get("browse")
        context['input'] = q
        return context

    def get_queryset(self):
        queryset = Cats.objects.all()
        if self.request.GET.get("browse"):
            selection = self.request.GET.get("browse")
            if selection == "Cats":
                queryset = Cats.objects.all()
            elif selection == "Dogs":
                queryset = Dogs.objects.all()
            elif selection == "Worms":
                queryset = Worms.objects.all()
            else:
                queryset = Cats.objects.all()
        return queryset

rawDescription: Django ListView customising queryset

description: Django ListView customising queryset


code:
class Test1( OurTest ):
    source_file = 'this'
    result_file = 'that'

class Test2( OutTest ):
    source_file= 'foo'
    result_file= 'bar'

rawDescription: How to write a unit-test where each test case has different input but does the same?

description: Write a unit-test where each test case has different input but does the same


code:
df = pd.DataFrame(data={'a':np.random.randn(1000)},
        index=pd.date_range(start='2000-01-01', periods=1000, freq='30T'))

rawDescription: Average hourly week profile for a year excluding weekend days and holidays


code:
from mysuper import MySuper

class Magistrate(MySuper):
  def __init__(self, fizz=None, foo=None):
    if fizz is None:
      self.fizz = 'baz'
    else:
      self.fizz = fizz
    if foo is None:
      self.foo = 42
    else:
      self.foo = foo
    super().__init__()

rawDescription: How to dynamically create new python class files?

description: Dynamically create new python class files


code: b = Button(app_name, text="..." , command = lambda: any_function(7))

rawDescription: tkinter , python , buttons

description: Tkinter , python , buttons


code:
def get_url(self):
    current_url = 'xyz'
    return current_url

def test_check_url(self):
    url = get_url()
    # write more lines

rawDescription: Python unit test how do I pass variable from one function to another


code:
# define common carrier for calculation of average curve
x_all_1 = np.linspace(0, 1, num=101, endpoint=True)
x_all_2 = np.linspace(1, 10, num=21, endpoint=True)
x_all = np.concatenate((x_all_1, x_all_2))

rawDescription: Calculate mean over discrete functions with different amount of sampling points


code:
filename = root.find("./Locations/*[@name='CacheLocation']").text
filename

rawDescription: Parse XML attribute to variable with ElementTree


code: funcs = { 'A':ctypes.uint64, 'B':bool }

rawDescription: Automatic code generation in python

description: Automatic code generation in python


rawDescription: splitting a sparse matrix into two

description: Splitting a sparse matrix into two


code: strip_output.py < my_notebook.ipynb > my_notebook_stripped.ipynb

rawDescription: How can I open an IPython notebook without the output?

description: Open an IPython notebook without the output


code:
COLORMAP_AUTUMN = 0
COLORMAP_BONE = 1
COLORMAP_COOL = 8
COLORMAP_HOT = 11
COLORMAP_HSV = 9
COLORMAP_JET = 2
COLORMAP_OCEAN = 5
COLORMAP_PINK = 10
COLORMAP_RAINBOW = 4
COLORMAP_SPRING = 7
COLORMAP_SUMMER = 6
COLORMAP_WINTER = 3

rawDescription: Create colour picture from greyscale picture


code:
...
if __name__ == '__main__':
    args = argparser()

    from tests import *

    ...

rawDescription: Passing python script arguments to test modules


code:
from datetime import date

@property
def is_past_due(self):
    if date.today() > self.date:
        return True
    return False

rawDescription: How to compare dates in Django

description: Compare dates in Django


code:
def cycle_file(filename):
    while True:
        for line in open(filename):
            yield line

rawDescription: Re-reading file when cycling over a file object in Python


code:
print('rows')
print(df[df == 0].count(axis=1)/len(df.columns))
print('cols')
print(df[df == 0].count(axis=0)/len(df.index))

rawDescription: Pandas: Counting the proportion of zeros in rows and columns of dataframe


code:
from string import ascii_lowercase as ALC
from itertools import chain, product

for chars in chain(ALC, product(ALC, repeat=2), product(ALC, repeat=3)):
    print(''.join(chars))

rawDescription: Iterate a to zzz in python

description: Iterate a to zzz in python


code:
GLOBAL_MYCLASS_LIST = []

class MyClass(object):

    def __init__(self, x, y):
        GLOBAL_MYCLASS_LIST.append(self)
        self.x = x
        self.y = y

    def power(self):
        print(self.x**self.y)

    def divide(self):
        print(self.x/self.y)

a = MyClass(2, 3)
b = MyClass(4, 7)
all_powers = [i.power() for i in GLOBAL_MYCLASS_LIST]

rawDescription: Is there a way to run a method for all instances of a class in python?


code:
Alpha, 10
Beta, 30
Alpha, 42
Gamma, 81
Beta, 10

rawDescription: How to sort two columns at once using sorted()

description: Sort two columns at once using sorted()


code:
rate_df.lookup(df['state'], df['year'])
df['rate2'] = res.lookup(df['state'], df['year'])
df

rawDescription: n-dimensional table lookup: array, dataframe, or dictionary?

description: N-dimensional table lookup: array, dataframe, or dictionary


Status: Active

Card name: NAMEn

Account holder: NAME

rawDescription: Convert a HTML Table to JSON

description: Convert a HTML Table to JSON


code:
import pygame
pygame.init()

clock = pygame.time.Clock()
# or whatever loop you're using for the animation
while True:
    # draw animation
    # pause so that the animation runs at 30 fps
    clock.tick(30)

rawDescription: Python Animation Timing

description: Python Animation Timing


rawDescription: Django Urls regex to suport old php pages


code:
m,n= image.shape
r = np.sqrt((np.arange(m)[:,None]-origin[0])**2 + (np.arange(n)-origin[1])**2)

rawDescription: Fastest computation of distances in rectangular array


code:
dot = re.compile("[^.]*\.[^.]*$")
dot.match("fooooooooooooo.bar")
dot.match("fooooooooooooo.bar.sad") is None

rawDescription: regex for character appearing at most once

description: Regex for character appearing at most once


rawDescription: Rotating a 5D array in the last 2 dimensions


rawDescription: Check whether list element is greater than previous elements


rawDescription: Using python to remove all strings and comments from python code


code:
idx = df[df['BoolCol']].index.tolist()
idx

rawDescription: Python Pandas: Get index of rows which column matches certain value


code:
def createfile():
    var = """#!/bin/sh\necho ${test}"""
    funcToCreateScript(filename,var)

rawDescription: store formatted text in variable python

description: Store formatted text in variable python


rawDescription: Removing special characters from a string in Python


code:
d = sub_df.groupby(sub_df.idxmax(), axis = 1).groups
d.values()
Out[110]: dict_values([[5], [2], [6, 7, 8], [3, 4]])

rawDescription: Finding the rows which has a unique column values in python


code:
import lxml.html
img = lxml.html.fragment_fromstring('<img src="old-value" />')
thm = "new-value"
img.set('src', thm)
a = etree.Element('a', href="#")
a.insert(0, img)
lxml.html.etree.tostring(a)

rawDescription: lxml python load html string without header and body and add element around targeted elements

description: Lxml python load html string without header and body and add element around targeted elements


rawDescription: pandas: Boolean indexing with multi index

description: Pandas: Boolean indexing with multi index


code: k = all(sorted(x) == sorted(y) for x, y in zip(li1, li2))

rawDescription: How to write parallel loop iterations in one line (lists have unequal lengths)

description: Write parallel loop iterations in one line (lists have unequal lengths)


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

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


code:
from ast import literal_eval

nums = literal_eval(raw_input('Enter some numbers: '))  # Type in [1, 2, 3]

rawDescription: user inputs ipython

description: User inputs ipython


code: SubElement(schedule, 'Sunday', {'open': '08:00', 'close': '17:00'})

rawDescription: What is the proper way to automate use of ElementTree in Python?


code: from __future__ import print_function

rawDescription: Variable printing in python

description: Variable printing in python


code:
user = relationship(User, backref=backref('user_to_groups', cascade='all, delete-orphan'))
group = relationship(Group, backref=backref('group_to_user', cascade='all, delete-orphan'))

rawDescription: How can SQLAlchemy association_proxy be used bi-directionally?


code:
parser = MultichoiceArgumentParser(formatter_class=MultichoiceFormatter)
parser.add_argument("-a", choices=["ABC", "XYZ"], nargs=2, action=MultichoiceAction)
print(parser.parse_args())

rawDescription: Python argparse second choices

description: Python argparse second choices


code:
def count_modify(string):
    d = {}
    for i in string:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return ''.join(str(x)+str(d[x]) for x in d)

rawDescription: Print custom string with character and character count without using python built-in methods


code:
L1 = ["the","end"]
bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
tuple(L1) in bigramslist

rawDescription: comparing lists with tuples in python

description: Comparing lists with tuples in python


code:
import dis
dis.dis('for x in it: pass')

rawDescription: Location of methods and classes in Python3 interpreter


code:
#!/usr/bin/env python
import fileinput
import sys
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('files', nargs='*', help='specify input files')
group = parser.add_mutually_exclusive_group()
group.add_argument('-o', '--output',
    help='specify the output file.  The default is stdout')
group.add_argument('-i', '--inplace', action='store_true',
    help='modify files inplace')
args = parser.parse_args()

if args.output and args.output != '-':
   sys.stdout = open(args.output, 'w')

for line in fileinput.input(args.files, inplace=args.inplace):
    process(line)

rawDescription: Consistent way to redirect both stdin & stdout to files in python using optparse


code:
data = rand(600,600)
extent = [.002, .018, 10, 80]

ax = gca()
ax.matshow(data, extent=extent, aspect='auto')
ax.get_xaxis().set_major_locator(matplotlib.ticker.LinearLocator(5))

plt.draw()

rawDescription: matplotlib 2d data with floating values ranges

description: Matplotlib 2d data with floating values ranges


code:
def authorize(self, session, uri, action):
    return True

rawDescription: How to limit Autobahn python subscriptions on a per session basis

description: Limit Autobahn python subscriptions on a per session basis


code:
def weekdays_to_string(days):
    # convert days to indexes
    day_indexes = {name:i for i, name in enumerate(calendar.day_name)}
    indexes = [day_indexes[d] for d in days]

    # find the places where sequential days end
    ends = [i + 1
            for i in range(len(indexes))
            if (indexes[(i + 1) % len(indexes)]) % 7 !=
               (indexes[(i) % len(indexes)] + 1) % 7]

    # wrap the days if necessary to get longest possible sequences
    split = ends[-1]
    if split != len(days):
        days = days[split:] + days[:split]
        ends = [len(days) - split + end for end in ends]

    # group the days in sequential spans
    spans = [days[begin:end] for begin, end in zip([0] + ends, ends)]

    # format as requested, with "to", "and", commas, etc.
    words = []
    for span in spans:
        if len(span) < 3:
            words.extend(span)
        else:
            words.append("%s to %s" % (span[0], span[-1]))
    if len(days) == 1:
        return words[0]
    elif len(days) == 2:
        return "%s and %s" % tuple(words)
    else:
        return ", ".join(words)

rawDescription: Python: Converting ('Monday', 'Tuesday', 'Wednesday') to 'Monday to Wednesday'


code:
import signal
...
signal.signal(signal.SIGALRM, alarm_handler)  # set the signal handler
signal.alarm(interval)                        # set the alarm
...
def alarm_handler(signum, stack):
    # call function
    function()

rawDescription: Python Time Problem

description: Python Time Problem


rawDescription: Numpy Routine for Computing Matrix Minors?


code:
from subprocess import Popen, PIPE
p = Popen(["grep", "VmRSS", "/proc/%s/status" % os.getpid()], shell=False, stdout=PIPE)
p.communicate()

rawDescription: Resource.getrusage() always returns 0

description: Resource.getrusage() always returns 0


code:
import collections

by_shape = collections.defaultdict(list)
for d in data:
    by_shape[d[4]].append(d[:4])

for key, val in by_shape.items():
    X, Y, Z, col = zip(*val)
    ax.scatter(X, Y, Z, c=col, marker=key)

rawDescription: How to change shapes/colours for 3d points with matplot3d

description: Change shapes/colours for 3d points with matplot3d


code:
df[df.Group =='A'].Age.hist()
df[df.Group =='B'].Age.hist()
df[df.Group =='C'].Age.hist()

rawDescription: Pandas: boxplot of one column based on another column


code:
make_callback = lambda i: lambda *args: self.yscroll(i, *args)
lb = Listbox(self, yscrollcommand = make_callback(i))

rawDescription: Which dynamically created object called the function?


code:
class Break(Text):
    def __init__(self):
        self.xml = """<w:br/>"""

    def _get_xml(self):
        return self.xml

rawDescription: Create docx via python (page breaks, tables) - possible?


code:
from itertools import compress
list(compress(f,sec))

rawDescription: Creating New Array when Second Array is > 0


code:
def validate(request, fields=None):
    return [
        f for f in fields
        if request.data[f] != check_validity(f)
    ]

rawDescription: Better way to know if there are any elements left to iterate in for loop in Python


code: reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))

rawDescription: Python - Comparing two lists

description: Python - Comparing two lists


rawDescription: How can I execute a command inputted by the user as a turtle command?

description: Execute a command inputted by the user as a turtle command


code:
elements = driver.find_elements_by_css_selector(".dropdown")
# or
elements = driver.find_elements_by_class_name("dropdown")
# elements[0]
# elements[1]
# ...

rawDescription: Selenium with Python - find elements of more than one css class


code:
a = np.array(v)
a.sum(axis=1)
a.sum(axis=1).argsort()
a[a.sum(axis=1).argsort()[::-1]]

rawDescription: Order a NXM Numpy Array according to cumulative sums of each sub-array


rawDescription: How to apply different aggregation functions to same column by using pandas Groupby

description: Apply different aggregation functions to same column by using pandas Groupby


code:
from itertools import product
from PIL import Image, ImageDraw

def closed_regions(image, test):
    """
    Return all closed regions in image who's pixels satisfy test.
    """
    pixel = image.load()
    xs, ys = map(xrange, image.size)
    neighbors = dict((xy, set([xy])) for xy in product(xs, ys) if test(pixel[xy]))
    for a, b in neighbors:
        for cd in (a + 1, b), (a, b + 1):
            if cd in neighbors:
                neighbors[a, b].add(cd)
                neighbors[cd].add((a, b))
    seen = set()
    def component(node, neighbors=neighbors, seen=seen, see=seen.add):
        todo = set([node])
        next_todo = todo.pop
        while todo:
            node = next_todo()
            see(node)
            todo |= neighbors[node] - seen
            yield node
    return (set(component(node)) for node in neighbors if node not in seen)

def boundingbox(coordinates):
    """
    Return the bounding box that contains all coordinates.
    """
    xs, ys = zip(*coordinates)
    return min(xs), min(ys), max(xs), max(ys)

def is_black_enough(pixel):
    r, g, b = pixel
    return r < 10 and g < 10 and b < 10

if __name__ == '__main__':

    image = Image.open('some_image.jpg')
    draw = ImageDraw.Draw(image)
    for rect in disjoint_areas(image, is_black_enough):
        draw.rectangle(boundingbox(region), outline=(255, 0, 0))
    image.show()

rawDescription: How to determine regions of pixels with a shared value using PIL

description: Determine regions of pixels with a shared value using PIL


code:
nodes = ("apples", "pears", "oranges")

digraphs = list(enumerate_digraphs(nodes))
layout = nx.random_layout(digraphs[0])

plt.figure(figsize=(20,30))
for i,g in enumerate(digraphs):
    plt.subplot(6,5,i+1)
    nx.draw_networkx(g, pos=layout)
    plt.gca().get_xaxis().set_visible(False)
    plt.gca().get_yaxis().set_visible(False)

rawDescription: Efficient storage and use of large sets of graphs in Python w/ networkX, the aim being inference across the graphs?


code:
[build]
build_base=my/build/dir

rawDescription: Is there a way to specify the build directory for py2exe


code:
from multiprocessing import Pool

def job(url):
    file_name = str(url.split('/')[-1])
    u = urllib2.urlopen(url)
    f = open(file_name, 'wb')
    f.write(u.read())
    f.close()

pool = Pool()
urls = ["ftp://ftp.sec.gov/{0:s}".format(f) for f in flist]
pool.map(job, urls)

rawDescription: Downloading a LOT of files using python

description: Downloading a LOT of files using python


code:
def foo(x, y = None):
    if y is None:
        x, y = x.x, x.y
    # do something at position (x, y)

rawDescription: Best way to "overload" function in python?

description: "overload" function in python


code:
import dataset

db = dataset.connect('sqlite:///:memory:')
persons_table = db['persons']
persons_table.insert(dict(name='Jolien'))

jobs_table = db['jobs']
jobs_table.insert(dict(place='Mall', start_date=2012, type=1, salary=20000, person_id=1))

rawDescription: Python: data on many people - how to structure?


code:
try:
    dt = datetime.strptime(line.split(" [", 1)[0], "%Y-%m-%d %H:%M:%S,%f")
except ValueError:
    dt = None

rawDescription: python to search files and parse using regular expression

description: Python to search files and parse using regular expression


code: {{ form.as_p }}

rawDescription: how to create check box and display it in templates

description: Create check box and display it in templates


code:
import subprocess

# Start pipe with other file
p = subprocess.Popen("./invoked.py", stdout=subprocess.PIPE, stdin=subprocess.PIPE)

# Send a value to the other file
p.stdin.write("Value!\n")

# Print the result coming from the other file
print(p.stdout.read())

description: Python subprocess.stdout.readline doesn't


code:
class ScoreFact( object ):
    def __init__( self, year, player, team, score ):
        self.year= year
        self.player= player
        self.team= team
        self.score= score
        years[self.year].append( self )
        players[self.player].append( self )
        teams[self.team].append( self )

rawDescription: Python data structure recommendation?

description: Python data structure recommendation


rawDescription: Pandas EWMA not working as expected

description: Pandas EWMA not working as expected


code:
import requests
from bs4 import BeautifulSoup

response = requests.get('https://familysearch.org/pal:/MM9.1.1/KH21-211')
soup = BeautifulSoup(response.content, 'lxml')

soup.find(text='Religion:').parent.find_next_sibling('td').get_text(strip=True)

rawDescription: BeautifulSoup Python script no longer working for mining a simple field


code: print(a, "is your number.")

rawDescription: Need assistance on Print function

description: Need assistance on Print function


code:
from collections import OrderedDict
import csv
with open('test.csv','r') as f:
    reader = csv.reader(f)
    headerlist = next(reader)
    csvlist = []
    for row in reader:
            d = OrderedDict()
            for i, x in enumerate(row):
                    d[headerlist[i]] = x
            csvlist.append(d)

import json
with open('test.json','w') as f:
    json.dump(csvlist,f)

rawDescription: Python csv to json column order

description: Python csv to json column order


rawDescription: Convert a string in a few int between commas in python


code:
last_v = np.dot(np.ones((N,1)),ainf)
np.linalg.norm(v - last_v, 2)
np.linalg.norm(v - last_v, 2) <= v_quadratic_error

rawDescription: PageRank python implementation, algorithm


code:
import itertools
itertools.combinations('abcd',2)
list(itertools.combinations('abcd',2))
[''.join(x) for x in itertools.combinations('abcd',2)]

rawDescription: Is there a math nCr function in python?

description: Is there a math nCr function in python


rawDescription: Exception Value: list indices must be integers, not str


rawDescription: Finding text in a string matching patterns


rawDescription: Python functions in Mako templates (not in module-level blocks)


code:
all([True, True, True])
all([True, True, True, False])
all([True, True, True, 1])
all([True, True, True, 0])
all([True, 1, True, 0])

rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
def verify_permissions(request, purpose):
  user = request.user
  sid = request.POST.get('subscription_id')
  try:
    sub = Subscription.objects.get(id=sid)
  except ObjectDoesNotExist:
    return (False, [(purpose, 'Given subscription does not exist.')])
  if sub.user != user:
    return (False, [(purpose, 'Invalid permission.')])
  return (True,)

def subscribe(request):
  result = verify_permissions(request, 'subscription')
  if result[0]: sub.save()
  return ajax_response(*result)

rawDescription: how should i refactor a piece of code that is present in many different functions, but has return statement in it

description: How should i refactor a piece of code that is present in many different functions, but has return statement in it


code:
def find_ancestors(resource):
    ancestors = [resource]
    while hasattr(ancestors[-1], '__parent__'):
        ancestors.append(ancestors[-1].__parent__)
    return ancestors

rawDescription: Pythonic shortcut (syntax sugar) for nested self.__parent__.__parent__


code:
if re.findall(dia, line):
    pass

rawDescription: use variable inside regex python

description: Use variable inside regex python


code:
args = parser.parse_args()
if not args.inputdir:
    parser.error('Please specify an inputdir with the -i or --inputdir option')

rawDescription: How to make a short and long version of a required argument using Python Argparse?

description: Make a short and long version of a required argument using Python Argparse


code:
field = {
    'headers': [u'Birthday:', u'Education', u'Job', u'Child Sex'],
    'rows': [[datetime.date(2012, 4, 6), u'A1', u'job1', u'M']
            ,[datetime.date(2012, 4, 27), u'A2', u'job2', u'F']]
}

rawDescription: Dictionary As Table In Django Template

description: Dictionary As Table In Django Template


rawDescription: Python: How to countdown a number, and append that countdown to a list


rawDescription: How can I select a certain value based on 2(or more) other values in a pandas dataframe

description: Select a certain value based on 2(or more) other values in a pandas dataframe


code:
with open('spam.json') as f:
    new_dict = defaultdict(list)
    for row in f:
        thing = json.loads(row)
        new_dict[thing["id"]].extend(thing["ua"])
with open('eggs.json', 'w') as f:
    for id, ua in new_dict.items(): # use iteritems in Python 2.x
        thing = {'id': id, 'ua': ua}
        f.write(json.dumps(thing) + '\n')

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
from sqlalchemy import TypeDecorator, type_coerce, String, or_

class NullComparisons(TypeDecorator):
    impl = String

    class comparator_factory(TypeDecorator.Comparator):
        def __ne__(self, other):
            expr = type_coerce(self.expr, String)
            return or_(expr == None, expr != other)

rawDescription: NULL safe inequality comparisons in SQL Alchemy?


code:
class BSTNode:
    def __init__(self, x, L=None, R=None):
        self.data = x
        self.left = L
        self.right = R

    def inOrder(self):
        ret = []
        if self.left: ret.append(self.left.inOrder())
        ret.append(self.data)
        if self.right: ret.append(self.right.inOrder())
        return ret

    def preOrder(self):
        ret = []
        ret.append(self.data)
        if self.left: ret.append(self.left.preOrder())
        if self.right: ret.append(self.right.preOrder())
        return ret

    def postOrder(self):
        ret = []
        if self.left: ret.append(self.left.postOrder())
        if self.right: ret.append(self.right.postOrder())
        ret.append(self.data)
        return ret

rawDescription: Output BST in Nested Form

description: Output BST in Nested Form


code:
df2 = pd.pivot_table(df.groupby('Transaction').size().reset_index(), index=0, values='Transaction', aggfunc=len).reset_index()
df2.columns = ("Count_Products", "Count_Transactions")

rawDescription: Python Pandas: Re pivot or re groupby using the values as index


code:
x = 0
user_class_instance = user_class(0)
result = lib_func(user_class_instance, param1)

rawDescription: Python: Passing function with arguments to a function


code:
#command all workers to consume from the 'dynamic_queue' queue
app.control.add_consumer('dynamic_queue', reply=True)

# command specific workers
app.control.add_consumer('dynamic_queue', reply=True, destination=[w1@example])

rawDescription: Celery worker: How to consume from all queues?


code: tarfiles = [fname for fname in dirlist if fname.endswith(('.tgz','.tar'))]

rawDescription: Assigning elements from a for loop to another list


code: result = 'weekly_' + '_'.join(map(str, args.weeks))

rawDescription: How to pass flexible amount of arguments using getopt in python?

description: Pass flexible amount of arguments using getopt in python


rawDescription: Dictionaries in Python

description: Dictionaries in Python


code:
while True:
    flag, frame = capture.read()
    cv2.imshow("Camera", frame)
    key_pressed = cv2.waitKey(10)
    if key_pressed == 27:                           #Escape key
        break
    writer.write(frame)
cv2.destroyAllWindows()

rawDescription: How do I use the FPS argument in cv2.VideoWriter?

description: Use the FPS argument in cv2.VideoWriter


code: df.index = pd.to_datetime(df.index)

rawDescription: Pandas-mean along dataframe.index (hour, minute) for a dataframe with a large amount of data (months) (Python)


code: t = threading.Thread(target=wrapped_worker, on_close=on_done)

rawDescription: Python threading on close callback

description: Python threading on close callback


rawDescription: Search all drives for a file

description: Search all drives for a file


code:
import hashlib
s = 'something to hash'
sb = s.encode("utf8")
hashlib.md5(sb)
hashlib.md5(sb).hexdigest()
hashlib.sha1(sb).hexdigest()

rawDescription: Simple programming language with a md5/sha1 hash command?


code: ask_ok('OK to overwrite the file?', 2)

rawDescription: Passing in arguments to command line (PYTHON)


code: output = list(zip(list1, list2, list3))

rawDescription: How to compare three list /guidance on classes

description: Compare three list /guidance on classes


code:
myrect = pygame.Rect(0, 0, 10, 10)
another = pygame.Rect(5, 5, 10, 10)
print(myrect.colliderect(another)) # 1

rawDescription: How to Make the Ball Bounce only if it Hits the Paddle in Python, Pygame (Breakout Recreation)


rawDescription: Using pysqlcipher with SqlAlchemy?

description: Using pysqlcipher with SqlAlchemy


rawDescription: Make a number more probable to result from random


rawDescription: Saving data in pickle

description: Saving data in pickle


code:
class VerbTestForm(forms.ModelForm):
    # Your code ...
    class Meta:
        # Your code ...

        widgets = {
            'answer': forms.TextInput(attrs={'placeholder': tip.tip}),
        }

rawDescription: Setting an example answer in a text input field


code:
import re
p = re.compile(r'(?:^|(?<=\n))\d+\s+credits[]\s\S]*?(?=\n\d+\s+credits|$)')
test_str = "3 credits in Philosophical Perspectives\nPHIL 101L\nPHILOSOPHICAL PERSPECTIVES\nB\n3\nFall 2014\nStudent View\n3 credits in Fine Arts\nART 160L\nHIST WEST ART I\nB+\n3\nFall 2014\n3 credits in History\nStill Needed:\nClick here to see classes that satisfy this requirement.\n3 credits in Literature\nENG 201L\nINTRO LINGUISTIC\nIP\n(3)\nSpring 2016\n3 credits in Math\nStill Needed:\nClick here to see classes that satisfy this requirement.\n3 credits in Natural Science\nBIOL 225L\nTOPICS IN NUTRITION\nA-\n3\nSpring 2015\n3 credits Ethics/Applied Ethics/Religious Studies\nREST 209L\nWORLD RELIGIONS\nA-\n3\nSpring 2015\n3 credits in Social Science\nECON 104L\nPRINC MACROECONOM\nT\n3\nFall 2014"

re.findall(p, test_str)

rawDescription: Regex with multiple lines

description: Regex with multiple lines


code: p5 = axScatter.plot((0, 1), "r--")

rawDescription: How to draw line inside a scatter plot

description: Draw line inside a scatter plot


code:
chunkFromFile = bytes((123,45,0,67,89))
chunkFromFile
chunkFromFile.split(b'\x00')
chunkFromFile.split('\x00')

rawDescription: Python 3 null terminated string to list?

description: Python 3 null terminated string to list


code:
subs[Symbol('almost_meter')] = 0.9*u.meter
sympify('almost_meter').subs(subs)

rawDescription: How to parse and simplify a string like '3cm/µs² + 4e-4 sqmiles/km/h**2' treating physical units correctly?

description: Parse and simplify a string like '3cm/µs² + 4e-4 sqmiles/km/h**2' treating physical units correctly


code:
import re
# Dictionary to hold the results
results = {}
# Break-up the file text to get the names and their associated data.
# filetext2.split('\n\n') breaks it up into individual data blocks (one per person).
# Mapping to str.splitlines breaks each data block into single lines.
for name, *data in map(str.splitlines, filetext2.split('\n\n')):
    # See if the name matches our pattern.
    if re.match('[A-Za-z]*\d{5}:', name):
        # Add the name and the relevant data to the file.
        # [:-1] gets rid of the colon on the end of the name.
        # The list comprehension gets only the file names from the data.
        results[name[:-1]] = [x for x in data if x.endswith('.zip')]

rawDescription: Match all names with exactly 5 digits at the end


code:
import sys
from PyQt4 import QtGui, QtCore
# from PySide import QtGui, QtCore
import urllib
from bs4 import BeautifulSoup

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.text = '?????'
        self.medal_update()
        self.my_timer = QtCore.QTimer()
        self.my_timer.timeout.connect(self.medal_update)
        self.my_timer.start(60000) #1 min intervall

        self.setGeometry(300, 300, 400, 200)
        self.setWindowTitle('Draw text')
        self.setWindowIcon(QtGui.QIcon('web.png'))
        self.show()

    def medal_update(self):
        html = urllib.urlopen("http://olympics.cbc.ca/medals/index.html")
        soup = BeautifulSoup(html)
        Rank = soup.find(cns='Canada').find_previous('td').find_previous('td').text
        Rank = int(Rank)
        Rankend='st'
        if Rank==1:
            Rankend='st'
        elif Rank==2:
            Rankend='nd'
        elif Rank==3:
            Rankend='rd'
        elif Rank > 3:
            Rankend='th'
        else:
            Rankend='dey more dan 10th'
        Gold = soup.find(text='CAN').find_next('td').text
        Silver = soup.find(text='CAN').find_next('td').find_next('td').text
        Bronze = soup.find(text='CAN').find_next('td').find_next('td').find_next('td').text
        self.text = ''
        self.text += ("Canada is in " + str(Rank) + str(Rankend) + ' Place' + '\n')
        self.text += ('They Have ' + Gold + ' Gold' + '\n')
        self.text +=('They Have ' + Silver + ' Silver' + '\n')
        self.text +=('They Have ' + Bronze + ' Bronze' + '\n')
        self.update()

    def paintEvent(self, event):

        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawText(event, qp)
        qp.end()

    def drawText(self, event, qp):

        qp.setPen(QtGui.QColor(200, 100, 3))
        qp.setFont(QtGui.QFont('Decorative', 20))
        qp.drawText(event.rect(), QtCore.Qt.AlignCenter, self.text)

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt4 Constantly Updating Text

description: PyQt4 Constantly Updating Text


code: fig.subplots_adjust(right=0.9, left=0.1, top=0.9, bottom=0.1, wspace=0.2)

rawDescription: How to align subplot with specified size?

description: Align subplot with specified size


rawDescription: Access index in pandas.Series.apply

description: Access index in pandas.Series.apply


code: binary = cv2.inRange(gray_image, d, u)

rawDescription: Binarize pixels by value

description: Binarize pixels by value


code:
def reset_cache(request, view='dyn_css', args=None):
    from django.core.cache import cache
    from django.utils.cache import get_cache_key

    if args is None:
        path = reverse(view)
    else:
        path = reverse(view, args=args)

    request.path = path
    key = get_cache_key(request)
    if key in cache:
        cache.delete(key)

rawDescription: Customize CSS from Code (Django)

description: Customize CSS from Code (Django)


code:
from collections import Counter
a = ['a', 'a', 'b', 'c', 'c', 'c', 'd', 'e', 'f']
b = ['a', 'b', 'c', 'd', 'e', 'f']
Counter(a) - Counter(b)
list((Counter(a) - Counter(b)).elements())

rawDescription: Remove elements of one list from another, while keeping duplicates


code:
while p:
   e = p.pop()
   if e in p:
      return True
return False

rawDescription: Python Lists: How can I search for another element or duplicate item in a list


code:
@some_decorator
def some_func():
    ...

rawDescription: Should Python's property() be used as a decorator or saved to a variable?


rawDescription: Delete list via referent ? > Was : How do you alias variable in Python ? or similar?


code: nvrp = NumberValueRangeProcessor(valno, 'value_range:', True)

rawDescription: Search range of int values using djapian


code:
T = '(x in A or x in B) and not(x in A and x in C)'
sets = {'A': {0, 1}, 'B': {0, 2}, 'C': {1, 3}}
universe = {x for s in sets.values() for x in s}
{x for x in universe if eval(T, sets, {'x': x})}

rawDescription: Parsing and computing boolean set definitions


code:
DOWNLOADER_MIDDLEWARES = {
    'myproject.middlewares.IgnoreDuplicates': 543,
    'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 500,
}

rawDescription: Using Middleware to ignore duplicates in Scrapy


rawDescription: Updating a dict which is stored in an array


code:
import numpy as np

def selectEdge(positions, positions_u, originalMat, selectedMat):
    for ele in positions:
        for ele_u in positions_u:
            selectedMat[ele][ele_u] += originalMat[ele][ele_u]
            selectedMat[ele_u][ele] += originalMat[ele_u][ele]
    return selectedMat

def alt_selectEdge(positions, positions_u, originalMat, selectedMat):
    X, Y = positions[:,None], positions_u[None,:]
    selectedMat[X, Y] += originalMat[X, Y]
    selectedMat[Y, X] += originalMat[Y, X]
    return selectedMat

N, M = 100, 50
positions = np.random.choice(np.arange(N), M, replace=False)
positions_u = np.random.choice(np.arange(N), M, replace=False)
originalMat = np.random.random((N, N))
selectedMat = np.zeros_like(originalMat)

rawDescription: Speed up getting edge matrix by index with numpy array


rawDescription: Convert a tuple to a string that is that tupple


code: from mytoplevel.mydeploymenttasks import installApplicationTask

rawDescription: Structuring a fabric project with namespaces


rawDescription: sort an array by row in pyhton

description: Sort an array by row in pyhton


code: allzeniths, allazimuths = zip(*itertools.product(zeniths, azimuths))

rawDescription: Parallelise nested for-loop in IPython

description: Parallelise nested for-loop in IPython


code:
gb = df.groupby(['extra'], as_index=False)
df = gb.agg({'Starts': np.min, 'Ends': np.max}, as_index=False)

rawDescription: Taking Min and Max of Contigous Rows in a Pandas Dataframe


code:
import os
myconst1 = os.environ['MY_DAILY_CONST_1']
...

rawDescription: How to efficiently define daily constant?

description: Efficiently define daily constant


code:
xyz.py
import argparse

def parser(prefix):
    result = argparse.ArgumentParser(add_help=False)
    result.add_argument("--%s-cat"%prefix, action='store_true')
    result.add_argument("--%s-dog"%prefix, action='store_true')
    return result

rawDescription: How to specify multiple instances of same type of parent parser in argparse

description: Specify multiple instances of same type of parent parser in argparse


code:
#-- Remove closest point ---------------------
mask = np.squeeze(dist) != dist.min(axis=1)
filtered = data[mask]

# Once again, let's reshape things back to the original shape...
filtered = filtered.reshape(data.shape[0], -1, data.shape[2])

rawDescription: NumPy: Execute function over each ndarray element


rawDescription: No Column Names in pandas python

description: No Column Names in pandas python


rawDescription: Pandas: Selection with MultiIndex

description: Pandas: Selection with MultiIndex


code:
mouseX, mouseY = win.getMouse() #Myro module, win = Window object
a = Point(662,200)
b = Point(1,1)
print(inTriangle(a, Point(661,156), Point(633,217), Point(688,218))) #TRUE!
print(inTriangle(b, Point(661,156), Point(633,217), Point(688,218))) #FALSE!
triangle = [Point(661, 156), Point(633, 217), Point(688, 218)]
if inTriangle(Point(mouseX, mouseY), triangle[0], triangle[1], triangle[2]):
    print("clicked up")

rawDescription: Verifying Mouse Position Within Triangle - Python


code:
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render, redirect
from haystack.forms import ModelSearchForm, SearchForm
from haystack.views import SearchView
from search.models import SearchQuery, SearchTerm
import datetime

def search(request):
    if 'page' not in request.GET :
        try :
            st, created = SearchTerm.objects.get_or_create(query=request.GET['q'])
            sq = SearchQuery()
            sq.term = st
            sq.user = request.user
            sq.when = datetime.datetime.now()
            sq.save()
        except :
            pass

    view = SearchView()
    return view(request)

rawDescription: Logging Django Haystack search keyword

description: Logging Django Haystack search keyword


code:
import numpy as np
a = [1, 2, 3]
v = [0, 1, 0.5]
np.correlate(a, v, mode="full")

rawDescription: How multiarray.correlate2(a, v, mode) is actually implemented?


rawDescription: JSON data recognized as a string field instead of integer


code:
def predict(x, data, kernel, params, sigma, t):
    k = [kernel(x, y, params) for y in data]
    Sinv = np.linalg.inv(sigma)
    y_pred = np.dot(k, Sinv).dot(t)
    sigma_new = kernel(x, x, params) - np.dot(k, Sinv).dot(k)
    return y_pred, sigma_new

rawDescription: Gaussian Process scikit-learn - Exception


code:
from operator import itemgetter
b = map(itemgetter(0), a)

rawDescription: Get the nth element from the inner list of a list of lists in Python


code: df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

rawDescription: Add new column in Pandas DataFrame Python


rawDescription: Most efficient way to recode these multiple if statements


code: (st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))

rawDescription: What's the best way to find the closest matching type to an existing type?


code:
d = UnsortableOrderedDict([
    ('z', 0),
    ('y', 0),
    ('x', 0)
])
yaml.dump(d, default_flow_style=False)

rawDescription: Can PyYAML dump dict items in non-alphabetical order?


rawDescription: what is the best way to represent a char in its bits representation(Python)

description: What is the best way to represent a char in its bits representation(Python)


code:
import numpy as np
np.random.seed(2015)

def getslice(G, axes):
    idx = [0 if i in axes else slice(None) for i in range(G.ndim)]
    return G[idx]

G = np.random.randint(10, size=(2,2,2,2,2,))
assert np.allclose(getslice(G, [0,2]), G[0,:,0,:,:])

rawDescription: How do I make a function that slices an array depending on parameters

description: Make a function that slices an array depending on parameters


code: os.chown(path, uid, gid)

rawDescription: python subprocess as normal user

description: Python subprocess as normal user


rawDescription: Assign scientific notation to variable in Python


code: Directionalindicator(2, [1, 2, 2, 1, 2, 1])

rawDescription: Class based directional indicator

description: Class based directional indicator


code: A() # creates a new object I call a

rawDescription: Why the id of an object would change depending on the line in the python shell


code:
d = dict()

for i in xrange(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1

rawDescription: Check if a given key already exists in a dictionary


code:
for i in range(len(content)):
    content[i] = ...

rawDescription: Why is my code printing incorrectly to the text file?


code:
"""All visualization functionality is collected here."""
from pylab import plot

# ToDo: create proper documentation
def simple_link(t, ndx, level):
    """Simple_link is just a minimal example to demonstrate what can be
    achieved when it's called from _grouper.tree.traverse for each link.
    - t, tree instance
    - ndx, a pair of (from, to) indicies
    - level, of from, i.e. root is in level 0
    """
    plot(t.points[0, ndx], t.points[1, ndx])
    if 0== level:
        plot(t.points[0, ndx[0]], t.points[1, ndx[0]], 's')
    if t.is_leaf(ndx[1]):
        plot(t.points[0, ndx[1]], t.points[1, ndx[1]], 'o')

# ToDO: implement more suitable link visualizers
# No doubt, this will the part to burn most of the dev. resources

if __name__ == '__main__':
    # ToDO: implement tests
    pass

rawDescription: How do I create a radial cluster like the following code-example in Python?

description: Create a radial cluster like the following code-example in Python


code:
import socket
def dist(a, b):
    def to_num(addr):
        # parse the address string into integer quads
        quads = map(ord, socket.inet_aton(addr))
        # spread the quads out
        return reduce(lambda x,y: x * 0x10000 + y, quads)
    return abs(to_num(a) - to_num(b))

rawDescription: Find the network distance between two IPv4 addresses (not geographic distance)


rawDescription: With argparse are subparsers inherently mutually exclusive?


code:
input = {
    "something" : [{"one":"200"}, {"three":"400"}, {"one":"100"}, {"two":"800"}],
    "foo" : [{"a" : 100, "b" : 200}, {"a" : 300, "b": 400}],
}

def counterize(x):
    return Counter({k : int(v) for k, v in x.iteritems()})

counts = {
    k : sum((counterize(x) for x in v), Counter())
    for k, v in input.iteritems()
}

rawDescription: Python Collections Counter for a List of Dictionaries


code: results = [action for i in range(N)]

rawDescription: How does xrange() work inside of a while loop?


code:
def lenRecur(s):

    count = [0]

    # ...

    def leng(s):
        if len(s)==0:
            return count[0]
        else:
            count[0] += 1
            return lenIter(s[1:])

rawDescription: Global variables in recursion. Python

description: Global variables in recursion. Python


code:
ends
ends.index = ends.index + 1
ends

rawDescription: Pandas, simple add one month to a datetime column in a dataframe


code:
numbers = []
labels = []
with open('myfile.txt') as fobj:
    for line in fobj:
        if not line.strip():
            continue
        label, number = line.split(',')
        numbers.append(int(number.strip()[:-1]))
        labels.append(label[2:-1])

rawDescription: how can i plot histogram like this?

description: Plot histogram like this


code:
match = re.search(r"field2:\s(.*)", subject)
if match:
    result = match.group(1)
else:
    result = ""

rawDescription: Simple python regex, match after colon

description: Simple python regex, match after colon


code: pivoted

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


code:
from __future__ import print_function # I'm on Python 2.7
from threading import Thread

Thread(target=(lambda: print('test') == print('hello'))).start()

rawDescription: Is it possible to use an inline function in a Thread call?


code:
from itertools import permutations, combinations

def permut_with_pivot(sequence, pivot=0):
    pivot_indexes = set()
    seq_len = 0
    def yield_non_pivots():
        nonlocal seq_len
        for i, item in enumerate(sequence):
            if item != pivot:
                yield item
            else:
                pivot_indexes.add(i)
        seq_len = i + 1

    def fill_pivots(permutation):
        for pivot_positions in combinations(range(seq_len), len(pivot_indexes)):
            sequence = iter(permutation)
            yield tuple ((pivot if i in pivot_positions else next(sequence)) for i in range(seq_len))

    for permutation in permutations(yield_non_pivots()):
        for filled_permutation in fill_pivots(permutation):
            yield filled_permutation

rawDescription: How to generate permutations of a list without “moving” zeros. in Python

description: Generate permutations of a list without “moving” zeros. in Python


code: step_1 = sd(odds(st)) - sd(evens(st))

rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
class MyBaseFormSet(BaseFormSet):
    def clean(self):
        """Checks that only one instance is current"""
        if any(self.errors):
            # Don't bother validating the formset unless each form is valid on its own
            return
        count = 0
        for form in self.forms:
            if form.cleaned_data['current']:
                count += 1
                if count > 1:
                    raise forms.ValidationError("Only one item can be current")

rawDescription: django inlineformset, how to allow only 1 boolean field to be true at a time?

description: Django inlineformset, how to allow only 1 boolean field to be true at a time


code:
#!/usr/bin/env python
import subprocess
import sys
import time

start = time.time()
cmd = sys.executable + " -c 'import time; time.sleep(2)' &"
subprocess.check_call(cmd, shell=True)
assert (time.time() - start) < 1

rawDescription: Python subprocess .check_call vs .check_output


code:
jsonip.com
from json import load
from urllib2 import urlopen

my_ip = load(urlopen('http://jsonip.com'))['ip']

rawDescription: How can I get the public IP using python2.7?

description: Get the public IP using python2.7


rawDescription: Extract a larger slice than the numpy array's size


code:
class DraggableLegend:
    def __init__(self, legend):
        self.legend = legend
        self.gotLegend = False
        legend.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
        legend.figure.canvas.mpl_connect('pick_event', self.on_pick)
        legend.figure.canvas.mpl_connect('button_release_event', self.on_release)
        legend.set_picker(self.my_legend_picker)

    def on_motion(self, evt):
        if self.gotLegend:
            dx = evt.x - self.mouse_x
            dy = evt.y - self.mouse_y
            loc_in_canvas = self.legend_x + dx, self.legend_y + dy
            loc_in_norm_axes = self.legend.parent.transAxes.inverted().transform_point(loc_in_canvas)
            self.legend._loc = tuple(loc_in_norm_axes)
            self.legend.figure.canvas.draw()

    def my_legend_picker(self, legend, evt):
        return self.legend.legendPatch.contains(evt)

    def on_pick(self, evt):
        if evt.artist == self.legend:
            bbox = self.legend.get_window_extent()
            self.mouse_x = evt.mouseevent.x
            self.mouse_y = evt.mouseevent.y
            self.legend_x = bbox.xmin
            self.legend_y = bbox.ymin
            self.gotLegend = 1

    def on_release(self, event):
        if self.gotLegend:
            self.gotLegend = False

rawDescription: How to create a draggable legend in matplotlib?

description: Create a draggable legend in matplotlib


code:
print(type(typ))
print(dir(typ))
print(type(msgnums))
print(dir(msgnums))

rawDescription: find all items in list object

description: Find all items in list object


rawDescription: R dcast equivalent in python pandas

description: R dcast equivalent in python pandas


code:
df_new = pd.melt(df,id_vars=['Season', 'Location'], value_vars=['Count_2014', 'Count_2015'],
        var_name='Year',
        value_name='Count')

rawDescription: Reshape Pandas Dataframe

description: Reshape Pandas Dataframe


code:
from collections import defaultdict

outerdict = defaultdict(dict)
with open(filename) as infh:
    for line in infh:
        name, _, type_, *values = line.split()
        outerdict[name][type_] = [int(i) for i in values]

rawDescription: Python idiom for creating dict of dict of list


code:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage

new = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach( MIMEText("reply body text", "plain") )
body.attach( MIMEText("<html>reply body text</html>", "html") )
new.attach(body)

new["Message-ID"] = email.utils.make_msgid()
new["In-Reply-To"] = original["Message-ID"]
new["References"] = original["Message-ID"]
new["Subject"] = "Re: "+original["Subject"]
new["To"] = original["Reply-To"] or original["From"]
new["From"] = "me@mysite.com"

rawDescription: How do I reply to an email using the Python imaplib and include the original message?

description: Reply to an email using the Python imaplib and include the original message


code: file_count_string.set("Input Directory: " + str(file_count) + " files.")

rawDescription: Python: 'Refresh' specific variables within a script


code:
with open('results.txt', 'wb') as r:
    with open('updates.txt', 'rb') as u:
        for line in u.readlines():
            if '-'*51 in line:
                r.write(line)
            else:
                if any(field in line for field in ['Timestamp', 'Peer AS Number', 'Local AS Number', 'Peer IP Address', 'Local IP Address','MRTHeader']):
                    r.write(line)

rawDescription: Python - String manipulation by specific delimeter and write in text file


code:
def get_word_counts(text, wanted):
    counts = {}; # The number of times a wanted item was read

    # Dictionary mapping word lengths onto wanted items
    #  (in the form of a dictionary where keys are wanted items)
    lengths = {};

    # Find the number of times each wanted item occurs
    for item in wanted:
        matches = re.findall('\\b' + item + '\\b', text);

        counts[item] = len(matches)

        l = len(item) # Length of wanted item

        # No wanted item of the same length has been encountered
        if (l not in lengths):
            # Create new dictionary of items of the given length
            lengths[l] = {}

        # Add wanted item to dictionary of items with the given length
        lengths[l][item] = 1

    # Get and sort lenths of wanted items from largest to smallest
    keys = lengths.keys()
    keys.sort(reverse=True)

    # Remove overlapping wanted items from the counts working from
    #  largest strings to smallest strings
    for i in range(1,len(keys)):
        for j in range(0,i):
            for i_item in lengths[keys[i]]:
                for j_item in lengths[keys[j]]:
                    #print str(i)+','+str(j)+': '+i_item+' , '+j_item
                    matches = re.findall('\\b' + i_item + '\\b', j_item);

                    counts[i_item] -= len(matches) * counts[j_item]

    return counts

rawDescription: Count strings in a file, some single words, some full sentences


code:
import pandas as pd
df = pd.DataFrame(
    {'score': [5, 8], 'sentence': ["This is a sentence.", "Another sentence sentence?"]})
df['sentence'] = df['sentence'].str.findall(r'\w+')

longframe = pd.DataFrame([(row.score, word) for row in df.itertuples()
                          for word in row.sentence],
                         columns=['score', 'word'])
score = longframe.groupby('word')['score'].sum()
count = longframe['word'].value_counts()
result = pd.DataFrame({'score':score, 'count':count, 'normalized_score':score/count})
result = result.reset_index()
result = result.rename(columns={'index':'word'})
print(result)

rawDescription: How do I convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores?

description: Convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores


code:
price = df['PRICE'].resample('D', how='ohlc').reset_index()
price

rawDescription: How do you convert time series data with pandas and show graph via highstock

description: Convert time series data with pandas and show graph via highstock


code:
replys = pd.read_csv('Replys.csv')
users = pd.read_csv('Users.csv')

rawDescription: Query CSV files maintaining foreign key relationship? Is this possible?


code:
from tkinter import *

class FocusFrame(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.bind("<1>", lambda event: self.focus_set())

top = Tk()

Entry(top, width="20").pack()
FocusFrame(top, width=200, height=200, bg='blue').pack()
FocusFrame(top, width=200, height=200, bg='green').pack()
FocusFrame(top, width=200, height=200, bg='yellow').pack()

top.mainloop()

rawDescription: Remove focus from Entry widget

description: Remove focus from Entry widget


code:
def cell_was_clicked(self, row, column):
    print("Row %d and Column %d was clicked" % (row, column))
    item = self.table.itemAt(row, column)
    self.ID = item.text()

rawDescription: Retrieving cell data from a selected cell in a tablewidget


code: re.search(r'^[^,]*', s).group()

rawDescription: working with regex

description: Working with regex


rawDescription: Why does wxPython panel masks key down event?


code: data = urllib2.urlopen(url).read()

rawDescription: Process File in memory using python

description: Process File in memory using python


code: euro = unichr(0x20ac)

rawDescription: how to convert currency in python file

description: Convert currency in python file


code:
a
mask_fewest(a,2,10)

rawDescription: Count number of elements in numpy ndarray


code:
from multiprocessing import Pool
def myfunc(x):
    return [i for i in range(x)]

A = []
def mycallback(x):
    print('mycallback is called with {}'.format(x))
    A.extend(x)

pool=Pool()
r = pool.map_async(myfunc, (1,2), callback=mycallback)
r.wait()
print(A)

rawDescription: how does the callback function work in python multiprocessing map_async

description: How does the callback function work in python multiprocessing map_async


code:
data
sorted(data)

rawDescription: Sort datetime in double array list

description: Sort datetime in double array list


rawDescription: Python: Automatic object generation plus naming


code:
i = "\xd9\x88"
type(i)
type(i.encode('latin-1'))
print(i.encode('latin-1').decode('utf-8'))

rawDescription: representing \xd9\x88 (UTF-8 literal) in its arabic character و in Python

description: Representing \xd9\x88 (UTF-8 literal) in its arabic character و in Python


code: new_data = ['{0:02.0f}'.format(float(x)) for x in data]

rawDescription: Adding zero in front of a character in Python


code:
def main():
    rand = random.randint(1, 4)
    frame_count = 0
    frame_rate = 60
    start_time = 60
    running = True
    while running:
        total_seconds = start_time - (frame_count // frame_rate)
        minutes = total_seconds // 60
        seconds = total_seconds % 60
        output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds)

        screen.fill(BLACK)
        screen.blit(font.render(output_string, True, WHITE), (150, 110))
        pygame.display.flip()

        frame_count += 1
        clock.tick(frame_rate)

rawDescription: Pygame not displaying text

description: Pygame not displaying text


code: string1 = 'ac'

rawDescription: Python: place a characters in string

description: Python: place a characters in string


code:
(df.assign(closest=df.apply(lambda x: x.abs().argmin(), axis='columns'))
 .apply(lambda x: x[x['closest']], axis='columns'))

rawDescription: Selecting the value in a row closest to zero in a pandas DataFrame


code:
sql1 = '''SELECT *
FROM Dogs INNER JOIN Owners
ON Dogs.DogID = Owners.DogID
WHERE Dogs.DogID = ?
Order By Speed desc;
'''
c.execute(sql1, dogid)
...

rawDescription: How can you use python variables in an sql search

description: Use python variables in an sql search


code: random.sample(coordinaten, 20)

rawDescription: Python pick 20 random results from list

description: Python pick 20 random results from list


code: [word for word in word_tokenize(sent)]

rawDescription: Confused about priority between stemmer and pos tagger


code: one, two, three, four, five = l2

rawDescription: unpacking a list in python

description: Unpacking a list in python


code:
for index, item in enumerate(my_list):
   pass # do something

rawDescription: How do I remove an element from a list without using .remove

description: Remove an element from a list without using .remove


code: full_data = {'normal_data':[normal_data_list], 'extra_value': [extra_value_list], 'whatever':whatever_you_need}

rawDescription: Creating a dictionary of dictionaries in Python


code:
from collections import namedtuple
from itertools import groupby
import csv

data = []

a_tuple = namedtuple('x_change', ['Time', 'Change'])
another_tuple = namedtuple('y_change', ['Time', 'Change', 'id'])

data.append(a_tuple(6, 1))
data.append(a_tuple(2, 1))
data.append(another_tuple(5, 3, 2))
data.append(another_tuple(7, 1, 3))
data.append(a_tuple(5, 2))

data.sort(key=lambda x: type(x).__name__)

for k, g in groupby(data, lambda x: type(x).__name__):
    with open('{}.csv'.format(k), 'w', newline='') as f_output:
        csv_output = csv.writer(f_output)
        rows = list(g)
        csv_output.writerow(['Name'] + list(rows[0]._fields))
        for row in rows:
            csv_output.writerow([type(row).__name__] + list(row))

rawDescription: Pass list of different named tuples to different csv by tuple name


rawDescription: how to find frequency of the keys in a dictionary across multiple text files?

description: Find frequency of the keys in a dictionary across multiple text files


code:
for i in xrange(K.shape[0]):
    for j in xrange(K.shape[1]):

        print(i,j)
        '''create an r vector '''
        r=(i*distX,j*distY,z)

        for x in xrange(img.shape[0]):
            for y in xrange(img.shape[1]):
                '''create an ksi vector, then calculate
                   it's norm, and the dot product of r and ksi'''
                ksi=(x*distX,y*distY,z)
                ksiNorm=np.linalg.norm(ksi)
                ksiDotR=float(np.dot(ksi,r))

                '''calculate the integrand'''
                temp[x,y]=img[x,y]*np.exp(1j*k*ksiDotR/ksiNorm)

        '''interpolate so that we can do the integral and take the integral'''
        temp2=rbs(a,b,temp.real)
        K[i,j]=temp2.integral(0,n,0,m)

rawDescription: Need help vectorizing code or optimizing


code:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

rawDescription: How to work properly with django static files

description: Work properly with django static files


rawDescription: plotting a range of data that satisfies conditions in another column in matplotlib python

description: Plotting a range of data that satisfies conditions in another column in matplotlib python


code:
summaptime = timeit.timeit('mins=sum(map(lambda x, y: x * y, map(int, "2:40".split(":")), [60, 1]))', "s='02:40'", number=100000) / 100000
summaptime
summaptime/parsetime

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


rawDescription: Overflowing ints in python

description: Overflowing ints in python


code: y = 50*(math.sin(math.radians(x)))

rawDescription: How do I modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9?

description: Modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9


code:
from collections import Counter
print(list((Counter(['cat','dog','wolf']) & Counter(['pig','fish','cat'])).elements()))

rawDescription: How To Compare Items In Two Lists Python 3.3


code:
from itertools import zip_longest
a='AAAAAAAA'
b='GGGG'
[''.join(i) for i in zip_longest(a,b,fillvalue='')]

rawDescription: Zipping strings according to the longer string


rawDescription: Wait for data from one task in a second independently scheduled task


rawDescription: Select rows and subrows in pandas multiindex dataframe by condition


code:
#b.py
import a
print(lol)

rawDescription: What are all the ways to add an object to the local scope in Python?


rawDescription: How to mathematically subtract two lists in python?

description: Mathematically subtract two lists in python


code:
with open('outputfile.csv', 'wb') as outputfile:
    writer = csv.writer(outputfile)
    writer.writerows([n, min(values), max(values)] for n, v in species.iteritems() for values in (map(float, v),))

rawDescription: Obtain and store adjacent values from a .csv file (Python)


code:
for key, value in valuesA.items():
    valuesB[key] = valuesB.get(key, 0) + value

rawDescription: Merge dictionaries with key combinations


code: types.MethodType(f1, C(), C)

rawDescription: What is the difference between a function, an unbound method and a bound method?


code: from collections import OrderedDict

rawDescription: Python sort by values that are lists of numbers


code:
strings = input("type something : ")
while(True):
    MyString = []
    if strings == "stop": break
    for string in strings.split():
        for char in string:
            if(char.isalnum()): MyString.append(char)
        MyString.append(" ")
    print (''.join(MyString))
    strings = input("continue : ")

rawDescription: Converting a list into a string

description: Converting a list into a string


code: ArgSpec(args=['arg1'], varargs=None, keywords=None, defaults=('a default value',))

rawDescription: How to find out the default values of a particular function's argument in another function in Python?

description: Find out the default values of a particular function's argument in another function in Python


code: np.max(b,axis=1)[...,None] == b

rawDescription: Numpy: np.where function given argmax

description: Numpy: np.where function given argmax


code: cb.t_test("Ln(labor) +Ln(capital)=1")

rawDescription: Test the hypothesis test of Constant Return to scale for a cobb-douglas function:


code: has_1 = any(line == "1" for line in f)

rawDescription: How do I match a word if it starts with a nonalphanumeric character in Python?

description: Match a word if it starts with a nonalphanumeric character in Python


code:
def listspaces(str):
    return [i for i, c in enumerate(str) if c==' ']

rawDescription: python to php code conversion

description: Python to php code conversion


code:
s = SomeClass("mytest")
s.f2()
s.f2

rawDescription: Generic methods in python

description: Generic methods in python


code:
import pprint
pprint.pprint(d)

rawDescription: recursively traverse multidimensional dictionary, dimension unknown

description: Recursively traverse multidimensional dictionary, dimension unknown


rawDescription: How to add matrices in python

description: Add matrices in python


code:
a = self.center(a)
U, s, Vh = np.linalg.svd(a, full_matrices=False)

rawDescription: Basic example for PCA with matplotlib

description: Basic example for PCA with matplotlib


rawDescription: How can I directly access a file in a Python script?

description: Directly access a file in a Python script


code: lst = [j + k for j in s1 for k in s2]

rawDescription: Nested For Loops Using List Comprehension


code: appl.reset_index(inplace = True)

rawDescription: Retrieving .loc index values in pandas dataframe


code:
data
out

rawDescription: Numpy: Fix array with rows of different lengths by filling the empty elements with zeros


code:
a=np.zeros((3,3),int)
a[i]=1
a

rawDescription: Why does numpy indexing work differently in higher dimensions?


code: [''.join(e) for e in  izip(data, data[1:])]

rawDescription: Parse String every 2 letters

description: Parse String every 2 letters


code:
class string(str):
    def sayHello(self):
        print(self, "is saying 'hello'")

rawDescription: Add custom method to string object

description: Add custom method to string object


code:
timeit.timeit('[v for k, v in sorted(dictionary.iteritems())]', 'from __main__ import dictionary')
timeit.timeit('[d[key] for key in sorted(d)]', 'from __main__ import dictionary as d')

rawDescription: python : list of dictionary values by alphabetical order of keys

description: Python : list of dictionary values by alphabetical order of keys


code:
obj = Duck()

def say_something(keyword):
     return getattr(obj, keyword, None)

print(say_something('duck')())

rawDescription: How to iterate over class methods

description: Iterate over class methods


code:
import json

handler = open('main.txt', 'r')
data = json.loads(handler.read())

rawDescription: Storing Multiple responses in dictionaries


code: end += timedelta(hours=1)

rawDescription: How to naturally roll-over to the next day when adding hours to a datetime

description: Naturally roll-over to the next day when adding hours to a datetime


code:
def process_file(filename):
    reg = re.compile(r'([\w]{2,3}):\s') # Matches line header
    tmp = '' # Stored/cached data for mutliline string
    key = None # Current key
    data = {}

    with open(filename,'r') as f:
        for row in f:
            row = row.rstrip()
            match = reg.match(row)

            # Matches header or is end, put string to list:
            if (match or not row) and key:
                data[key] = tmp
                key = None
                tmp = ''

            # Empty row, next dataset
            if not row:
                # Prevent empty returns
                if data:
                    yield data
                    data = {}

                continue

            # We do have header
            if match:
                key = str(match.group(1))
                tmp = row[len(match.group(0)):]
                continue

            # No header, just append string -> here goes assumption that you want to
            # remove newlines, trailing spaces and replace them with one single space
            tmp += ' ' + row

    # Missed row?
    if key:
        data[key] = tmp

    # Missed group?
    if data:
        yield data

rawDescription: Python - reading data from file with variable attributes and line lengths


code:
from django.contrib.auth.models import User

class EmailOrUsernameModelBackend(object):
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

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

rawDescription: How to make customer's email as the username in UserCreationForm / User Model in Django?

description: Make customer's email as the username in UserCreationForm / User Model in Django


code:
def flatten(it):
    for x in it:
        if (isinstance(x, collections.Iterable) and
            not isinstance(x, str)):
            for y in flatten(x):
                yield y
        else:
            yield x

rawDescription: Python: Function to flatten generator containing another generator


rawDescription: Parsing "From:" field of an e-mail message in Python


code:
#!/usr/bin/env python

import sys
import time

sys.stdout.write("This is in a line")
# force flush as stdout is flushed by default on '\n'
sys.stdout.flush()
time.sleep(2)
# rewrite line and move to next
sys.stdout.write("\rThis is still in the same line\n")

rawDescription: how can avoid the output to look like a log(Python)

description: How can avoid the output to look like a log(Python)


rawDescription: string to list conversion in python

description: String to list conversion in python


code:
import itertools
import operator
import csv

outfile_path4 = 'input.csv'
outfile_path5 = r'my_output_folder\output.csv'
csv_contents = []

with open(outfile_path4, 'rb') as fin:
    dict_reader = csv.DictReader(fin)   # default delimiter is comma
    fieldnames = dict_reader.fieldnames # save for writing

    for line in dict_reader:            # read in all of your data
        csv_contents.append(line)         # gather data into a list (of dicts)

group = ['prot_desc','ident','country']
# input to itertools.groupby must be sorted by the grouping value
sorted_csv_contents = sorted(csv_contents, key=operator.itemgetter(*group))

for groupkey, groupdata in itertools.groupby(sorted_csv_contents, key=operator.itemgetter(*group)):
    with open(outfile_path5+'slice_{:s}.csv'.format(groupkey), 'wb') as fou:
        dict_writer = csv.DictWriter(fou, fieldnames=['pep_seq'], extrasaction='ignore')
        dict_writer.writeheader()
        dict_writer.writerows(groupdata)

rawDescription: How to slice a single CSV file into several smaller ones grouped by a field and deleting columns in the final csv's?

description: Slice a single CSV file into several smaller ones grouped by a field and deleting columns in the final csv's


Model: El Camino

WrapperName: Car Wrapper

rawDescription: Passing inherited object to a WCF service using JSON


code:
for key,value in abridged_data.items():
    abridged_data[key] = np.array(value)

rawDescription: Plotting with Numpy Arrays

description: Plotting with Numpy Arrays


rawDescription: Negative RegEx pattern matching in Python equivalent to Perl(!~ operator)


code:
for i in range(10):
    #print i, i+10
    mod = pd.ols(y=df['A'].iloc[i:i + 10], x=df[['B','C']].iloc[i:i + 10], window=10)

rawDescription: Selecting specific rows from a python dataframe for an ols regression in PANDAS


rawDescription: Using Twisted AMP with Database insertion


rawDescription: Combination of all possible cases of a string


code:
try:
    socket.inet_aton(data)
except socket.error:
    pass
else:
    print(data)

rawDescription: Validate IP address from list

description: Validate IP address from list


code:
from operator import mul

def sum_of_divisors(n):
    """
    Return the sum of divisors of n.

    >>> sum_of_divisors(1)
    1
    >>> sum_of_divisors(33550336) // 2
    33550336
    """
    return reduce(mul, ((p**(k+1)-1) // (p-1) for p, k in factorization(n)), 1)

rawDescription: How would you implement a divisor function?


code:
# Run kernels many times, we will only keep data from last loop iteration.
for j in range(10):
    for k in range(n):
        event[k]['kernel_begin'].record(stream[k])
        my_kernel(d_data[k], block=(N,1,1), stream=stream[k])
    for k in range(n): # Commenting out this line should break concurrency.
        event[k]['kernel_end'].record(stream[k])

rawDescription: Pycuda Concurrency

description: Pycuda Concurrency


rawDescription: Converting OHLC stock data into a different timeframe with python and pandas


code: converted_times = map(convert, orig_times)

rawDescription: Converting time from (mm:ss.ddd) to (ss.ddd)


code: df.apply(lambda x: pd.qcut(x, 5, labels=list(range(5))), axis=0)

rawDescription: python - possible to apply percentile cuts to each column in a dataframe?

description: Python - possible to apply percentile cuts to each column in a dataframe


code: questions.remove(Question("How many legs on a horse", 0, []))

rawDescription: Python trivia game

description: Python trivia game


code: requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])

rawDescription: how to post multiple value with same key in python requests?

description: Post multiple value with same key in python requests


code:
df.duplicated(['Column2', 'Column3', 'Column4'])
df['is_duplicated'] = df.duplicated(['Column2', 'Column3', 'Column4'])

rawDescription: How to identify the first occurence of duplicate rows in Python pandas Dataframe

description: Identify the first occurence of duplicate rows in Python pandas Dataframe


rawDescription: Return different value from function depending on suffix


code:
with transaction.atomic():
    with MyMPTTModel.objects.disable_mptt_updates():
        for new_record in new_records:
            new_node = MyMPTTModel(..., parent=get_parent(new_record))
            new_node.save()
    MyMPTTModel.objects.rebuild()

rawDescription: How optimize adding new nodes in `django-mptt`?


code:
img
img_out

rawDescription: Flipping continuous chunks of 1's up to a certain size in a binary numpy matrix


code:
get_user_choice('choose an option in A, B, C: ', ['A', 'B', 'C'])
get_user_choice('choose an option in A, B, C: ', ['A', 'B', 'C'])

rawDescription: python: If an entry is not an acceptable parameter for a prompt, how to re-ask

description: Python: If an entry is not an acceptable parameter for a prompt, how to re-ask


rawDescription: How do I remove the first Item from a Python list?

description: Remove the first Item from a Python list


rawDescription: Where does python look for files in a script?


rawDescription: Convert black and white array into an image in python?


code:
l = [{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]
[a.get('term') for a in l]

rawDescription: Python - Correct Method of Parsing

description: Python - Correct Method of Parsing


code:
def func():
    a = 10000; b = 10000; return a is b
from dis import dis
dis(func)

rawDescription: Weird id result on CPython IntObject

description: Weird id result on CPython IntObject


code:
if userInDate.replace('-','').isdigit() and len(userInDate) == 10 and userInDate[4] == userInDate[7] == '-':
    d = userInDate

rawDescription: python - convert date input to date output without time

description: Python - convert date input to date output without time


rawDescription: issubclass of abstract base class Sequence

description: Issubclass of abstract base class Sequence


rawDescription: How to find the local minima of a smooth multidimensional array in NumPy efficiently?

description: Find the local minima of a smooth multidimensional array in NumPy efficiently


code:
def powerset_generator(it, rev=False):
    rn = range(len(it), 0, -1) if rev else range(1, len(it)+1)
    for subset in chain.from_iterable(combinations(it, r) for r in rn):
        yield list(subset)

rawDescription: Python inverse power set generator

description: Python inverse power set generator


code: tensorcontraction(tp, (1, 2))

rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


rawDescription: Accessing the keys of a dict when the keys are tuple and checking the elements of the tuple if they are equal


code:
class AuthRequiredMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('landing_page')) # or http response
        return None

rawDescription: Django, redirect all non-authenticated users to landing page


code:
import itertools as IT
import numpy as np
import pandas as pd
np.random.seed(2015)

N = 10000
df1, df2 = [pd.DataFrame(
    np.random.choice(map(''.join, IT.product(list('ABC'), repeat=2))+['--'],
                     size=(N, 2)),
    columns=['Col1', 'Col2']) for i in range(2)]

comparison = df1.eq(df2)
mask = (df1=='--') | (df2=='--')
comparison |= mask

# for column stats
column_stats = comparison.sum(axis=0) / float(len(df1.index))

# for row stats
row_stats = comparison.sum(axis=1) / float(len(df1.columns))

rawDescription: Python Pandas Compare 2 Large DataFrames of Text for Similarity


rawDescription: Pandas list comprehension in a dataframe


code:
def add_missing_empty_frames(g):
    last_key = None
    for key, items in g:
        if last_key:
            while (key-last_key).seconds > 30*60:
                empty_key = last_key + timedelta(minutes=30)
                yield (empty_key, [])
                last_key = empty_key
        yield (key, items)
        last_key = key

for key, items in add_missing_empty_frames(g):
    ...

rawDescription: Python: Grouping into timeslots (minutes) for days of data


code:
gen = (["-".join((min(a,b), max(a,b))) for b in shops if b != a] for a in shops)
for item in gen:
    print(item)

rawDescription: Fast way of crossing strings in a list

description: Fast way of crossing strings in a list


code:
with open('infile.txt', 'r+') as fopen:
    for line in fopen:
        for word in line.split():
            print(word)

rawDescription: Trying to count words in a file using Python


code: ' one two\n three\n'

rawDescription: Set the wrap width for python docs in a terminal


code: [column.key for column in myTable.__table__.columns]

rawDescription: get table columns from sqlAlchemy table model

description: Get table columns from sqlAlchemy table model


rawDescription: Pandas: Number of unique days in a timestamp Series


code:
from tkinter import *
things = [{"dictionaryItem":"value"}, {"anotherDict":"itsValue"}, 3, "foo", ["bar", "baz"]]
root = Tk()
f = Frame(root).pack()
l = Listbox(root)
b = Button(root, text = "delete selection", command = lambda: delete(l))
b.pack()
l.pack()

for i in range(5):
    l.insert(END, things[i])

def delete(listbox):

    global things
    # Delete from Listbox
    selection = l.curselection()
    l.delete(selection[0])
    # Delete from list that provided it
    value = eval(l.get(selection[0]))
    ind = things.index(value)
    del(things[ind])
    print(things)

root.mainloop()

rawDescription: Removing a selection from a listbox, as well as remove it from the list that provides it


code:
import functools
pairwise = functools.partial(grouper, 2)

rawDescription: Creating a python dictionary from a line of text


rawDescription: Dynamic ordered python structure?

description: Dynamic ordered python structure


code:
for i in range(10):
    pub.sendMessage("update", i+1)
    time.sleep(1)

rawDescription: wxPython threading wxGauge

description: WxPython threading wxGauge


code:
choices = ['prod', 'staging', 'test', 'dev']
help = "Environment to run on (choose from: {!r})".format(choices)
parser.add_option('-e', '--env',
                  type='choice',
                  action='store',
                  dest='environment',
                  choices=choices,
                  default='dev',
                  help=help,)

rawDescription: Display list of option choices in help text automatically in OptionParser


code: frame[frame.duplicated(['key1', 'key2'], keep=False)].groupby(('key1', 'key2')).min()

rawDescription: How to analyze all duplicate entries in this Pandas DataFrame?

description: Analyze all duplicate entries in this Pandas DataFrame


code:
with open('file.son') as fh:
    a = json.load(fh)

rawDescription: What is the difference between json.dumps and json.load


code:
def sliceDataframe(df, x):
    # supposing the column labels are sorted:
    pos = np.searchsorted(df.columns.values, x)

    # select the two neighbouring column labels:
    left = df.columns[pos-1]
    right = df.columns[pos]

    # simple interpolation
    interpolated =  df[left] + (df[right] - df[left])/(right - left) * (x - left)
    interpolated.name = x
    return interpolated

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


code:
def foo(A, B=None):
    if B is None:
        B = A
    do_something()

rawDescription: Python optional function argument to default to another argument's value


code:
from nltk.tag import pos_tag

sentence = "Michael Jackson took Daniel Jackson's hamburger and Agnes' fries"
tagged_sent = pos_tag(sentence.split())
# [('Michael', 'NNP'), ('Jackson', 'NNP'), ('took', 'VBD'), ('Daniel', 'NNP'), ("Jackson's", 'NNP'), ('hamburger', 'NN'), ('and', 'CC'), ("Agnes'", 'NNP'), ('fries', 'NNS')]

possessives = [word for word in sentence if word.endswith("'s") or word.endswith("s'")]
# ["Jackson's", "Agnes'"]

rawDescription: Finding Proper Nouns using NLTK WordNet

description: Finding Proper Nouns using NLTK WordNet


code: networkx.edges(G, ['my_node_name'])

rawDescription: Get all edges linked to a given node in a networkx graph


code:
import datetime
hours_d = datetime.datetime.strptime('26:00','%H:%M')

rawDescription: How to get hhh:mm datetime format with Python?

description: Get hhh:mm datetime format with Python


code: x.loc[index1, 3] = x.loc[index2, 2]

rawDescription: Editing values in a pandas dataframe using data from another part of the dataframe


Preprocessor: httpinspect

Preprocessor: detect

rawDescription: How can I parse a log file to JSON

description: Parse a log file to JSON


code:
wx.MessageBox('Download completed',
       'Info',
        wx.OK | wx.ICON_INFORMATION)

rawDescription: JOptionPane equivalent in python?

description: JOptionPane equivalent in python


code:
class StateDetails(object):
    def __init__(self, state, abbrev):
        self.state = state
        self.abbrev = abbrev
    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.abbrev == other.abbrev
    def __hash__(self):
        return hash(self.abbrev)
    def __repr__(self):
        return '{}({!r}, {!r})'.format(self.__class__.__name__, self.state, self.abbrev)

CA = StateDetails('California', 'CA')
AZ = StateDetails('Arizona', 'AZ')
NV = StateDetails('Nevada', 'NV')
UT = StateDetails('Utah', 'UT')
graph = {CA: [AZ, NV],
         AZ: [CA, NV, UT],
         NV: [CA, AZ, UT],
         UT: [AZ, NV]}

rawDescription: implementation of graphs in python that have a label

description: Implementation of graphs in python that have a label


code:
def get_level(module_info):
    for i in module_info[0]:
        if str.isdigit(i):
            return i

rawDescription: A functon that finds the numeric letter from the input


code: d = datetime.strptime(self.date, "%Y-%m-%d")

rawDescription: python: access a date field attributes

description: Python: access a date field attributes


code:
stopwords_regex_list = []
chunk_size = 100  # can tweak depending on size
for i in xrange(0, len(stopwords), chunk_size):
    stopwords_slice = stopwords[i:i + chunk_size]
    stopwords_regex_list.append(re.compile('\b(' + '|'.join(stopwords_slice) + ')\b'))
    with open('document') as doc:
        words = doc.read()  # can read only a certain size if the files are massive
    with open('regex_document', 'w') as regex_doc:
        for regex in stopwords_regex_list:
            words = regex.sub('', words)
        regex_doc.write(words)

rawDescription: Removing stopwords with Python - quickly and efficiently


code:
data_copy = list(data)  # you can replace any appearance of data_copy with data if you don't care if it is changed
while data_copy:  # this is equivalent to: while len(data_copy) != 0:
    to = min(10, len(data_copy))  # If there are less then 10 entries left, the length will be smaller than ten, so that it is either 10 or the (smaller) length. This is the amount of data that's processed
    f(data_copy[:to])  # make the function call with any value up to 'to'
    del data_copy[:to]  # delete the data, because we already processed it

rawDescription: Adding 'n' values in list using for-loop and step-loop for that 'n' values in python


code:
import lxml.objectify as objectify
import lxml.etree as ET

content = """
<A>
    <B foo="baz"/>
    <B foo="bar"/>
</A>"""
xml_obj = objectify.fromstring(content)
print(xml_obj.getchildren())
# [u'', u'']

rawDescription: Getting valueless elements in python lxml


code:
prefix = 'sw_apple-mc-stded'
firmware = [s for s in lists if prefix in s]
# firmware = [s for s in lists if s.startswith(prefix)]
return firmware

rawDescription: Python regex in lists

description: Python regex in lists


code:
import csv
from collections import defaultdict
with open("in.txt" ) as f:
    next(f) # skip header
    d = defaultdict(lambda: defaultdict(list))
    r = csv.reader(f)
    for row in r:
        d[row[0]][row[1]].extend(row[2:])

from pprint import pprint as pp

pp(dict(d))

rawDescription: Python 3: nested dictionary with multiple keys from csv


code: [i for (i, c) in enumerate(String) if c == 'a']

rawDescription: Finding index number for a character of a particular word in the string


code: (x for x in G.nodes_iter() if G.out_degree(x)==0 and G.in_degree(x)==1)

rawDescription: Find end nodes (leaf nodes) in radial (tree) networkx graph


code:
myarray *= 100
timeit.timeit('f()', 'from __main__ import withchain as f', number=25000)
timeit.timeit('f()', 'from __main__ import withsum as f', number=25000)
timeit.timeit('f()', 'from __main__ import withlistcomp as f', number=25000)

rawDescription: how to add all array's elements to one list in python

description: Add all array's elements to one list in python


code:
class CustomerDeletionHandler(webapp2.RequestHandler):
    def get(self):

        customers = Customers.all()
        countCustomers= 0

        for p in customers:
            p.delete()
            countcustomers+= 1

        self.response.out.write("\nDeleted Customers: " + str(countCustomers))

app = webapp2.WSGIApplication([
('/deleteCustomers', CustomerDeletionHandler)
], debug=True)

rawDescription: gae & python - setting different urls in yaml: 404 not found

description: Gae & python - setting different urls in yaml: 404 not found


code:
import csv

with open('test.csv', 'rb') as infile, open('out.csv', 'wb') as outfile:
    r = csv.reader(infile, delimiter=',', quotechar='"')
    headers=r.next()
    for index, heading in enumerate(headers):
        if heading == 'mail':
            headers[index] = "Username"
        elif heading == 'data1':
            data_1_index = index
    headers.insert(data_1_index, 'data1')

    w = csv.writer(outfile, delimiter=',', quotechar='"')
    w.writerow(headers)
    for row in r:
        row.insert(data_1_index, row[data_1_index])
        w.writerow(row)

rawDescription: replacing the first line of a csv file python

description: Replacing the first line of a csv file python


code:
lines = myfile.readlines()
for line in lines:
    ...

rawDescription: why we recommend iterators instead of lists (low-level explanation)

description: Why we recommend iterators instead of lists (low-level explanation)


code:
def funct(*args):
    ...

funct(
    data1, {"x": "x_val", "y": "y_val"},
    data2, {"x": "x_val", "y": "y_val"},
    data3, {"x": "x_val", "y": "y_val", "other_args": "other_args_val"}
)

rawDescription: Method signature for variable length of arguments


code:
"""
My script.

usage:
    myscript -a | --along
    myscript -b | --blong

Options:
  -a --along     a help
  -b --blong     b help
"""

from docopt import docopt
arguments = docopt(__doc__, version='myscript 1.0')
print(arguments)

rawDescription: What is the canonical way of handling sys arguments in Python?


code:
from sklearn.base import BaseEstimator

class FaceRecognizerModel(BaseEstimator):

    def __init__(self):
        self.model = cv2.createEigenFaceRecognizer()

    def fit(self, X, y):
        self.model.train(X,y)

    def predict(self, T):
        return [self.model.predict(T[i]) for i in range(0, T.shape[0])]

rawDescription: Face recognition in OpenCV Python FAR/FRR


code:
for i in np.arange(0,l00):
     i=i*10

rawDescription: Steps for "for loop" in python

description: Steps for "for loop" in python


code: df.index + pd.offsets.MonthEnd(0)

rawDescription: pandas: convert datetime to end-of-month

description: Pandas: convert datetime to end-of-month


code: print([ind for ind, s  in enumerate(mylist) if re.search(r"\bis the colour\b",s)])

rawDescription: How to remove an item in a list that has a specific ordering of words

description: Remove an item in a list that has a specific ordering of words


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code: event.listen(Site.words, 'append', test_event, retval = True)

rawDescription: React on UniqueKeyViolation in SQLAlchemy


code:
def divisors(factors):
    div = [1]
    for (p, r) in factors:
        div = [d * p**e for d in div for e in range(r + 1)]
    return div

rawDescription: Finding all divisors of a number optimization


code:
counter = Counter()
for dict_ in test_dict:
    counter.update(**dict_)

counter

rawDescription: Adding Values that Have the Same Key

description: Adding Values that Have the Same Key


code:
l = ['172.27.145.130/25', '172.27.145.129/25', '172.27.145.131/25']
interfaces = [netaddr.IPNetwork(interface) for interface in l]
addresses = [interface.ip for interface in interfaces]
bits = [address.bits() for address in addresses]
bits
myip = '172.27.145.129'
myaddress = netaddr.IPAddress(myip)
mybits = myaddress.bits()

rawDescription: python netaddr find closest Ip address match

description: Python netaddr find closest Ip address match


code:
connection = get_connection(backend=backend)
email = EmailMessage(subject='subj', body='body', from_email=from_email, to=to,
             connection=connection)

rawDescription: Dynamic Django Mail Configuration

description: Dynamic Django Mail Configuration


code: fh = codecs.open(fname,'r','utf8')

rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


code: [[] for _ in range(int(input("How Many?")))]

rawDescription: Make a for-loop that makes "n" lists (i.e. 5 lists when n= 5 or 10 lists when n=10)


code:
class sale_order(osv.Model):
    _inherit = 'sale.order'
    _columns = {
        'fleet_id': fields.many2one('fleet.service.type', 'Fleet Service Type'),
    }

rawDescription: retrieve all values of fleet_service_type.name into sale.order

description: Retrieve all values of fleet_service_type.name into sale.order


code:
x2 = np.ascontiguousarray(x).view(np.dtype((np.void, x.dtype.itemsize * x.shape[1])))
y_temp, z = np.unique(x2, return_inverse=True)
y = y_temp.view(dtype='int64').reshape(len(y_temp), 2)
print(y)
print(z)

rawDescription: Generating numpy array of indices for a deduplicated set of points


rawDescription: Unable to get regex to capture last group


code: XinY_Stack(2, 3)

rawDescription: Is it possible to remove recursion from this function?


code: frenchies, englishers, probs = zip(*results)

rawDescription: Python: separate results of re.findall

description: Python: separate results of re.findall


code:
l = ['a','b','x','f',"x"]
sub_list = ['c','d','e']
for ind, ele in enumerate(l): # use l[:] if the element to be replaced is in sub_list
    if ele == "x":
        l[ind:ind+1] = sub_list
print(l)
['a', 'b', 'c', 'd', 'e', 'f', 'c', 'd', 'e']

rawDescription: Replacing an element of a list with multiple values


rawDescription: Use regular expressions to match any number of characters as long as the first character isn't a digit


code:
# Create the Eigenfaces model. We are going to use the default
# parameters for this simple example, please read the documentation
# for thresholding:
model = cv2.createEigenFaceRecognizer(threshold=100.0)

rawDescription: eigenfaces with openCV

description: Eigenfaces with openCV


code:
while True:
    euser = input("Enter Gmail Username: ")
    epass = input("Enter Gmail Password: ")
    try:
        user.login(euser, epass)
    except smtplib.SMTPAuthenticationError:
        print ("Invalid Credentials!")
        continue
    break

rawDescription: Why does python ask me to input the same thing over and over again after it has been already entered - (smtpib - gmail)


rawDescription: group dictionary by values in a new nested one

description: Group dictionary by values in a new nested one


code: signal

rawDescription: Incorrect Output While Comparing Two Lists


code: pprint(list(cur))

rawDescription: Find values from MongDB from an array for only one date


code:
l1
l2
l3 = [x for x in l1 if x not in l2]
l3
df[df['category'].isin(l3)][['amount','freq']]

rawDescription: slice pandas dataframe by column showing all except the column provided

description: Slice pandas dataframe by column showing all except the column provided


code: [(int(math.log10(abs(x))), y) for x, y in t]

rawDescription: python find first non-zero digit after decimal point

description: Python find first non-zero digit after decimal point


rawDescription: why using multiple threading to get the sum is correct?

description: Why using multiple threading to get the sum is correct


code:
value_counts = [(value, len(list(it))) for value,it in groupby(values)]
vc = NoNegativesDict(value_counts)
nna = [NoNegativesDict(a) for a in subsetsA]
nnb = [NoNegativesDict(b) for b in subsetsB]
nnc = [NoNegativesDict(c) for c in subsetsC]

# this is kind of ugly; with some more effort
# I could probably make it a recursive call also
b_tries = 0
c_tries = 0
sol_count = 0
start = dt.datetime.utcnow()

for a in nna:
    try:
        res_a = vc - a
        sa = str(a)

        for b in nnb:
            try:
                res_b = res_a - b
                b_tries += 1
                sb = str(b)

                for c in nnc:
                    try:
                        res_c = res_b - c
                        c_tries += 1

                        #unpack remaining values
                        res_values = [val for val,num in res_c.items() for i in range(num)]
                        for sol in find_subsets_which_sum_to(1438214, res_values):
                            sol_count += 1
                            print("\n================")
                            print("a =", sa)
                            print("b =", sb)
                            print("c =", str(c))
                            print("d =", str(sol))

                    except ValueError:
                        pass

            except ValueError:
                pass

    except ValueError:
        pass

print("{} solutions found in {} b-tries and {} c-tries".format(sol_count, b_tries, c_tries))
end = dt.datetime.utcnow()
elapsed = end - start
seconds = elapsed.days * 86400 + elapsed.seconds + elapsed.microseconds * 0.000001
print("  -> took {:0.1f} seconds.".format(seconds))

rawDescription: Determine which numbers in list add up to specified value


rawDescription: Sorting dictionary by value and lexicographical


rawDescription: take sum of ints preserving specific information

description: Take sum of ints preserving specific information


code:
def __str__(self):
    return ' '.join([self.firstName, self.lastName])

rawDescription: Automatically setting getter, setter and deleter in python


code:
#!/usr/bin/env python

import csv

myfile = '/path/to/untitled.csv'
newfile = '/path/to/untitled_new.csv'

reader = csv.reader(open(myfile))

remove_me = {'3270','2500'}

print('Before:')
print(open(myfile).read())

for row in reader:
    new_row = []
    for column in row:
        if column not in remove_me:
            new_row.append(column)

    csv.writer(open(newfile,'a')).writerow(new_row)

print('\n\n')
print('After:')
print(open(newfile).read())

rawDescription: Remove cell in a CSV file if a certain value is there


code:
class Custom_Polygon(object):
    """docstring for Polygon"""
    def __init__(self, verts):
        self.verticies = np.array(verts)
        self.dims = self.verticies.shape[1]

    def scale(self, scaleFactor):
        scaleMatrix = np.zeros((self.dims, self.dims))
        np.fill_diagonal(scaleMatrix, scaleFactor)
        self.verticies = np.dot(self.verticies, scaleMatrix)

    def scale_with_orgin(self, scaleFactor, origin):
        origin = origin.copy()
        self.translate([-i for i in origin])
        self.scale(scaleFactor)
        self.translate([i for i in origin])

    def translate(self, shiftBy):
        self.verticies += shiftBy

    def get_width(self):
        x_min = self.verticies[:,0].min()
        x_max = self.verticies[:,0].max()
        return abs(x_max - x_min)

    def get_height(self):
        y_min = self.verticies[:,1].min()
        y_max = self.verticies[:,1].max()
        return abs(y_max - y_min)

rawDescription: How to create a repetitive image pattern programmatically?

description: Create a repetitive image pattern programmatically


code:
origin_text = [string.text for text_elem in origin_root.iter('Texts')
               for string in text_elem]

rawDescription: Matching the XML Req and Res

description: Matching the XML Req and Res


code:
myList = ['qwer', 'tyu', 'iop12', '3456789']
not any('wer' in s for s in myList)
not any('123' in s for s in myList)

rawDescription: Check if none of list elements contain searched substring


code: attendee_by_role = session.query(Attendee).filter_by(**{role: True})

rawDescription: Substituting variable into SQLAlchemy / Postgresql Query


code:
def dict_gen(curs):
    ''' From Python Essential Reference by David Beazley
    '''
    import itertools
    field_names = [d[0].lower() for d in curs.description]
    while True:
        rows = curs.fetchmany()
        if not rows: return
        for row in rows:
            yield dict(itertools.izip(field_names, row))

rawDescription: Python - mysqlDB, sqlite result as dictionary


code:
def inAll(x, *lsts):
    return all((x in l) for l in lsts)

rawDescription: How to check if an element is also in another list

description: Check if an element is also in another list


code:
class Student:
    student_id = Property(...)
    name = Property(...)
    classes = Property(...)

rawDescription: Correct way of implementing a Python class that calls external functions on attribute update


code:
def belongs(set1, set2):
    return any(s1 in s2 for s1 in set1 for s2 in set2)

rawDescription: Pythonic way of writing belongs function in two sets


rawDescription: Shortest way to write the program in Python


code:
values = numpy.ndarray(1000000, dtype=numpy.uint64)
# fill in the data
values >>= 8

rawDescription: Global vs local variable efficiency in multiple function call