code:
def render_to_s(request, *args, **kwargs):
    panelDisplays = PanelDisplay.listAll()
    csrf_token_value = request.COOKIES['csrftoken']

    c = {"panelDisplays": panelDisplays, "csrf_token_value": csrf_token_value}
    return render_to_string('panels/config.html', c)

rawDescription: Populate {% csrf_token %} when using render_to_string?


rawDescription: how connect to vertica using pyodbc

description: How connect to vertica using pyodbc


rawDescription: Zip Lists together based on many to one relationship


code: def index (req): return "Hello World!"

rawDescription: How to print to HTML using python as server side script?

description: Print to HTML using python as server side script


rawDescription: Finding tuples with a common element

description: Finding tuples with a common element


code:
results, _ = theano.scan(
    _step,
    sequences=inputs,
    outputs_info=[None] + initial_states,
    go_backwards=go_backwards)

# deal with Theano API inconsistency
if type(results) is list:
    outputs = results[0]
    states = results[1:]
else:
    outputs = results
    states = []

rawDescription: GRU implementation in Theano

description: GRU implementation in Theano


code:
import requests
import json

url = 'https://api.box.com/2.0/files/content'
h.headers = {'Authorization':'Bearer TOKEN'}
parent_folder_id = "2843500681"    # replace with your folder id

h.kwargs = {"name": "Wolves owners.ppt",
            "parent": {"id": parent_folder_id},
            "id": parent_folder_id,
            "size": 15243}

resp = requests.options(url, headers=h.headers, data=json.dumps(h.kwargs))

rawDescription: python requests authorization fails when json.dumps included

description: Python requests authorization fails when json.dumps included


code:
#models.py
class Job(models.Model):
    candidate = models.ManyToManyField('Candidate', through='CandidateToJob')
    title = models.CharField(max_length=500)
    ...

class Candidate(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    photo = models.ImageField(upload_to=user_profile_path)

class CandidateLook(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    HAIRCOLOR_CHOICES = (
        ('1', 'Black'),
        ('2', 'Brown'),
        ('3', 'Blonde'),
        ('4', 'Red')
    )
    haircolor = models.CharField(max_length=2, choices=HAIRCOLOR_CHOICES)

class CandidateToJob(models.Model):
    job = models.ForeignKey(Job, related_name='applied_to')
    candidate = models.ForeignKey(Candidate, related_name='from_user')
    STATUS_CHOICES = (
        ('0', 'New'),
        ('1', 'Not approved'),
        ('2', 'Approved')
     )
    status = models.CharField(max_length=2, choices=STATUS_CHOICES)

rawDescription: How to filter results using forms in Django (best approach)

description: Filter results using forms in Django (best approach)


rawDescription: Hourly frequency count with Python

description: Hourly frequency count with Python


code:
def read(ser, queue):
    for line in ser:
         queue.put(line)
threading.Thread(target=read, args=(ser, queue)).start()

rawDescription: Confusing 'readline' warning in the documentation


rawDescription: DESede in Java and 3des in python

description: DESede in Java and 3des in python


code:
data = '\x00\r\xeb\x00\x00\x00\x00\x01t\x00'
' '.join(["%02X" % ord(char) for char in data])

rawDescription: Non-binary(hex) characters in string received over TCP with Python


code:
message = f.read().lower()
crypt = ''.join(i for i in message if i in monocrypt)
encrypted_message = [monocrypt[letter] for letter in crypt]

rawDescription: How to keep "spaces" although dict contains it?

description: Keep "spaces" although dict contains it


rawDescription: Python Compare List to Dict Value

description: Python Compare List to Dict Value


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

fig, ax = plt.subplots()

min_val, max_val = 0, 10
ind_array = np.arange(min_val + 0.5, max_val + 0.5, 1.0)
x, y = np.meshgrid(ind_array, ind_array)

for i, (x_val, y_val) in enumerate(zip(x.flatten(), y.flatten())):
    c = 'x' if i%2 else 'o'
    ax.text(x_val, y_val, c, va='center', ha='center')
#alternatively, you could do something like
#for x_val, y_val in zip(x.flatten(), y.flatten()):
#    c = 'x' if (x_val + y_val)%2 else 'o'

ax.set_xlim(min_val, max_val)
ax.set_ylim(min_val, max_val)
ax.set_xticks(np.arange(max_val))
ax.set_yticks(np.arange(max_val))
ax.grid()

rawDescription: Matplotlib imshow/matshow display values on plot


code:
def convert(capital):
    first, _, rest = capital.partition(' ')
    return '{} {}'.format(first.title(), rest)

rawDescription: python function capitalize first letter only

description: Python function capitalize first letter only


rawDescription: Simplify Matrix by Averaging Multiple Cells


rawDescription: How to treat a hex as string?

description: Treat a hex as string


code:
s = r'\x09'
s.encode('unicode_escape').decode('unicode_escape')
'\t'

rawDescription: How to convert "\x09" back to tab

description: Convert "\x09" back to tab


code:
from ctypes import cdll
lib = cdll.LoadLibrary('./lib.so')
main = cdll.LoadLibrary('./main.so')
main.mainfunction(lib.fn1)
main.mainfunction(lib.fn2)

rawDescription: How to pass a function pointer to an external program in Cython

description: Pass a function pointer to an external program in Cython


code:
medObj = MedicationDS.Medication.factory()
medObj.set_dateStarted('2010-01-01')
medObj.set_dateStopped('2010-02-02')
medObj.set_reasonStopped('hurt my brain')
brandNameObj = MedicationDS.CodedValue.factory()
brandNameObj.set_abbrev('aspirin')
brandNameObj.set_value('aspirin')
medObj.set_brandName(brandNameObj)

xmlStr=StringIO()
medObj.export(xmlStr, 0)

rawDescription: Can generateDS be used like xsd.exe

description: Can generateDS be used like xsd.exe


code:
from splinter import Browser
browser = Browser()
browser
browser.driver

rawDescription: Manipulating browser (window) size using Splinter


code:
'{0} {1}'.format('hello', 'world')
inputs = ['hello', 'world']  # or 'hello world'.split()
'{0} {1}'.format(*inputs)

rawDescription: How to map word combinations in python

description: Map word combinations in python


code: [{'DataType          ': 'int          ', 'Table          ': 'A          ', 'Column               ': 'C1          '}, {'DataType          ': 'varchar          ', 'Table          ': 'A          ', 'Column               ': 'C2          '}, {'DataType          ': 'int          ', 'Table          ': 'B          ', 'Column               ': 'C3          '}]

rawDescription: How to append space at the end of Key and Values in the list of dictionary in python

description: Append space at the end of Key and Values in the list of dictionary in python


code:
def method_1():
    nonlocal value
    value = True    # Works as expected -- assigns to `value` from outer scope

rawDescription: Python and closed variables

description: Python and closed variables


code: timeit.timeit("{('column_' + str(i)): range(i,81,9) for i in xrange(9)}", number = 100000)

rawDescription: Possible to compress into a dictionary comprehension?


code:
weight = "The mass of the load is %.2f Newtons, which is "%(mass * conversion_const)

print(weight + 'too heavy')
print(weight + 'too light')
print(weight + 'just right')
print(weight + 'way too heavy')

rawDescription: How can I format a number for multiple prints in python3.x?

description: Format a number for multiple prints in python3.x


code:
class SomeClass(object):
    __instances__ = {}

    def __new__(cls, v1, v2, v3):
        try:
            return cls.__insts__[(v1, v2, v3)]
        except KeyError:
            return cls.__insts__.setdefault(
               (v1, v2, v3),
               object.__new__(cls, v1, v2, v3))

rawDescription: Why do attribute references act like this with Python inheritance?


rawDescription: Change the key value in python dictionary


code:
#!/usr/bin/python3

nx, ny = 4, 5
values = [1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,35,36,40]
# grid[x][y] so it is a list of columns (prints misleadingly!)
grid = [[0 for _ in range(ny)] for _ in range(nx)]
# cache these to avoid re-calculating
xy_moves = {}
debug = False

def neighbours(grid, x, y):
    'coordinates of vertical/horizontal neighbours'
    for (xx, yy) in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:
        if xx > -1 and xx < nx and yy > -1 and yy < ny:
            yield xx, yy

def filled_neighbours(grid, x, y):
    'filter "neighbours" to give only filled cells'
    return filter(lambda xy: grid[xy[0]][xy[1]], neighbours(grid, x, y))

def count_neighbours(grid, x, y):
    'use this to find most-constrained location'
    return sum(1 for _ in filled_neighbours(grid, x, y))

def next_xy(grid, depth):
    '''given a certain depth in the search, where should we move next?
       choose a place with lots of neighbours so that we have good
       constraints (and so can reject bad moves)'''
    if depth not in xy_moves:
        best, x, y = 0, nx // 2, ny // 2 # default to centre
        for xx in range(nx):
            for yy in range(ny):
                if not grid[xx][yy]:
                    count = count_neighbours(grid, xx, yy)
                    if count > best:
                        best, x, y = count, xx, yy
        xy_moves[depth] = (x, y)
        if debug: print('next move for %d is %d,%d' % (depth, x, y))
    return xy_moves[depth]

def drop_value(value, values):
    'remove value from the values'
    return [v for v in values if v != value]

def copy_grid(grid, x, y, value):
    'copy grid, replacing the value at x,y'
    return [[value if j == y else grid[i][j] for j in range(ny)]
            if x == i else grid[i]
            for i in range(nx)]

def move_ok(grid, x, y, value):
    'are all neighbours multiples?'
    for (xx, yy) in filled_neighbours(grid, x, y):
        g = grid[xx][yy]
        if (g > value and g % value) or (g < value and value % g):
            if debug:
                print('fail: %d at %d,%d in %s' % (value, x, y, grid))
            return False
    return True

def search(grid, values, depth=0):
    'search over all values, backtracking on failure'
    if values:
        (x, y) = next_xy(grid, depth)
        for value in values:
            if move_ok(grid, x, y, value):
                if debug: print('add %d to %d,%d' % (value, x, y))
                for result in search(copy_grid(grid, x, y, value),
                                     drop_value(value, values),
                                     depth+1):
                    yield result
    else:
        yield grid

# run the search, knowing that (2,2) (which is (1,1) for zero-indexing)
# has the value 10.
for result in search(copy_grid(grid, 1, 1, 10), drop_value(10, values)):
    print(result)

# how many solutions in total?
#xy_moves = {} # reset cache
#for (n, solution) in enumerate(search(grid, values)):
#    print('%d: %s' % (n, solution))

rawDescription: How to get rid of maximum recursion depth error or better solve this?

description: Get rid of maximum recursion depth error or better solve this


code:
u,v = sorted((u,v))
weight = matrix[v][u]

rawDescription: Creating Adjacency Lists from Dicts in Python


code:
big_ax = fig.add_subplot(gs[1,0]) # bottom left
top_ax = fig.add_subplot(gs[0,0]) # top left
right_ax = fig.add_subplot(gs[1,1]) # bottom center
cbar_ax = fig.add_subplot(gs[1,2]) # bottom right

rawDescription: How to plot heat map with matplotlib?

description: Plot heat map with matplotlib


code: output = regex.findall(r'(?:'+probe+'){s<'+str(int(mismatches)+1)+'}', sequence, regex.BESTMATCH, overlapped=True)

rawDescription: Python regex : overlapping sequences position


code: # rq worker

rawDescription: How to return data from a CherryPy BackgroundTask running as fast as possible

description: Return data from a CherryPy BackgroundTask running as fast as possible


code: linematcher('new_foo.txt', 'old_foo.txt', [1, 3, 4])

rawDescription: Mapping line numbers across two diff files using emacs/python/winmerge


code:
s = ["element1", (3, "element2"), (2, "element3")]
result = sum(([x] if type(x) != tuple else x[0]*[x[1]] for x in s), [])

rawDescription: I need to print/return multiple elements from tuple in Python


code:
from functools import lru_cache
func = lru_cache(1)(func)
if func():
   print(func())

rawDescription: Python assignment and test of function using elif


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Validate", command=self.validate)
        self.entry.pack(side="top", fill="x")
        self.button.pack(side="bottom")

        self.validate() # initialize the border

    def validate(self):
        data = self.entry.get()
        if len(data) == 0:
            self.entry.configure(highlightbackground="red", highlightcolor="red")
        else:
            self.entry.configure(highlightbackground="blue", highlightcolor="blue")

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

rawDescription: How to change a entry widgets border color in Python Tkinter

description: Change a entry widgets border color in Python Tkinter


code:
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):

    def __init__(self, stream):
        Reader.__init__(self, stream)
        Scanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        Constructor.__init__(self)
        Resolver.__init__(self)

rawDescription: PyYAML automatically converting certain keys to boolean values


code:
#!/usr/bin/env python

import argparse as ap
import argcomplete

def main(**args):
  pass

if __name__ == '__main__':
  parser = ap.ArgumentParser()
  parser.add_argument('positional', choices=['spam', 'eggs'])
  parser.add_argument('--optional', choices=['foo1', 'foo2', 'bar'])
  argcomplete.autocomplete(parser)
  args = parser.parse_args()
  main(**vars(args))

rawDescription: Custom tab completion in python argparse


rawDescription: Use ElementTree's findall() to match text of elements


rawDescription: Append to the same list

description: Append to the same list


code:
data2.columns = pd.MultiIndex.from_tuples(data2.columns.values)
data2
data2.columns.levels

rawDescription: Deep copy of DataFrame does not remove columns


code:
from datetime import datetime, timedelta, date
def tofirstdayinisoweek(year, week):
    ret = datetime.strptime('%04d-%02d-1' % (year, week), '%Y-%W-%w')
    if date(year, 1, 4).isoweekday() > 4:
        ret -= timedelta(days=7)
    return ret

rawDescription: Get date from ISO week number in Python

description: Get date from ISO week number in Python


code:
class Completer(QtWidgets.QCompleter):

    def __init__(self, parent=None):
        super(Completer, self).__init__(parent)

        self.setCaseSensitivity(Qt.CaseInsensitive)
        self.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
        self.setWrapAround(False)

    # Add texts instead of replace
    def pathFromIndex(self, index):
        path = QtWidgets.QCompleter.pathFromIndex(self, index)

        lst = str(self.widget().text()).split(',')

        if len(lst) > 1:
            path = '%s, %s' % (','.join(lst[:-1]), path)

        return path

    # Add operator to separate between texts
    def splitPath(self, path):
        path = str(path.split(',')[-1]).lstrip(' ')
        return [path]

rawDescription: PyQt - Auto Completer with QLineEdit multiple times


code:
t = datetime.time(1, 2)
dt = datetime.datetime.combine(datetime.date.today(), t)
dt
dt -= datetime.timedelta(hours=5)
dt.time()

rawDescription: python time offset

description: Python time offset


code:
import urllib2
from bs4 import BeautifulSoup

url = 'http://www.bbc.co.uk/zhongwen/simp/'

page = urllib2.urlopen(url).read().decode("utf-8")
dom = BeautifulSoup(page)
data = dom.findAll('meta', {'name' : 'keywords'})

with open("test.txt", "w") as myfile:
    myfile.write(data[0]['content'].encode("utf-8"))

rawDescription: Read multilanguage strings from html via Python 2.7


rawDescription: How to print specific things from JSON

description: Print specific things from JSON


code: re.match('\\r', s)

rawDescription: How python and the regex module handle backslashes


code: re.split('[Hh]ello', 'Hello moon')

rawDescription: Is there a way to make python str.partition ignore case?


code:
dval = pd.DataFrame(md[0].tolist(), )
dval

rawDescription: Transposing one column in python pandas with the simplest index possible


code: "\n" in "hello\ngoodbye"

rawDescription: How can I check for a new line in string in Python 3.x?

description: Check for a new line in string in Python 3.x


code: add(1, multiply(exp(add(-C24, -A2), 2), subtract(B2, F4)))

rawDescription: iterating over nester tuples to generate specific string

description: Iterating over nester tuples to generate specific string


code:
from distutils.version import LooseVersion
LooseVersion('1.2b') > LooseVersion('0.1')
LooseVersion('1.2b') > LooseVersion('1.2c')

rawDescription: How to accurately change a parsed version number in string form to numeric?

description: Accurately change a parsed version number in string form to numeric


code:
import re
p = re.compile(r'/\* *Custom-D Start *\*/\s*(.*?)/\* *Custom-D End *\*/', re.DOTALL)
test_str = "/* Highlighting edits text on TIB ONLY and NOT ON PDF Output. \n   .main-igp selector makes this style apply only for TIB.  */\n.main-igp .edit1 {color: rgb(235, 127, 36)}\n.main-igp .edit2 {color: rgb(0, 0, 180);}\n/*Custom-D Start     */\n.main-igp .edit3 {color: rgb(0, 180, 180);}\n.main-igp .edit6 {color: rgb(200, 200, 0);}\n/* Custom-D End */\n/* Production Note ===== */\np.production-note-rw {\n    display: none;}\n/* Production Note END ===== */"
m = p.search(test_str)
if m:
    print(m.group(1))

rawDescription: Extract block from CSS by Regular expression or any other method?


code:
def alllocal():
    for i in range(1000):
        for j in range(1000):
            for k in range(1000):
                pass

rawDescription: Python profiling - What are the columns in runsnakerun output?


code: set(x for lst in list_of_lists for x in lst)

rawDescription: how to convert list of lists to a set in python so I can compare to other sets?

description: Convert list of lists to a set in python so I can compare to other sets


code: return out.reshape(len(arrays), -1)

rawDescription: Detect the first unique rows in multiple numpy 2-d arrays


rawDescription: complicated iteration through a dictionary

description: Complicated iteration through a dictionary


code:
pattern = r"the (.+_.+)-SomeWord-(.+)"
groups = [(("Artist", "Album"), "_"), ("Year", None)]

rawDescription: How to match regex with multiple overlapping patterns?

description: Match regex with multiple overlapping patterns


code:
for enemy in enemies:  # Runs through the enemy list
    enemy.move()  # Moves the enemy
    player.collide(enemy,enemies)  # Checks if enemy is touching player
    enemy.draw(screen)  # Renders Enemies in the list

rawDescription: Python Pygame Enemy Collision

description: Python Pygame Enemy Collision


code: [u'legal', u'google']

rawDescription: Matching Against Unwanted Links

description: Matching Against Unwanted Links


rawDescription: Exercises 3.3 from Think Python

description: Exercises 3.3 from Think Python


code:
from itertools import product

options = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']]

for combo in product(*options):
    print("".join(combo))

rawDescription: Pythonic way of single list with all variations of sublists


code:
from collections import Counter
def repeater(strings, k):
    ctr = Counter()
    first = None
    for i in range(len(strings) - k + 1):
        seq = tuple(strings[i:i+k])
        if seq in ctr and first is None:
            first = seq
        ctr[seq] += 1
    return first, ctr.get(first)

seq, ctr = repeater(["a", "b", "c", "g", "h", "t", "i", "a", "b","c", "z", "g", "h", "t"], 3)
if ctr:
    print(seq, 'occurred', ctr, 'times')

rawDescription: Finding a repeating set of strings among a larger set


code:
import numpy as np
x = np.arange(0,1,0.001)
y = np.sqrt(1-x**2)

rawDescription: Calculate area of polygon given (x,y) coordinates


code: d = np.frombuffer(data, np.int16).astype(np.float)

rawDescription: audioop.rms() - why does it differ from normal RMS?

description: Audioop.rms() - why does it differ from normal RMS


code:
TimeFormat=365.25*60*60*24

def planet_time(data):
    def value(Week):
        return (Week+data)/52 * TimeFormat
    return value(Week)

rawDescription: How do I add different amounts to one inputted variable?

description: Add different amounts to one inputted variable


rawDescription: beautiful soup doesn't find all the tags

description: Beautiful soup doesn't find all the tags


rawDescription: Force the Y axis to only use integers

description: Force the Y axis to only use integers


code: output =  [row for row in newList2 if row not in oldList1]

rawDescription: Compare 2 csv files and output different rows to a 3rd CSV file using Python 2.7


code: first_idx = bisect_left(sorted_ips, first)

rawDescription: How to search a large database of IP addresses in a timely manner?

description: Search a large database of IP addresses in a timely manner


code:
class Foo(object):
    list_of_all_foos = []

    @classmethod
    def create_foo_and_add_to_list(cls, *args, **kwargs):
        new_foo = cls(*args, **kwargs)
        Foo.list_of_all_foos.append(new_foo)
        return new_foo

rawDescription: Loop over instances of a class to find attribute that equals a keyword


code:
enum_upperdiag = lambda mat: (((j,c),(r,k)) for n in [len(mat)-1]
                                 for r in range(n) for c in range(n-r)
                                 for j in range(r+1,n) for k in range(c+1,n-j+1))

rawDescription: NumPy: Iterating over items to right, bottom of given element w/ its index


code:
cols = ['A', 'B', 'C']
df['concat'] = df[cols].apply(''.join, axis=1)

rawDescription: Pandas Apply Function with Multiple **Kwarg Arguments


code: map(dict, zip(*[[(k, v) for v in value] for k, value in d.items()]))

rawDescription: Split dictionary of lists into list of dictionaries


rawDescription: Human format date range parsing

description: Human format date range parsing


code:
import serial # if you have not already done so
ser = serial.Serial('/dev/tty.usbserial', 9600)
ser.write('5')

rawDescription: How can I interface python with the serial output from an Arduino Uno on a Mac?

description: Interface python with the serial output from an Arduino Uno on a Mac


rawDescription: Make a copy of a list and set an element in one line?


code:
def isroutine(object):
    """Return true if the object is any kind of function or method."""
    return (isbuiltin(object)
            or isfunction(object)
            or ismethod(object)
            or ismethoddescriptor(object))

rawDescription: Is there a common way to check in Python if an object is any function type?


code:
class MyIter(object):
    def __iter__(self):
        return iter(range(10))

i = MyIter()
isinstance(i, collections.Iterable)
collections.Iterable.__subclasshook__(type(i))

rawDescription: Iterating over list or single element in python


code:
data = np.random.random_sample((200, 300, 100)) > 0.5
data.any(axis=-1).shape # show the result has the shape we want
data.any(axis=-1)

rawDescription: Numpy fastest 3D to 2D projection

description: Numpy fastest 3D to 2D projection


code:
mapping = dict((item,set()) for item in listOfItems
                            if item != "SomethingIDoNotWant")

rawDescription: Initialize dict with only some of a list


code:
def iterate(seed, num, fct):
#                      ^^^
    x = seed
    orbit = [x]
    for i in range(num):
        x = fct(x)
        #   ^^^
        orbit.append(x)
    return orbit

rawDescription: How to pass a function as function parameter in Python

description: Pass a function as function parameter in Python


code: ar.add_plot(bar1, bar2, bar3)

rawDescription: For loop inside a function

description: For loop inside a function


code:
cmap2 = mpl.colors.ListedColormap(sns.color_palette("husl", 256))

plt.figure()
plt.imshow(img, cmap=cmap2)
plt.colorbar()

rawDescription: seaborn husl or hsl color palette is not working: remains default black and white colors

description: Seaborn husl or hsl color palette is not working: remains default black and white colors


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

a=np.random.rand(200)*10
b=np.random.rand(200)*10
binmin=min(a.min(),b.min())
binmax=max(a.max(),b.max())
H_1, xedges_1, yedges_1, img_1 = plt.hist2d(a[:len(a)/2], b[:len(b)/2], bins = np.linspace(binmin,binmax,10+1))
H_2, xedges_2, yedges_2, img_2 = plt.hist2d(a[len(a)/2:], b[len(b)/2:], bins = np.linspace(binmin,binmax,10+1))
H_3, xedges_3, yedges_3, img_3 = plt.hist2d(a, b, bins = np.linspace(binmin,binmax,10+1))

rawDescription: matplotlib: plot hist2d piecewise

description: Matplotlib: plot hist2d piecewise


code: logger.propagate = False

rawDescription: Logger prints to console even though FileHandler is defined


rawDescription: How to determine the method type of stdlib methods written in C

description: Determine the method type of stdlib methods written in C


rawDescription: Python Get Docstring Without Going into Interactive Mode


code:
from sqlalchemy.orm.attributes import ClassManager, instrumentation_registry

class ReadonlyClassManager(ClassManager):
    """Enables configuring a mapper to return instances of uninstrumented
    classes instead. To use add a readonly_type attribute referencing the
    desired class to use instead of the instrumented one."""
    def __init__(self, class_):
        ClassManager.__init__(self, class_)
        self.readonly_version = getattr(class_, 'readonly_type', None)
        if self.readonly_version:
            # default instantiation logic doesn't know to install finders
            # for our alternate class
            instrumentation_registry._dict_finders[self.readonly_version] = self.dict_getter()
            instrumentation_registry._state_finders[self.readonly_version] = self.state_getter()

    def new_instance(self, state=None):
        if self.readonly_version:
            instance = self.readonly_version.__new__(self.readonly_version)
            self.setup_instance(instance, state)
            return instance
        return ClassManager.new_instance(self, state)

Base = declarative_base()
Base.__sa_instrumentation_manager__ = ReadonlyClassManager

rawDescription: SqlAlchemy optimizations for read-only object models


code: shlex.split("this is 'my string' that --has=arguments -or=something")

rawDescription: What is the difference between shlex.split() and re.split()?


code:
last = slice(-1)
def littery(*lst):
    return ''.join(lst)[last]

rawDescription: How do I join a list and then delete the last character?

description: Join a list and then delete the last character


rawDescription: Check if number is made of both 0 and 1 using regex


code: string = "float is %.3f" % 3.1425

rawDescription: What is the % operator in python for?

description: What is the % operator in python for


code: np.matmul(arr, w)

rawDescription: Numpy tensor: Dot product along third axis


code:
class Tristate(object):
    def __init__(self, value=None):
       if any(value is v for v in (True, False, None)):
          self.value = value
       else:
           raise ValueError("Tristate value must be True, False, or None")

    def __eq__(self, other):
       return (self.value is other.value if isinstance(other, Tristate)
               else self.value is other)
    def __ne__(self, other):
       return not self == other
    def __nonzero__(self):   # Python 3: __bool__()
       raise TypeError("Tristate object may not be used as implicit Boolean")

    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return "Tristate(%s)" % self.value

rawDescription: Booleans have two possible values. Are there types that have three possible values?


code:
try:
    import argparse
    # Argparse-specific stuff
except ImportError:
    import optparse
    # Optparse-specific stuff

rawDescription: Dynamically choosing Python library based on Python version


code:
def match_anywhere(completion, entrystr, iter, data):
    modelstr = completion.get_model()[iter][0]
    return entrystr in modelstr
completion.set_match_func(match_anywhere, None)

rawDescription: Entry with suggestions

description: Entry with suggestions


code:
import colorsys

def get_hsv(hexrgb):
    hexrgb = hexrgb.lstrip("#")   # in case you have Web color specs
    r, g, b = (int(hexrgb[i:i+2], 16) / 255.0 for i in xrange(0,5,2))
    return colorsys.rgb_to_hsv(r, g, b)

rawDescription: Sort (hex) colors to match rainbow

description: Sort (hex) colors to match rainbow


rawDescription: Is there any way to do HTTP PUT in python


code:
import itertools

class MyMeta(type):
    class DescName(object):
        def __init__(self, cls):
            self.cache = {None: self, cls: set()}
            self.counter = {cls: itertools.count()}

        def __get__(self, obj, cls=None):
            return self.cache[obj]

        def __set__(self, obj, value):
            self.setname(obj, value)

        def setname(self, obj, name=None):
            cls = obj.__class__
            name = name or '%s_%d' % (cls.__name__, next(self.counter[cls]))

            s = self.cache[cls]
            if name in s:
                raise AttributeError('EXISTING NAME %s' % name)

            s.discard(self.cache.get(obj, None))
            s.add(name)
            self.cache[obj] = name

    def __new__(meta, name, bases, dct):
        cls = super(MyMeta, meta).__new__(meta, name, bases, dct)
        cls.name = meta.DescName(cls)  # add the name class attribute
        return cls

    @classmethod
    def as_metaclass(meta, *bases):
        class metaclass(meta):
            def __new__(cls, name, this_bases, d):
                # subclass to ensure super works with our methods
                return meta(name, bases, d)
        return type.__new__(metaclass, str('tmpcls'), (), {})

    def __call__(cls, *args, **kwargs):
        # Instead of relying on type we do the new and init calls
        obj = cls.__new__(cls, *args, **kwargs)
        cls.name.setname(obj)
        obj.__init__(*args, **kwargs)
        return obj

class MyClass(MyMeta.as_metaclass()):
    def __init__(self, *args, **kwargs):
        print('__init__ with name:', self.name)

a = MyClass()
b = MyClass()
c = MyClass()

a.name = 'my new name'
print('a.name:', a.name)

try:
    a.name = b.name
except AttributeError as e:
    print(e)
else:
    print('a.name %s == %s b.name' % (a.name, b.name))

rawDescription: Ensure uniqueness of instance attribute in python


code:
phonebook_data = open(data_path)
contents = phonebook_data.read()
phonebook_data.close()

if contents == "":
    print("Your contact book is empty.")

rawDescription: updating tkinter window (Python 3.4)

description: Updating tkinter window (Python 3.4)


rawDescription: Broadcasting into views of Numpy arrays

description: Broadcasting into views of Numpy arrays


code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot_date(df['Date'], df['Data'])

rawDescription: dataframe.plot exclude missing data

description: Dataframe.plot exclude missing data


code:
import Image
import redis
import StringIO

output = StringIO.StringIO()
im = Image.open("/home/cwgem/Pictures/portrait.png")
im.save(output, format=im.format)

r = redis.StrictRedis(host='localhost')
r.set('imagedata', output.getvalue())
output.close()

rawDescription: how to store an image into redis using python / PIL

description: Store an image into redis using python / PIL


rawDescription: Finding solutions to row reduced matrix python


rawDescription: How to identify a specific XML element without ID attributes

description: Identify a specific XML element without ID attributes


code:
from collections import namedtuple

Rectangle = namedtuple("Rectangle", "top bottom left right")

def find_rectangles(arr):

    # Deeply copy the array so that it can be modified safely
    arr = [row[:] for row in arr]

    rectangles = []

    for top, row in enumerate(arr):
        start = 0

        # Look for rectangles whose top row is here
        while True:
            try:
                left = row.index(0, start)
            except ValueError:
                break

            # Set start to one past the last 0 in the contiguous line of 0s
            try:
                start = row.index(1, left)
            except ValueError:
                start = len(row)

            right = start - 1

            if (  # Width == 1
                  left == right or
                  # There are 0s above
                  top > 0 and not all(arr[top-1][left:right + 1])):
                continue

            bottom = top + 1
            while (bottom < len(arr) and
                   # No extra zeroes on the sides
                   (left == 0 or arr[bottom][left-1]) and
                   (right == len(row) - 1 or arr[bottom][right + 1]) and
                   # All zeroes in the row
                   not any(arr[bottom][left:right + 1])):
                bottom += 1

            # The loop ends when bottom has gone too far, so backtrack
            bottom -= 1

            if (  # Height == 1
                  bottom == top or
                  # There are 0s beneath
                  (bottom < len(arr) - 1 and
                   not all(arr[bottom + 1][left:right+1]))):
                continue

            rectangles.append(Rectangle(top, bottom, left, right))

            # Remove the rectangle so that it doesn't affect future searches
            for i in range(top, bottom+1):
                arr[i][left:right+1] = [1] * (right + 1 - left)

    return rectangles

rawDescription: Detecting rectangles (sub-arrays of same element value) in 2-d list


code:
import codecs
f = codecs.open('fubar.txt', 'wt', encoding='utf8')
f.write(u'\u0a0aline1\n\xffline2\n')
f.close()
open('fubar.txt', 'rb').read()
f.mode

rawDescription: Print to UTF-8 encoded file, with platform-dependent newlines?


code:
to_delete_ids = [v.index for v in G.vs if '@enron.com' not in v['label']]
G.delete_vertices(to_delete_ids)

rawDescription: Python igraph: delete vertices from a graph


code:
from multiprocessing import Process
import urllib2

def main():

  try:

    # Read URLs/Destinations from a file
    jobs = []
    with open("urls.txt","r") as ifile:
      for line in ifile:
        jobs.append(line.split(" "))

    # Create a process list to keep track of running processes
    process_list = []
    # Iterate through our jobs list
    for url, save_to in jobs:
      # Create a new process that runs function 'download'
      p = Process(target=download, args=(url, save_to))
      # Save it to a list
      process_list.append(p)
      # Start the process
      p.start()
  except KeyboardInterrupt:
    print("Received keyboard interrupt (ctrl+c). Exiting...")
  finally:
    # Wait for all processes to finish before exiting
    for process in process_list:
       # Wait for this process to finish
       process.join()
    print("All processes finished successfully!")

def download(url, destination):
  # Open a request
  request = urllib2.urlopen(url)
  # Read and save the webpage data to a file
  with open(destination, "w+") as save_file:
    print("Downloading {0}".format(url))
    save_file.write(request.read())

if __name__=="__main__":
  main()

rawDescription: Returning response while server is busy

description: Returning response while server is busy


rawDescription: Truncate `TimeStamp` column to hour precision in pandas `DataFrame`


code:
# select rows where year equals 2007
series2007 = series.loc[dateindex.year == 2007]

rawDescription: Pandas: Select from date in MultiIndex

description: Pandas: Select from date in MultiIndex


code:
for i in f:
    url="http://graph.facebook.com/"+str(int(i))+"?fields=likes"

rawDescription: facebook page info using Graph Api 2.2

description: Facebook page info using Graph Api 2.2


code:
class RedisManager(object):
    def __init__():
        # Connect to redis etc
        self.redis = 12345

redis_manager = RedisManager()

rawDescription: How to handle Redis connection across multiple modules?

description: Handle Redis connection across multiple modules


code:
def test(my_list, i, end):
    my_list[i:end] = [1]*(end-i)
    return my_list
test(range(10), 0, 5)
test(range(10), 5, 10)
test(range(10), 3, 8)

rawDescription: iterating over a sublist in python

description: Iterating over a sublist in python


code:
from functools import wraps

def decor(fun):
    @wraps(fun)
    def living(*args, **kw):
        ...
    return func

rawDescription: Why python decorator will lose func attribute __doc__?


code:
from rest_framework import permissions

class MyPermissionClass(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.META.get('HTTP_SECRET_KEY', None) == 'your key':
            return True
        else:
            return False

rawDescription: How to authenticate connected application with key? Django, Python

description: Authenticate connected application with key? Django, Python


code:
import ast
d={}
with open("scored.txt","r") as filer:
     for line in filer:
            data = ast.literal_eval(line)
            team,score = data[0],data[1]
            if team not in d or d[team] < score:
                d[team] = score

rawDescription: How do I remove duplicate terms with scores from a text file?

description: Remove duplicate terms with scores from a text file


code:
writer = pd.ExcelWriter('pandas_simple.xlsx',
                        engine='xlsxwriter',
                        options={'strings_to_urls': False})

rawDescription: Export Pandas data frame with text column containg utf-8 text and URLs to Excel


rawDescription: How to replace key + null value, Python

description: Replace key + null value, Python


code:
import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')

rawDescription: How can I convert an RGB image into grayscale in Python?

description: Convert an RGB image into grayscale in Python


code:
python_scanf("12 ooops", "%d ooo%s")
python_scanf("12 ooops", "%d uuu%s")

rawDescription: Parsing from format in Python

description: Parsing from format in Python


code:
a = np.arange(10)
a.flags['C_CONTIGUOUS'] # True
b = a[::2]
b.flags['C_CONTIGUOUS'] # False

c = np.ascontiguousarray(b)
c.flags['C_CONTIGUOUS'] # True

rawDescription: np.ascontiguousarray versus np.asarray with Cython

description: Np.ascontiguousarray versus np.asarray with Cython


code:
origin_key = db.Key.from_path('Origin', 123)
winery_key = db.Key.from_path('Winery', 456, parent=origin_key)
wines_query = db.Query(Wine).ancestor(winery_key)

rawDescription: Modeling Hierarchical Data - GAE

description: Modeling Hierarchical Data - GAE


code:
for metric in metric:
    print(metric.field1)  # field on metric model
    print(metric.site)  # related site
    print(metric.site.name)  # name of related site

rawDescription: Django Access Primary Model Attribute with select_related


rawDescription: How to extract sublists from a string in Python?

description: Extract sublists from a string in Python


code: dt = datetime.datetime.strptime('2014-12-01', '%Y-%m-%d')

rawDescription: Get the offset for a specific time and timezone in python


code:
def get():
  # rest of the code ...
  return out

rawDescription: Extract value from a list in another function in Python


code: ss = [pd.Series([ True, False,  True, False,  True]), pd.Series([False,  True,  True, False, False]), pd.Series([False, False,  True, False,  True]), pd.Series([False,  True,  True, False, False]), pd.Series([ True,  True,  True,  True, False])]

rawDescription: Element-wise logical AND on indeterminate number of Pandas Series


code: print (df.username.groupby(df.time.dt.date).apply(lambda x: x.mode()))

rawDescription: Using Agg to find most frequent user per day


code:
new_user.set_attribute("mail", "daniel@example.com")
group = ADGroup.from_dn("so-users")
group.add_member(new_user)

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


code:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        quit()
    elif event.type == pygame.MOUSEBUTTONUP: #This will check if you have unclicked
        not_press = True # and only then reset the condition for the content of Button() to be done again

rawDescription: How to make button not holdable pygame

description: Make button not holdable pygame


rawDescription: Trying to run a python script with crontab every hour, but one section of the python code does not execute


code:
meta = response.xpath('//meta[@id="_bootstrap-neighborhood_card"]')
content = meta.xpath('@content').extract_first()
data = json.loads(content)

rawDescription: Decoding HTML character entities in JSON


code:
os.system("osascript -e 'mount volume \"smb://server/servershare\" \
as user name \"myUserName\" with password \"myPassword\"'")

rawDescription: Mounting SMB network share on desktop

description: Mounting SMB network share on desktop


code:
class VariableManagerClass:
    def __getattr__(self, attr):
        if attr.startswith('_'):
            raise AttributeError(attr)
        return AttributeSetter(self, attr)

rawDescription: How to copy all python instances to a new class?

description: Copy all python instances to a new class


code:
s = "abcde"
result = s[:lb] + s[lb:rb][::-1] + s[rb:]

rawDescription: Reverse a substring of a given string

description: Reverse a substring of a given string


code:
print (C - A * x) / (B)
print (C * (A + B))
print (C * (A + B + A + B + C + x))

rawDescription: python math expressions to latex, verbatim (no reordering, factoring, etc.)

description: Python math expressions to latex, verbatim (no reordering, factoring, etc.)


code:
from pickle import load

credentials = load(open("credentials.p", "rb"))

print(credentials)

rawDescription: Searching and sorting in text files

description: Searching and sorting in text files


code:
projects_map = cache.get('projects_map')
projects_map.get('search term')

rawDescription: Loading dictionary object causing memory spike


code:
from fractions import Fraction
Fraction(0.75)

rawDescription: Python - Parse float string to an integer


code:
def outer():
    string = [""]
    def inner():
        string[0] = "String was changed by a nested function!"
    inner()
    return string[0]

rawDescription: Python overwriting variables in nested functions


rawDescription: comparing two DateTime fields in django template

description: Comparing two DateTime fields in django template


code:
with open (file1, 'r') as f: ids = [line.strip () for line in f]
with open (file2, 'r') as f:
    with open (file3, 'w') as g:
        for line in f:
            if any (id in line for id in ids): g.write (line)

rawDescription: If term in file 1 is in line of file 2, write the whole line in file 2 to file 3


code:
import re
s='abcd2343 abw34324 abc3243-23A'
re.split('(\d+)',s)

rawDescription: Product code looks like abcd2343, what to split by letters and numbers


rawDescription: Why can't I repeat the 'for' loop for csv.Reader? (Python)


code:
l=eval(raw_input("How many CDs are bieng processed"))
m=0
s=0
for i in range(l):
    n=eval(raw_input("How many Tracks are on the CD:"))
    for i in range(n):
        print(i)
        m=m+eval(raw_input("Minutes in Track :"))
        print(m)
        s=s+eval(raw_input("Seconds in Track :"))
        print(s)
sec=m*60+s
minute=sec//60
second=sec%60
print("Total time:",minute,"Minutes",second,"Seconds")

rawDescription: IM trying to run a loop with in another loop, but my out put is always zero


code:
obj = pick.RealisticInfoArray([1, 2, 3], info='foo')
pickle_str = pickle.dumps(obj)
pickle_str
new_obj = pickle.loads(pickle_str)
new_obj.info

rawDescription: Preserve custom attributes when pickling subclass of numpy array


code:
import csv

from collections import Counter

with open(r'C:\test.csv', 'w', newline='') as write_file:
    sevwrite = csv.DictWriter(write_file, ('High', 'Severity', 'Medium', 'Info', 'Low'))
    sevwrite.writeheader()

    for filename in list_of_filenames:
        with open(r'C:\Report.csv', 'r') as f:
            reader = csv.reader(f)
            severities = Counter(r[3] for r in reader)
            sevwrite.writerow(severities)

rawDescription: Counting occurence of words in CSV column and writing to another CSV?


code:
import json
from operator import attrgetter

DATABASE = '/home/chim/Documents/moveit/final/hboImdb.json'

def read_database(database):
    with open(database) as data_file:   #opens the imdb database we created
        response = json.load(data_file)

    hbo_by_rating = sorted(response, key=attrgetter('imdbRating'), reverse=True)
    hbo_by_alpha = sorted(response, key=attrgetter('Title'))
    return hbo_by_rating, hbo_by_alpha

hbo_by_rating, hbo_by_alpha = read_database(DATABASE)

rawDescription: My HTML table prints \u0027 instead of an apostrophe


code:
def count_fx(s):
    return s.count(':')

rawDescription: pandas: count string criteria across down rows

description: Pandas: count string criteria across down rows


rawDescription: How to remove blank 2D list rows?

description: Remove blank 2D list rows


code: df = df[df.CURRENT_DATE > df.START_DATE] # just focusing on cases with calculation

rawDescription: vectorization of date range function for transformation of pandas dataframe

description: Vectorization of date range function for transformation of pandas dataframe


code:
import string
clean = lambda dirty: ''.join(filter(string.printable.__contains__, dirty))

rawDescription: Removing non-printable "gremlin" chars from text files


rawDescription: Regular Expression with python

description: Regular Expression with python


rawDescription: Matplotlib: move graph to the right

description: Matplotlib: move graph to the right


code:
from traits.api import HasTraits, Instance, Str, Property, Dict
from traitsui.api import View, Item, CheckListEditor

class Bclass(HasTraits):
    options = Dict({'one': 1, 'two': 2})

class Aclass(HasTraits):
    bclass = Instance(Bclass)
    abc = Str

    options = Property(Str, depends_on='bclass.options')
    def _get_options(self):
        return self.bclass.options.keys()

    traits_view = View(
        Item(name='abc', editor=CheckListEditor(name='options')),
    )

rawDescription: enthought traits UI, add values dynamically to 'values' trait of CheckListEditor

description: Enthought traits UI, add values dynamically to 'values' trait of CheckListEditor


code: d

rawDescription: How to convert JavaScript dictionary into Python syntax

description: Convert JavaScript dictionary into Python syntax


code:
def redirected_printed_output(module_call):
    # the pipe would fail for some reason if I didn't write to stdout at some point
    # so I write a space, then backspace (will show as empty in a normal terminal)
    sys.stdout.write(' \b')
    pipe_out, pipe_in = os.pipe()
    # save a copy of stdout
    stdout = os.dup(1)
    # replace stdout with our write pipe
    os.dup2(pipe_in, 1)

    # check if we have more to read from the pipe
    def more_data():
        r, _, _ = select.select([pipe_out], [], [], 0)
        return bool(r)

    # read the pipe, writing to (former) stdout
    def write_pipe_to_stdout():
        while more_data():
            os.write(stdout, os.read(pipe_out, 1024))

    done = False
    def read_loop():
        # rewrite the pipe out to stdout in a loop while the call is running
        while not done:
            write_pipe_to_stdout()
        # Finish the remnants
        write_pipe_to_stdout()

    t = threading.Thread(target=read_loop)
    t.start()

    module_call()

    done = True
    t.join() # wait for the thread to finish

    # put stdout back in place
    os.dup2(stdout, 1)

rawDescription: Capture c++ shared library log entries with ctypes


code:
import collections

def myzip(*args):
    if all(isinstance(arg, collections.Iterable) for arg in args):
        return [myzip(*vals) for vals in zip(*args)]
    return args

rawDescription: Python deep zip

description: Python deep zip


code:
mask = pd.isnull(columns[0])
columns[0] = columns[0].fillna('')

rawDescription: Pandas read multiindexed csv with blanks


rawDescription: recursively concatenate string in python

description: Recursively concatenate string in python


code:
import math
inputDict = {"in" : [0.01, -0.07, 0.09, -0.02], "and" : [0.2, 0.3, 0.5, 0.6], "to" : [0.87, 0.98, 0.54, 0.4]}
def cosine_similarity(vec1,vec2):
    sum11, sum12, sum22 = 0, 0, 0
    for i in range(len(vec1)):
        x = vec1[i]; y = vec2[i]
        sum11 += x*x
        sum22 += y*y
        sum12 += x*y
    return sum12/math.sqrt(sum11*sum22)

result = {}
for key,value in inputDict.items():
    temp,tempDict= 0,{}
    for keyC,valueC in inputDict.items():
        if keyC == key:
            continue
        temp = cosine_similarity(value,valueC)
        tempDict[keyC] =temp
    result[key]= tempDict

print(result)

rawDescription: How to iterate over the dictionary keys to calculate cosine similarity using the values?

description: Iterate over the dictionary keys to calculate cosine similarity using the values


code: soup = None

rawDescription: Using a script to set variables in IDLE

description: Using a script to set variables in IDLE


code:
foo = namedtuple("foo", "bar, baz")
Foo = foo('bar', 'baz')
foo.bar
foo.baz

rawDescription: coding style: lightweight/simplest way to create instances supporting attribute assignment?

description: Coding style: lightweight/simplest way to create instances supporting attribute assignment


rawDescription: using Python reduce over a list of pairs

description: Using Python reduce over a list of pairs


code:
sysTime = asctime()
timestamp = systime.split()[3]
separator = timestamp[2]
hour = timestamp.split(separator)[0]
while hour < 8:
    # just wait
    sysTime = asctime()
    timestamp = systime.split()[3]
    separator = timestamp[2]
    hour = timestamp.split(separator)[0]

# now, it's just become 8:00 AM
while hour < 17: # until 5:00 PM
    sysTime = asctime()
    timestamp = systime.split()[3]
    separator = timestamp[2]
    hour = timestamp.split(separator)[0]

    # start your thread to do whatever needs to be done

rawDescription: Have python run script at X:00 am

description: Have python run script at X:00 am


code:
elm = driver.find_element_by_class_name('next')
elm.click()

rawDescription: Python Selenium clicking next button until the end


code: json_data_rdd.flatMap(lambda j: processDataLine(j, arg1, arg2))

rawDescription: Spark RDD - Mapping with extra arguments


rawDescription: Index of an element in a numpy array

description: Index of an element in a numpy array


code:
whole_numbers = np.arange(1000000, dtype=float)
fractional = np.arange(0, 100000, 0.1, dtype=float)
float_to_int(whole_numbers)
float_to_int(fractional)

rawDescription: Convert float64 to int64 using "safe"

description: Convert float64 to int64 using "safe"


code:
where0s = [i for i in range(len(pieces)) if pieces[i] == '00']
where0s

rawDescription: replace or remove one null (python)

description: Replace or remove one null (python)


code:
import module
othername = module
del module

rawDescription: Finding the local name of a module from within that module


code:
# general imports
import random, time
from multiprocessing import Process, Queue

# for matplotlib
import random
import numpy as np
import matplotlib
matplotlib.use('GTKAgg') # do this before importing pylab

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

def matplotLibAnimate(q,points):

    # set up initial plot
    fig = plt.figure()
    ax = fig.add_subplot(111)

    circles = []
    for point in points:
        ax.add_patch(Circle(point,0.1))

    a_line, = ax.plot(*zip(*points))
    a_line.set_color('g')
    a_line.set_lw(2)

    currentNode = None
    def animate(currentNode = currentNode):
        while 1:
            newNode = q.get()
            if currentNode: currentNode.remove()
            circle = Circle(newNode,0.1)
            currentNode = ax.add_patch(circle)
            circle.set_fc('r')
            fig.canvas.draw()

    # start the animation
    import gobject
    gobject.idle_add(animate)
    plt.show()

#initial points
points = ((-0.25, -1.0),(0.7, -0.7),(1,0),(0.7,1),(-0.25,1.2),(-1,0.5),(-1,-0.5),(-0.25, -1.0))
q = Queue()
p = Process(target = matplotLibAnimate, args=(q,points,))
p.start()

# feed animation data
while 1:
    time.sleep(random.randrange(4))
    q.put(random.sample(points,1)[0])

rawDescription: Matplotlib in Python - Drawing shapes and animating them


rawDescription: How do you set the absolute position of figure windows with matplotlib?

description: Set the absolute position of figure windows with matplotlib


code: s.resample('24h', base=5)

rawDescription: Resample daily pandas timeseries with start at time other than midnight


rawDescription: Stuck at comparing date of birth in the form yyyy/mm/dd


code:
def distance(left, right):
    return sum((l-r)**2 for l, r in zip(left, right))**0.5

class NearestColorKey(object):
    def __init__(self, goal):
        self.goal = goal
    def __call__(self, item):
        return distance(self.goal, item[1])

rawDescription: Color classification library

description: Color classification library


rawDescription: compare column values of dataframes with non-unique indices of different length

description: Compare column values of dataframes with non-unique indices of different length


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup("""

Modern Europe & the World - Dewey

    92%

""")

grades = {}

for tr in soup.find_all("tr"):
    td_text = [td.text.strip() for td in tr.find_all("td")]
    grades[td_text[0]] = td_text[1]

rawDescription: Using beautiful soup to pull text from multiple <tr>'s


code:
from itertools import groupby
import json
matrix = [
    ['JAN',  '1', 'abc'],
    ['FEB',  '7', 'xyz'],
    ['FEB',  '4', 'abc'],
    ['MAR',  '3', 'xyz'],
    ['DEC', '12', 'xyz']
]
months = [x[0] for x in matrix]
items = [[x[2], int(x[1])] for x in matrix]
items = sorted(items, key=lambda x: x[0])
items = groupby(items, lambda x: x[0])
items = [{"group": k, "data": [x[1] for x in g]} for k, g in items]
result = {
    "month": months,
    "items": items
}
print (json.dumps(result, sort_keys=True, indent=4, separators=(',', ': ')))

rawDescription: python - create json file from input matrix by grouping rows

description: Python - create json file from input matrix by grouping rows


code: df.groupby('id', sort = False).max()

rawDescription: efficiently find maxes of one column over id in a Pandas dataframe

description: Efficiently find maxes of one column over id in a Pandas dataframe


code:
import itertools, operator

def catalog(fields,people):
    cur_field = operator.itemgetter(fields[0])
    groups = itertools.groupby(sorted(people, key=cur_field),cur_field)
    if len(fields)==1:
        return dict((k,list(v)) for k,v in groups)
    else:
        return dict((k,catalog(fields[1:],v)) for k,v in groups)

rawDescription: catalogue a list of dictionaries

description: Catalogue a list of dictionaries


code: from spells import cast,spellmaker

rawDescription: Python too slow - Can I rewrite engine in lower level and cp scripts?


rawDescription: Remove specific characters from list python


rawDescription: Easy way to keep counting up infinitely

description: Easy way to keep counting up infinitely


code:
import pandas as pd
from itertools import permutations

def subtract_group(df, col):
    pid = df['pid'].unique()

    # select piece with pid == i
    segment = lambda df, i: df[df['pid'] == i].reset_index()[col]

    for x, y in permutations(pid, 2):
        result_df = pd.DataFrame(segment(df, x) - segment(df, y))

        # rename columns
        result_df.columns=["%sp%d-%sp%d" % (c, x, c, y) for c in col]

        # insert pid column
        result_df.insert(0, 'pid', '-'.join([str(x), str(y)]))

        yield result_df

rawDescription: python pandas groupby and subtract columns from different groups

description: Python pandas groupby and subtract columns from different groups


code:
url_patterns1 = [
    (r'/web/([^/]+)/', IndexHandler),
    (r'/web/([^/]+)/test', IndexTestDic)
]

url_patterns2 = [
    (r'/web/([^/]+)/category/([^/]+)', CategoryHandler),
    (r'/web/([^/]+)/channel', ChannelHandler),
    (r'/web/([^/]+)/savechannel', savechannel),
]

rawDescription: Is it possible to break Python Tornado's urls into multiple files?


rawDescription: NumPy Vectorize a function, unknown shape


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setWindowTitle(self.tr('Document Printer'))
        self.editor = QtGui.QTextEdit(self)
        self.editor.textChanged.connect(self.handleTextChanged)
        self.buttonOpen = QtGui.QPushButton('Open', self)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonPrint = QtGui.QPushButton('Print', self)
        self.buttonPrint.clicked.connect(self.handlePrint)
        self.buttonPreview = QtGui.QPushButton('Preview', self)
        self.buttonPreview.clicked.connect(self.handlePreview)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.editor, 0, 0, 1, 3)
        layout.addWidget(self.buttonOpen, 1, 0)
        layout.addWidget(self.buttonPrint, 1, 1)
        layout.addWidget(self.buttonPreview, 1, 2)
        self.handleTextChanged()

    def handleOpen(self):
        path = QtGui.QFileDialog.getOpenFileName(
            self, self.tr('Open file'), '',
            self.tr('HTML files (*.html);;Text files (*.txt)'))
        if not path.isEmpty():
            stream = QtCore.QFile(path)
            if stream.open(QtCore.QIODevice.ReadOnly):
                info = QtCore.QFileInfo(path)
                text = QtCore.QString.fromLocal8Bit(stream.readAll())
                if info.completeSuffix() == 'html':
                    self.editor.setHtml(text)
                else:
                    self.editor.setPlainText(text)
            stream.close()

    def handlePrint(self):
        dialog = QtGui.QPrintDialog()
        if dialog.exec_() == QtGui.QDialog.Accepted:
            self.editor.document().print_(dialog.printer())

    def handlePreview(self):
        dialog = QtGui.QPrintPreviewDialog()
        dialog.paintRequested.connect(self.editor.print_)
        dialog.exec_()

    def handleTextChanged(self):
        enable = not self.editor.document().isEmpty()
        self.buttonPrint.setEnabled(enable)
        self.buttonPreview.setEnabled(enable)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: Print A Text Through A Printer Using PyQt4


rawDescription: How to create a given size list of lists from a dictionary?

description: Create a given size list of lists from a dictionary


code: d = [x + y[1:] for x, y in zip(a, b)]

rawDescription: Append list elements to a list of tuples


code:
result == my_func()
if result is None:
    foo()
else:
    bar(result)

rawDescription: Testing if a function returns a list or a bool


code:
current_players = (dict((k,v)
    for k,v in list(team.items())
        for player in v['player']
            if player['year'] == 2013))

rawDescription: How to format list and dictionary comprehensions

description: Format list and dictionary comprehensions


code:
l = [(48, 228), (96, 204), (120, 192), ... ]
# 'width' is the width of your bidimensional table (grid)
bidimensional = [l[a*width:(a+1)*width] for a in xrange(len(l)/width)]

rawDescription: How do I create bidimensional table from list?

description: Create bidimensional table from list


rawDescription: Parsing a specific element from XML using Python/ET


rawDescription: Changing dtype of structured array zeros out string data


code:
def create(args):
    # do the create stuff
    print(args)

def update(args):
    # do the update stuff
    print(args)

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands',
                                   description='valid subcommands',
                                   help='additional help')

create_parser = subparsers.add_parser('create')
create_parser.add_argument('name', type=str)
create_parser.set_defaults(func=create)

update_parser = subparsers.add_parser('update')
update_parser.set_defaults(func=update)

rawDescription: How to conditionally make python's argparse module require additional arguments

description: Conditionally make python's argparse module require additional arguments


code:
from multiprocessing import Process, Semaphore
from cat import Cat
from dog import Dog
from rabbit import Rabbit

semaphore = Semaphore(2)

cat = Cat()
dog = Dog()
rabbit = Rabbit()

def run(animal, sema):
    with sema:
        animal.worker_run(*args)

cat_proc = Process(target=run, args=(cat, semaphore))
dog_proc = Process(target=run, args=(dog, semaphore))
rabbit_proc = Process(target=run, args=(rabbit, semaphore))

cat_proc.start()
dog_proc.start()
rabbit_proc.start()

cat_proc.join()
dog_proc.join()
rabbit_proc.join()

rawDescription: How to control the maximum concurrently running processes?

description: Control the maximum concurrently running processes


code:
import pexpect

child = pexpect.spawn('lua -i -l demo')
child.readline()

child.sendline('test("a", "b")')
child.readline()
print(child.readline())

child.sendline('test2("c")')
child.readline()
print(child.readline())

child.close()

rawDescription: Run Lua script from Python

description: Run Lua script from Python


code: dct1 = {v[0]: v[1:] for v in lst1}

rawDescription: Function to convert List to Dictionary and viceversa using Python


code:
with open('pathToNewZip.zip', 'wb') as archive:
  archive.write(inMemoryZip.getvalue())

rawDescription: writing StringIO back to disk in python

description: Writing StringIO back to disk in python


code:
d = {'ONE' : (4, 6, 9), 'TWO' : (3, 8, 10), 'FOUR': (2, 5, 8), 'THREE': 0}
sorted(d.iteritems(),
       key=lambda i: i[1][2] if isinstance(i[1], tuple) else i[1])

rawDescription: Dictionary With Multiple Values To Nested List


code:
res = {}
files_to_merge = ['a.csv', 'b.csv']
for filename in files_to_merge:
    f=open(filename)
    for line in f:
        (id, rest) = line.split(',', 1)
        if rest[-1] != '\n': #last line may be missing a newline
            rest = rest + '\n'
        res[id] = rest
    f.close()

f=open('c.csv', 'w')
f.write("\"id\","+res["\"id\""])
del res["\"id\""]
for id, rest in sorted(res.iteritems()):
    f.write(id+","+rest)
f.close()

rawDescription: How to merge two csv files?

description: Merge two csv files


code:
from pprint import pprint
from collections import defaultdict

tets_sharing_vertex = defaultdict(list)
for k, v in vertices_on_tetrahedron.items():
    for x in v:
        tets_sharing_vertex[x].append(k)

pprint(tets_sharing_vertex)

rawDescription: Complicated referencing with dictionaries, python


code:
if row < 3 and column < 4:
    matrix[row][column] = T1

rawDescription: How to change values in nested list python

description: Change values in nested list python


rawDescription: Pandas to_dict modifying numbers

description: Pandas to_dict modifying numbers


code: runningSum += 3.25 * np.sum(rs) +  .75 * np.dot(rs, rs)

rawDescription: Masked Numpy arrays much slower than normal numpy arrays


code:
# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        # <create the rest of your GUI here>

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

rawDescription: Best way to structure a tkinter application

description: Structure a tkinter application


rawDescription: Python: Writing to a csv file from a 'list' of {(tuples): value} dicts


code:
import cv2

src_img = cv2.imread("blob.png")
gray_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)

contours = cv2.findContours(gray_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)[1]

print(contours)

# Choose one:

# Draw only first contour from the list
cv2.drawContours(src_img, contours, 0, (0,255,0), 2)
# Pass only the first contour (v1)
cv2.drawContours(src_img, [contours[0]], -1, (0,255,0), 2)
# Pass only the first contour (v2)
cv2.drawContours(src_img, contours[0:1], -1, (0,255,0), 2)

cv2.imshow("Contour", src_img)
cv2.waitKey()

rawDescription: Contour shows dots rather than a curve when retrieving it from the list, but shows the curve otherwise


code:
with open("file1.txt", 'r') as f1:
        f1 =f1.read().split()

rawDescription: Python Text Document Translation Comparison


code:
def my_zip(d):
  t,w = d.iloc[0,0],d.iloc[0,1:]
  return pd.DataFrame(zip([t]*len(w), w)).dropna()

df = (pd.read_csv('tales-01.txt',header=None)
      .groupby(level=0)
      .apply(my_zip)
      .reset_index(drop=True)
      .rename_axis({0:'text',1:'word'},axis=1)
      )

rawDescription: Python: create edge list for bipartite graph using pandas


code:
import sys
sys.modules[__name__] = MyClass(__name__)

rawDescription: Use alias for a property in Python at module level


code:
import sqlite3
import datetime as DT

this_year = (DT.date(DT.date.today().isocalendar()[0], 1, 1))
# this_year = ("'"+str(this_year)+"'")
# this_year = DT.date(DT.date.today().year,1,1)
with sqlite3.connect(':memory:') as conn:
    cursor = conn.cursor()
    sql = '''CREATE TABLE TEST_TABLE
        ("ID" TEXT,
        "DATE_IN" DATE,
        "WEEK_IN" number)
    '''
    cursor.execute(sql)
    sql = 'INSERT INTO TEST_TABLE(ID, DATE_IN, WEEK_IN) VALUES (?,?,?)'
    cursor.executemany(sql, [[1,'2012-03-25',13],[2,'2013-03-25',13],])
    sql = 'SELECT ID FROM TEST_TABLE where WEEK_IN = 13 and DATE_IN > ?'
    cursor.execute(sql, [this_year])
    for row in cursor:
        print(row)

rawDescription: Python SQLITE3 SELECT query with datetime calculated string not working


code:
# Here I'm assuming you get the data from the drone into parameter raw
# 1 frame contains 640*480*3/2 = 460800 bytes
import numpy as np

# turn raw into a numpy array
raw = np.array(raw)

# calculate where each plane starts and stops
wh = 640 * 480
p = (0, wh, wh, wh/4*5, wh/4*5, wh/2*3)

# Now use slizing to extract the different planes
yy = np.empty(640*480, dtype=np.uint8)
cb = np.empty(640*480/4, dtype=np.uint8)
cb = np.empty(640*480/4, dtype=np.uint8)

yy = raw[p[0]:p[1]]
cb = raw[p[2]:p[3]]
cr = raw[p[4]:p[5]]

rawDescription: YUV420p to other formats, color shift problems


rawDescription: Finding the index of the second match of a regular expression in python


code:
a = A()
del a[:]
del a[2]
del a["test"]

rawDescription: Python slice with del statement

description: Python slice with del statement


code:
from flask import Flask, render_template, redirect, url_for
from flask_wtf import Form
from wtforms import SubmitField

app = Flask(__name__)
app.secret_key = 'davidism'

class StatsForm(Form):
    user_stats = SubmitField()
    room_stats = SubmitField()

@app.route('/stats', methods=['GET', 'POST'])
def stats():
    form = StatsForm()

    if form.validate_on_submit():
        if form.user_stats.data:
            return redirect(url_for('user_stats'))
        elif form.room_stats.data:
            return redirect(url_for('room_stats'))

    return render_template('stats.html', form=form)

app.run(debug=True)

rawDescription: Determine which WTForms button was pressed in a Flask view


code:
def size_list(mypath):
    my_list = []
    with open("PathTest.txt","w") as of:
        for root, dirs, files in os.walk(mypath):
            for f in files:
                my_file = os.path.join(root, f)
                file_size = getsize(my_file)
                my_list.append((my_file, file_size))
                fo.write("\nPath: " +  my_file)
                fo.write("\tSize: " +  str(file_size) + " bytes")

rawDescription: Python file path and size

description: Python file path and size


code: np.delete(a, list(range(0, a.shape[0], 8)), axis=0)

rawDescription: delete every nth row or column in a matrix using Python

description: Delete every nth row or column in a matrix using Python


code:
with open(file) as f:
    for line in f:
        if var1 in line:
            print(re.search(r'.*(\s+'+ var1 + r':)', s).group(1))

rawDescription: Python regex: How to match a string at the end of a line in a file?


code:
dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)

rawDescription: Can pandas automatically recognize dates?


code:
with open('customers.txt') as customers:
    sorted_no = {}
    for ind, line in enumerate(customers,1):
        rows=line.split(";")
        sorted_no[rows[0]] = ind

rawDescription: Assign values to dictionary by order they were added


rawDescription: Is it all right to put a large non-Python file into site-packages?


code:
def splitList(myList, option):
    myList2 = []
    if option == 0:
        for element in myList:
            if abs(element)>5:
                myList2.append(element)
    return myList2

rawDescription: Absolute value and adding to a list

description: Absolute value and adding to a list


code: vals = list(map(int, re.findall(r'\((\d+)\)', Field)))

rawDescription: Storing selected portion from the string in Variables in Python


code:
import numpy as np
import pandas as pd
investment_df = pd.DataFrame(np.arange(10), columns=['investment'])
investment_df['decile'] = pd.qcut(investment_df['investment'], 10, labels=False)
investment_df['quintile'] = pd.qcut(investment_df['investment'], 5, labels=False)
investment_df

rawDescription: How to create a Decile and Quintile columns to rank another variable based on size using Python, Pandas?

description: Create a Decile and Quintile columns to rank another variable based on size using Python, Pandas


rawDescription: Python regex - Match words only containing A, B, or C


rawDescription: List of tuples deletion

description: List of tuples deletion


code:
def function(input1, input2):
    mapping = []
    for item in input1:
        risks = {"A":0, "B":0, "C":0, "D":0, "E":0}
        temp = []
        for row in input2:
            if item in row[0]:
                for key in risks.keys():
                    if row[1] == key:
                        risks[key] += 1
        temp.append(item)
        for key in risks.keys():
            temp.append(risks[key])
        mapping.append(temp)
    return mapping

rawDescription: Python nested loop comparing two lists and updating a dictionary


rawDescription: How to retrieve the list of models for model A which contains a foreign key to B?

description: Retrieve the list of models for model A which contains a foreign key to B


code:
for key in dict.iterkeys(): ...

for value in dict.itervalues(): ...

for key, value in dict.iteritems(): ...

rawDescription: Learn Python The Hard Way - Exercise 39

description: Learn Python The Hard Way - Exercise 39


code:
from nltk.corpus import swadesh
de2en = [(i.lower(),j.lower()) for i,j in swadesh.entries(['de','en'])]
translate = dict(de2en)
translate.update(swadesh.entries(['de','en']))
translate['hund']
translate['Hund']

rawDescription: How to translate words in NTLK swadesh corpus regardless of case - python

description: Translate words in NTLK swadesh corpus regardless of case - python


code: PASS="'pass'"

rawDescription: Running parameterized python script within bash script


code:
class A:
    def __init__(self):
        print("A")

class B:
    def __init__(self):
        print("B")

class C(A,B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

rawDescription: Call constructor in multiple derived classes


code:
import inspect

def make_key_maker(func):
    args_spec = inspect.getargspec(func)

    def key_maker(*args, **kwargs):
        left_args = args_spec.args[len(args):]
        num_defaults = len(args_spec.defaults or ())
        defaults_names = args_spec.args[-num_defaults:]

        if not set(left_args).symmetric_difference(kwargs).issubset(defaults_names):
            # We got an error in the function call. Let's simply trigger it
            func(*args, **kwargs)

        start = 0
        key = []
        for arg, arg_name in zip(args, args_spec.args):
            key.append(arg)
            if arg_name in defaults_names:
                start += 1

        for left_arg in left_args:
            try:
                key.append(kwargs[left_arg])
            except KeyError:
                key.append(args_spec.defaults[start])

            # Increase index if we used a default, or if the argument was provided
            if left_arg in defaults_names:
                start += 1
        return tuple(key)

    return key_maker

rawDescription: Identifying equivalent varargs function calls for memoization in Python


code:
conn = engine.connect().execution_options(sqlite_raw_colnames=True)
result = conn.execute(stmt)

rawDescription: sqlalchemy+sqlite stripping column names with dots?

description: Sqlalchemy+sqlite stripping column names with dots


code:
from math import pi, hypot, sqrt

class Circle:
    def __init__(self, x, y, r):
        self.x = x
        self.y = y
        super().__setattr__('r', r)
        super().__setattr__('area', pi * self.r * self.r)
        super().__setattr__('circumference', 2 * pi * self.r)
        super().__setattr__('distance_to_origin',
                            abs(sqrt(self.x * self.x + self.y * self.y) - self.r))

    def __setattr__(self, name, value):
        if name in ['x', 'y']:
            if isinstance(value, int):
                print('we can set x,y')
                super().__setattr__(name, value)
            else:  # value isn't an int
                raise TypeError('Expected an int for: {}'.format(name))
        else:
            raise AttributeError('Cannot set attribute: {}'.format(name))

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


code:
import fileinput
for line in fileinput.input(['file1', 'file2']):
   pass

rawDescription: In Python, how do I iterate over one iterator and then another?


code: summary

rawDescription: how to apply different functions to each group of pandas groupby?

description: Apply different functions to each group of pandas groupby


code:
health = 20 if health > 20 else health
health = min(20, health)

rawDescription: Python: How to stop a variable from exceeding a value?


code:
import os
open_files = [open(os.path.join(some_path, f)) for f in os.listdir(some_path)
              if os.path.isfile(f)]

rawDescription: Python - Opening successive Files without physically opening every one


rawDescription: Return dictionary name based on values

description: Return dictionary name based on values


code:
[x for x in (1, 2, 3)]  # Get all items in the tuple (1, 2, 3).
[x for x in (1, 2, 3) if x % 2]  # Only get the items where x % 2 is True.

rawDescription: What is an expression such as [d[k] for k in d] called?


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided

def windowed_view(arr, window, overlap):
    arr = np.asarray(arr)
    window_step = window - overlap
    new_shape = arr.shape[:-1] + ((arr.shape[-1] - overlap) // window_step,
                                  window)
    new_strides = (arr.strides[:-1] + (window_step * arr.strides[-1],) +
                   arr.strides[-1:])
    return as_strided(arr, shape=new_shape, strides=new_strides)

rawDescription: Window overlap in Pandas

description: Window overlap in Pandas


code: xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)

rawDescription: Copy string - Python

description: Copy string - Python


code: [word for data in input_list for word in (pluralize(data), data)]

rawDescription: Python - List comprehension how to insert 2 elements at a time?


rawDescription: Best way to replace \x00 in python lists?

description: Replace \x00 in python lists


code: chunks = [data[x:x+100] for x in range(0, len(data), 100)]

rawDescription: Split a python list into other "sublists" i.e smaller lists


code:
t = [["a", "b"], ["c", "d"], ["a", "e"], ["f", "g"], ["c", "d"]]

from collections import OrderedDict

t[:] = map(list, OrderedDict.fromkeys(map(tuple, t)))

print(t)
[['a', 'b'], ['c', 'd'], ['a', 'e'], ['g', 'f']]

rawDescription: Removing duplicate lists within another list


code:
import clalendar
def word_find(s):
      return [i for i in re.findall(r'[a-zA-Z]+',s) if i.capitalize() not in calendar.month_name and i.capitalize() not in calendar.month_abbr]

rawDescription: Separating a date from a string in Python


code: your_list.sort(key=lambda x: x[1], reverse=True)

rawDescription: Trying to sort a list very specifically in Python


code:
data_array = ctypes.c_uint8 * len(data)
result = myfunc(data_array(*data),ctypes.c_uint8(len(data)))

rawDescription: Wrapped C library in Python, but returned array is unchanged


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

class HomeScreen(BoxLayout):
    pass

class Screen1(Screen):
    pass

class SplitScreenApp(App):
    def build(self):

        return HomeScreen()

if __name__ == "__main__":
    SplitScreenApp().run()

rawDescription: Split Screen in Kivy?

description: Split Screen in Kivy


code: import testingA

rawDescription: Python creating a module

description: Python creating a module


code:
'foobar\n'.rstrip('\n')
'foobar'.rstrip('\n')
'foobar  \t \n'.rstrip()

rawDescription: removing the "\n" for every line except for the last line

description: Removing the "\n" for every line except for the last line


code:
ttk = None
with open('somefile.txt') as f:
    for line in f:
        if line.startswith('Mid-access token:'):
            ttk = next(f).strip()

print(ttk)

rawDescription: Reading a specific text in a file and assigning to a variable in python


code:
counts, edges = np.histogram(x, bins=bins)
counts

rawDescription: python average bitrate per second

description: Python average bitrate per second


code:
map(len, list_of_lists)
list(map(len, list_of_lists))

rawDescription: How to apply a function to each sublist of a list in python?

description: Apply a function to each sublist of a list in python


rawDescription: Pandas Dataframe GroupBy - Displaying Group Statistics


code:
def __init__(self):
    self._logger = logging.getLogger(__name__)
    self._logger.setLevel(logging.INFO)

rawDescription: Python Abstract Base Classes: Why doesn't abc prevent instantiation?


code:
def __contains__(self, val):
    curr = self.front
    while curr is not None:
        if curr._value == val: return True
        curr = curr._next
    return False

def intersection(self, rs):
    answer = List()
    curr = self.front
    while curr is not None:
        if curr._value in rs: answer.insert(-1, curr._value)
    return answer

rawDescription: python-Linked list implemention

description: Python-Linked list implemention


code:
import modA
class A2(modA.A):
   ...

rawDescription: How to split a Python module into multiple files?

description: Split a Python module into multiple files


code: [k for k, v in child_parent.items() if v == 0]

rawDescription: Create a list of keys given a value in a dictionary


code:
from string import ascii_lowercase
try:
    # Python 2
    from string import maketrans
except ImportError:
    # Python 3 made maketrans a static method
    maketrans = str.maketrans

cipher_map = maketrans(ascii_lowercase, ascii_lowercase[1:] + ascii_lowercase[:1])
encrypted = text.translate(cipher_map)

rawDescription: How to replace characters in string by the next one?

description: Replace characters in string by the next one


code:
from news.models import New
from news.forms import MyNewForm
class MyNew(admin.ModelAdmin):
    form = MyNewForm

admin.site.register(New,MyNew)

rawDescription: State Control/Workflow in Django

description: State Control/Workflow in Django


code: [next(d.iterkeys()) for d in a]

rawDescription: swap one element list to int

description: Swap one element list to int


code:
@tornado.gen.coroutine
def authentication(fun):
    def test(self, *args, **kwargs):
        ...
    return test

rawDescription: how to use coroutine in custom decorator when working with db operations in tornado

description: Use coroutine in custom decorator when working with db operations in tornado


rawDescription: Numpy matrix combination

description: Numpy matrix combination


code:
from __future__ import division # Required only for Python 2.x
from math import ceil
from itertools import takewhile

rdd1 = sc.parallelize([
    (1, 1, 2, 10),
    (2, 1, 5, 11),
    (3, 2, 3, 11),
    (4, 3, 4, 12),
    (5, 3, 5, 11),
])

def generate(start, end, step):
    def _generate(id, created, destroyed, price):
        # Smallest ts >= created
        start_for_record = int(ceil((created - start) / step) * step + start)
        rng = takewhile(
            lambda x: created <= x < destroyed,
            xrange(start_for_record, end, step)) # In Python 3.x use range
        for i in rng:
            yield i, price

    return _generate

result = rdd1.flatMap(lambda x: generate(1, 6, 1)(*x)).groupByKey()

rawDescription: Spark - Nested RDD Operation

description: Spark - Nested RDD Operation


code:
path = "/home/msvalkon/Pictures/Sample Album"
for fname in os.listdir(path):
    print("\<description>Test. <![CDATA[<img src='./files/{}'>]]>=</description>\n".format(fname))

rawDescription: String formatting in a loop

description: String formatting in a loop


code:
# profile/__init__.py
default_app_config = 'profile.apps.ProfileConfig'

rawDescription: how a django reusable apps can initialize itself?

description: How a django reusable apps can initialize itself


code:
def make_key(my_tuple):
    return -my_tuple[1], my_tuple[0]

sorted_list_of_tuples = sorted(list_of_tuples, key=make_key, reverse=True)

rawDescription: Sort a list of tuples with two tuple entries in opposite order


code: items = [entry.item for entry in cartEntries]

rawDescription: Python: How to refactor this simple list code?


code:
if somestring in d[key]:
    d[key][somestring] += 1
else:
    d[key][somestring] = 1

rawDescription: Pythonic way for checking if value exists in dictionary of dictionaries and taking corresponding actions


code:
fig, axes = plt.subplots(nrows=4, sharex=True)
for y, ax in zip(ydata, axes):
    ax.plot(x, y, color='salmon')
    ax.locator_params(axis='y', nbins=5, prune='both')

fig.subplots_adjust(hspace=0)
plt.show()

rawDescription: Python Numpy 2D plot set total number of y-tics with autoscaling


code:
from subprocess import call
call("maf2hal inputfile outputfile", shell=True)

rawDescription: What is the statement to use for executing a command allied with a different software in python?


code:
def updateMessages(self):
    MsgList = self.aMessages.values()
    model = self.ui.Messages.model()

    for i in xrange(len(MsgList)):
        value = MsgList[i][0]

        index = model.index(i, 0)
        model.setData(index, MsgList[i][1])
        model.setData(index, value, QtCore.Qt.UserRole)
        model.setData(index, MsgList[i][2], QtCore.Qt.UserRole + 1)
        self.ui.Messages.setRowHidden(i, not value)
    del MsgList
    model.setSortRole(QtCore.Qt.UserRole + 1)
    model.sort(0)

rawDescription: Message displaying in QListWidget/View on boolean condition


code:
positions = [(100, 30), (250, 90), (42, 623)]
for position in positions:
    screen.blit(platormimg, position)

rawDescription: In pygame, can i use a list to blit an object multiple times with only one line of code?


rawDescription: Python string to list best practice

description: Python string to list best practice


code:
dataPoints = []
for i in range(5):
    user = input('Enter city followed by temperature')
    data = user.split()
    dataPoints.append((data[0], int(data[1])))
d = dict(dataPoints)

rawDescription: Adding entered items separated by spaces into a dictionary. Python


code:
def parseTags(str):
    return filter(None, map(sanitizeTag, str.split(',')))

def sanitizeTag(str):
    words    = filter(lambda c: c.isalnum() or c.isspace(), str).split()
    numWords = len(words)
    if numWords == 0:
        return None
    elif numWords == 1:
        return words[0]
    else:
        words0 = words[0].lower() if words[0][0].islower() else words[0].capitalize()
        return words0 + ''.join(w.capitalize() for w in words[1:])

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code:
from xml.sax.saxutils import *
import sys
output = sys.stdout
encoding = 'utf-8'
xmlwriter = XMLGenerator(output, encoding, short_empty_elements=True)
xmlwriter.startDocument()
xmlwriter.startElement(name="foo", attrs={})
xmlwriter.endElement(name="foo")

rawDescription: XMLGenerator python sax library: write out inline / closed tag


code:
x = ((("A","B"),("C","D")),"E")
from pprint import pprint
pprint(x, width=1)

rawDescription: Visual alternative for hierarchical tree: (((A,B),(C,D)),E)?


rawDescription: Working with bit streams

description: Working with bit streams


code:
import operator, collections

home = operator.itemgetter(0,2)    #first and third item
away = operator.itemgetter(1,3)    #second and fourth item
team = operator.itemgetter(0)      #first item

#dictionary to hold the previous game's result
#default will be a blank string
last_game = collections.defaultdict(str)

#string to format the output
out = '{}\t{}'
with open('data.txt') as f:
    #skip the header
    f.next()
    #data = map(parse, f)
    for line in f:
        #split the line into its relavent parts
        line = line.strip()
        line = line.split()
        #extract the team and game result
        #--> (team1, result), (team2, result)
        h, a = home(line), away(line)
        home_team = team(h)
        #print the result of the last game
        print(out.format(home_team, last_game[home_team]))
        #update the dictionary with the results of this game
        last_game.update([h,a])

rawDescription: Python - loop through file to call most recent row that contained a variable in current row


code:
##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
    for line in text:
        file.write(line)
        file.write('\n')

rawDescription: Python write to CSV line by line

description: Python write to CSV line by line


code:
@transaction.atomic
def Register(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            u = User.objects.create_user(form.cleaned_data['mobile'], form.cleaned_data['email'], '1234', first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'])
            u.save()

            p = UserProfile.objects.create(user=u, company=form.cleaned_data['company'], mobile=form.cleaned_data['mobile'])
            p.save()

            return HttpResponse("Registration complete! Please head over to the login page to start using your SMS panel.")
    else:
        form = RegisterForm()
        return render(request, "message/register.html", {'form': form})

rawDescription: How to change this regular html form into django form?

description: Change this regular html form into django form


code: list(set([m2.model1 for m2 in Model2.objects.filter(user_id=1).all()]))

rawDescription: Django queryset: All Model1 objects where a Model2 exists with a model1 AND the given user


rawDescription: Plotting oceans in maps using basemap and python


code:
import viz
import viztask

def myfunc():

    for cuetime in (2,3,4):

        mydata = yield viztask.waitTime( cuetime)
        print( 'Wait time: ' , cuetime, ' - Elapsed time: ', mydata.elapsed )

viz.go()
viztask.schedule( myfunc )

rawDescription: How to schedule action at various timings from a list in Python

description: Schedule action at various timings from a list in Python


rawDescription: Serializing binary data in Python

description: Serializing binary data in Python


code:
xcol = ['PersonID', 'AnotherID', 'a']
xa.join(ts, on=xcol).fillna(0).set_index(xcol[:-1])

rawDescription: pandas: vectorize counting rows in time interval

description: Pandas: vectorize counting rows in time interval


rawDescription: Python: converting Trip duration of h min sec and leave only minute count


code: bar = imap(sorted, foo.values())

rawDescription: Sorting a list of lists with itertools imap in Python


rawDescription: Python pandas: How do I drop specific levels in a hierarchical index if any column values are NaN?


code:
for x,y in withHandler(the_list):
    ...

rawDescription: Combine variable and for each loop python


rawDescription: How to get content from tornado future object

description: Get content from tornado future object


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

comment = 'test'

box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "box")))
box.click()

frame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//iframe[@title="+1"]')))
driver.switch_to.frame(frame)

driver.find_element_by_xpath('//div[@onclick]').click()

element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@jsname="msEQQc"]/following-sibling::div//div[@g_editable="true"]')))
driver.execute_script("arguments[0].innerHTML='%s';" % comment, element)

rawDescription: How to Post Youtube Comment with Selenium

description: Post Youtube Comment with Selenium


code:
def _secret():
    for ind, val in enumerate(infinite_counter()):
        if ind >= start:
            if ind > end:
                yield list(next(iter([])))

            else:
                yield val

list(_secret())

rawDescription: Get list of subset from infinite generator in Python


code:
def thingy():
    global res
    if res=="food":
        res=0
    if res=="wood":
        res=1
    if res=="metal":
        res=2
    if res=="gold":
        res=3
    if res=="oil":
        res=3

res = "food"
thingy()
print(res)  # prints "0"

rawDescription: How can I save a variable inside a definition in python?

description: Save a variable inside a definition in python


code:
text(x, y, '%.1f' % x,
     horizontalalignment='center', size=size)

rawDescription: Boxplots in matplotlib - Making room for the text


code:
syn_ack = sr1(syn)
syn_ack

rawDescription: Python-Scapy or the like-How can I create an HTTP GET request at the packet level


code:
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array(number)
plt.colorbar(m)

rawDescription: Matching y axis points together

description: Matching y axis points together


rawDescription: Interpreting (and comparing) output from numpy.correlate


rawDescription: How to map values of a Django model column to a list?

description: Map values of a Django model column to a list


code: a = np.recfromcsv('yourfile.csv')

rawDescription: How to force genfromtxt read csv as record array?

description: Force genfromtxt read csv as record array


code:
def apply_mask(a, indices, axis):
    magic_index = np.ogrid[tuple(slice(i) for i in indices.shape)]
    magic_index.insert(axis, indices)
    return a[magic_index]

rawDescription: numpy 3d to 2d transformation based on 2d mask array

description: Numpy 3d to 2d transformation based on 2d mask array


code: rt = list(unflatten(flatten(sampledata), 4, 2))

rawDescription: Python: Serializing/de-serializing huge amount of data


code:
AR = 'AR'
ARU = 'ARU'
ARC = 'ARC'
CON = 'CON'
CSR = 'CSR'
MCR = 'MCR'
USF = 'USF'

MATERIALS_SIMPLE = [
    AR,
    ARU,
    ARC,
    CON,
    CSR,
    MCR,
    USF,
]

MATERIALS = [
    [AR, ARU, ARC, MCR, CSR],
    [AR, ARU, ARC, MCR],
    [AR, ARU, ARC],
]

rawDescription: What is the appropriate Python data structure to hold its items and a combined list of its items?


code:
for sku in new_skus:
    if sku not in old_skus:
       upload_skus.append(sku)

rawDescription: Python Improve List Compare Speed

description: Python Improve List Compare Speed


code:
def create_A(arg1=None, arg2=None):
    kwargs = {}
    if arg1 is not None: kwargs['arg1'] = arg1
    if arg1 is not None: kwargs['arg2'] = arg2
    return A(**kwargs)

rawDescription: python explicitly not passing optional parameter

description: Python explicitly not passing optional parameter


code:
Enter
Inside
Exit

rawDescription: Open file and with statement in Python

description: Open file and with statement in Python


code:
df['FF'] = df.dot(df.columns).str.slice(0, 1).replace('', 'P')
df

rawDescription: Python - Pandas - create "first fail" column from other column data


code:
og_dict = {'name':'user1', 'salary':'1k'}
og_dict_list =[]
for i in range(2,5):
    new = og_dict.copy()
    new['salary'] = str(i)+'k'
    og_dict_list.append(new)
for og_dict_obj in og_dict_list:
    print(og_dict_obj)

rawDescription: how to create a new dictionary in for loop?

description: Create a new dictionary in for loop


code: int(span.text[pos+2:].split(" ")[0])

rawDescription: convert to int using python

description: Convert to int using python


code: as_strided(arr2.T, strides=(8, 8, 32), shape=(3, 2, 3))

rawDescription: Distance between numpy arrays, columnwise


code:
def f(l, s):
    return [index for index, value in enumerate(l) if s in word_tokenize(value)]

rawDescription: Find the sentence’s index (sentences in a list) of a specific word in Python


code:
for x in data:
    if isinstance(x, (str, list, tuple, int)):
        print('found')

rawDescription: Elegant way to check if a list contains int, str, tuple and sub-list


code: c2.sort(key = lambda row: row[2])

rawDescription: Sorting a list of lists in Python

description: Sorting a list of lists in Python


code: map(float, s.split(","))

rawDescription: print sum of strings as float

description: Print sum of strings as float


code:
conversion_factors = {
    'foot': 0.3048,  # Google search '1 foot in m'
    'yard': 0.9144,
    # etc
}

def unit_convert(number, from_unit='m', to_unit='m'):
    m = number * conversion_factor[from_unit]
    return m / conversion_factor[to_unit]

rawDescription: Elegant list of conditions in Python

description: Elegant list of conditions in Python


rawDescription: PYTHON : abbreviate big data in DataFrame


code:
sql = "INSERT INTO isi_authors (article_id, name_first, name_last, email) VALUES (%s, %s, %s, %s)"
params = [(article.id, au.first_name, au.last_name, au.email) for au in article.authors]
cur.executemany(sql, params)

rawDescription: how do I avoid avoid multiple round trips for queries with MySQLdb with python?

description: Avoid avoid multiple round trips for queries with MySQLdb with python


code: sorted(coins_in_the_bag.items(), key=lambda s: s[1][1]*s[1][2])

rawDescription: print dictionary and string objects in same statement python

description: Print dictionary and string objects in same statement python


rawDescription: Combine (3) 32-char hex hashes into a single unique 32-char hash?


code:
def rec_fetcher(obj):
    if isinstance(obj, list):
        for item in obj:
            for value in rec_fetcher(item):
                yield value
    elif isinstance(obj, dict):
        for item in obj:
            for value in rec_fetcher(obj[item]):
                yield value
    else:
        yield obj

list(rec_fetcher(data))

rawDescription: Obtaining Values from a List-Dictionary Hybrid List Dynamically


rawDescription: How do I take an integer from a list intending to use it?

description: Take an integer from a list intending to use it


code:
longitude = random.random() * math.pi * 2
latitude = math.acos(random.random() * 2 - 1)

rawDescription: Increase the data size

description: Increase the data size


code:
lst = tst.splitlines()
lst.append("lemur")
lst

rawDescription: How to add new line as a separate element on a list?

description: Add new line as a separate element on a list


code:
round = {'tennis_ball':no_of_tennis_balls,'apple':no_of_apples}
fruit = {'banana':no_of_bananas,'apple':no_of_apples}

print(round['apple'].value) #prints 1
fruit['apple'].value = 2
print(round['apple'].value) #prints 2

rawDescription: Python references to references in python


code:
def pow2(n):
    if n<=0:
        return [1]
    else:
        return [2**n] + pow2(n-1)

rawDescription: I need to write a recursive function that prints 2**n as well as 2**(n-1) and 2**(n-2) etc. until 2**0. Outputs as one single sum currently


code:
def LCM(n,d):
    while n%d != 0:
        d += 1
    return d-1
print(LCM(99,12))

rawDescription: A Few Python questions

description: A Few Python questions


code: result_as_lists = [list(x) for x in result_as_iterators]

rawDescription: How to collect data from a list into groups based on condition?

description: Collect data from a list into groups based on condition


code:
n = neighbours([2], [1,4,5])
res = []
for i in n:
    print(i)
    res.append(i)

res

rawDescription: python `list` and `for` return different results

description: Python `list` and `for` return different results