code:
def incorrect_terms(polynomial, terms):
    for index in range(len(polynomial), len(terms)):
        eval = evaluate(polynomial,index)
        if eval != terms[index-1]:
            yield (polynomial, index, eval)

rawDescription: Python converting nested loops to simple line


code:
s = "%2 is a %1 %0"
args = ("Ram", "Good")

sub = re.sub(r"%\d+\b", lambda x: "{"+x.group()[1:]+"}" if int(x.group()[1:]) < len(args) else x.group(), s).format(*args)

print(sub)

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


code:
rowcount = select(u for u in User).count()  # approach 1
rowcount = User.select().count()  # approach 2
rowcount = count(u for u in User)  # approach 3

rawDescription: how to make a rowcount in ponyorm? Python

description: Make a rowcount in ponyorm? Python


code:
#!/usr/bin/env python
html = """<!doctype html>
<title>extract javascript object as json</title>
<script>
// ..
window.blog.data = {"activity":{"type":"read"}};
// ..
</script>
<p>some other html here
"""
import json
import re
from bs4 import BeautifulSoup  # $ pip install beautifulsoup4
soup = BeautifulSoup(html)
script = soup.find('script', text=re.compile('window\.blog\.data'))
json_text = re.search(r'^\s*window\.blog\.data\s*=\s*({.*?})\s*;\s*$',
                      script.string, flags=re.DOTALL | re.MULTILINE).group(1)
data = json.loads(json_text)
assert data['activity']['type'] == 'read'

rawDescription: How to extract a JSON object that was defined in a HTML page javascript block using Python?

description: Extract a JSON object that was defined in a HTML page javascript block using Python


code:
x = {'foo': 'bar'}
y = types.MappingProxyType(x)
y
x['baz'] = 'bla'
y
y['hello'] = 'world'
del x
y

rawDescription: Python: Freeze dict keys after creation

description: Python: Freeze dict keys after creation


code:
char = '\U00010165'
''.join(['\\{:03o}'.format(c) for c in char.encode('utf8')])
print(''.join(['\\{:03o}'.format(c) for c in char.encode('utf8')]))

rawDescription: Correct way to octal escape a UTF-8 character in Python


code: list(chain.from_iterable(someDict[x] for x in supraList))

rawDescription: List comprehension with some kind of loop interdependence?


code:
subprocess.Popen = some_mock_Popen
result = subprocess.call(...)
assert some_mock_popen.result == result

rawDescription: How to do dependency injection python-way?

description: Do dependency injection python-way


code:
import example
import struct

buf = struct.pack('BBBB', 0x41, 0x42, 0x43, 0x44)
e.printBuffer(buf)

rawDescription: How do I pass a pre-populated "unsigned char*" buffer to a C++ method using boost.python?

description: Pass a pre-populated "unsigned char*" buffer to a C++ method using boost.python


rawDescription: How do convert unicode escape sequences to unicode characters in a python string


code: isinstance(x, (float, complex, int))

rawDescription: Check whether the type of a variable is a specific type in Python


code:
env = Environment()
env.Replace(DLIBCOM='my custom lib command')
# The following command will utilize the default value for DLIBCOM, not the above
Library('name', ['source'])

rawDescription: What is the construction variable used for creating libraries in SCons?


code:
def text(ctx, string, pos, theta = 0.0, face = 'Georgia', font_size = 18):
    ctx.save()

    # build up an appropriate font
    ctx.select_font_face(face , cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
    ctx.set_font_size(font_size)
    fascent, fdescent, fheight, fxadvance, fyadvance = ctx.font_extents()
    x_off, y_off, tw, th = ctx.text_extents(string)[:4]
    nx = -tw/2.0
    ny = fheight/2

    ctx.translate(pos[0], pos[1])
    ctx.rotate(theta)
    ctx.translate(nx, ny)
    ctx.move_to(0,0)
    ctx.show_text(string)
    ctx.restore()

rawDescription: rotate text around its center in pycairo

description: Rotate text around its center in pycairo


code:
c = np.cos(x_axis_rotations)
s = np.sin(x_axis_rotations)
matrices = np.zeros((len(x_axis_rotations), 3, 3))
matrices[:, 0, 0] =  1
matrices[:, 1, 1] =  c
matrices[:, 1, 2] = -s
matrices[:, 2, 1] =  s
matrices[:, 2, 2] =  c

rawDescription: What is the proper way to create a numpy array of transformation matrices


rawDescription: How to use groupby to apply multiple functions to multiple columns in Pandas?

description: Use groupby to apply multiple functions to multiple columns in Pandas


code:
nsmap = {}
for ns in root.xpath('//namespace::*'):
    if ns[0]:
            nsmap[ns[0]] = ns[1]

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

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


code:
fd = pickle.load(open("data/fd.txt", 'rb'))

def compute_ave_freq(word_forms):
    l = len(word_forms)
    if  l > 0:
        return sum([fd.freq(form) for form in word_forms]) / l
    else:
        return 0

rawDescription: Faster way to store a NLTK FreqDict?

description: Faster way to store a NLTK FreqDict


code:
def dhms_to_seconds(days, hours, minutes, seconds):
    return (((days * 24) + hours) * 60 + minutes) * 60 + seconds

def seconds_to_dhms(seconds):
    days = seconds // (3600 * 24)
    hours = (seconds // 3600) % 24
    minutes = (seconds // 60) % 60
    seconds = seconds % 60
    return days, hours, minutes, seconds

rawDescription: How to convert datetime.timedelta to minutes, hours in Python?

description: Convert datetime.timedelta to minutes, hours in Python


code:
x = r'(\d+\.?\d+)'
l = 'Benzoyl Peroxide 50 MG/ML Topical Lotion'
re.split(x, l)

rawDescription: python 2.7 select words in list prior to number

description: Python 2.7 select words in list prior to number


code: url =[urlparse(u).netloc for u in file (ipath, "r+b")]

rawDescription: Python .csv writer

description: Python .csv writer


code:
#Original definition v8 /addons/sale_stock/sale_stock.py  line no 30 :
class sale_order(osv.Model):
    _name = "sale.order"

 #this is method originally defined in parent class and being over-ride here,
def action_wait(self, cr, uid, ids, context=None):
    #Your Code goes here
    res = super(sale_order, self).action_wait(cr, uid, ids, context=context)
    #Your Code goes here
    return res

rawDescription: Is it possible to inherit from an extension class in ODOO?


code:
import itertools
with open('path/to/file') as infile:
    allNums = [[int(num) for num in line.strip().split()[1:]] for line in infile]
nullValue = None
allNums = list(itertools.izip.from_iterable(allNums, fillvalue=None)) # python 2.x
# allNums = list(itertools.zip.from_iterable(allNums, fillvalue=None)) # python 3.x

rawDescription: Read in different amount of columns ignoring specific elements in Python


code:
import logging
from celery.utils.log import get_task_logger

def my_func_called_inside_a_task(celery_callback=None):
    if celery_callback:
        logger = get_task_logger(__name__)
    else:
        logger = logging.getLogger(__name__)

    logger.debug("SOME OUTPUT HERE")

rawDescription: Celery Logging: consistent way to log inside and outside of a task


code:
e.elementB[3][:]
e.elementB[3][4:7]

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


rawDescription: Dynamically choose argument for which to minimize a function in python using scipy.optimize


code:
import wx

class TipButton(wx.Button):
    """Subclass of wx.Button, has the same functionality.
    Allows user to set Status Bar help by using SetStatusText method.
    """
    current = None

    def __init__(self, *args, **kwargs):
        wx.Button.__init__(self, *args, **kwargs)

    def SetStatusText(self, help_string, status_bar_frame):
        self.help_string = help_string
        self.status_bar_frame = status_bar_frame
        self.Bind(wx.EVT_ENTER_WINDOW, self._ShowHelp)
        self.Bind(wx.EVT_LEAVE_WINDOW, self._HideHelp)

    def _ShowHelp(self, e):
        TipButton.current = self.GetLabel()
        self.status_bar_frame.SetStatusText(self.help_string)

    def _HideHelp(self, e):
        if self.GetLabel() == TipButton.current:
            self.status_bar_frame.SetStatusText("")

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

        self.CreateStatusBar()

        self.panel = wx.Panel(self)
      # Instead of
      # self.button1 = wx.Button(self.panel, label="Test1", size=(150, 50))
        self.button1 = TipButton(self.panel, label="Test1", size=(150, 50))
        self.button1.SetStatusText("This is for testing purposes", self)
        self.button1.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))

      # Instead of
      # self.button2 = wx.Button(self.panel, label="Test2", size=(150, 50))
        self.button2 = TipButton(self.panel, label="Test2", size=(150, 50))
        self.button2.SetStatusText("This is jusst for fun!", self)
        self.button2.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button1)
        self.sizer.Add(self.button2)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

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

rawDescription: Wxpython Description of event in status bar


code:
# Your parsing, reading and storing functions goes here..

# Now create your dictionary
constants = dict(
    host  = DB_HOST,
    pnum  = DB_PORT_NUMBER,
    num   = DB_NUMBER,
    serv  = IN_SERVICE,
    data  = IN_DATA
)

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


code:
with open(file_path, 'wb') if logging else sys.stdout as shell_stdout:
    subprocess.call(['ls'], stdout=shell_stdout)

rawDescription: Python context for file or None

description: Python context for file or None


code: imat = [[0]*4 for _ in xrange(4)]

rawDescription: Python Array Cleanup Issues

description: Python Array Cleanup Issues


code: df

rawDescription: How can I transform a dataframe in pandas without losing my index?

description: Transform a dataframe in pandas without losing my index


code: a.reshape(3, a.shape[0]//3, a.shape[1], a.shape[2]).sum(axis=1)

rawDescription: NumPy sum along disjoint indices

description: NumPy sum along disjoint indices


code:
from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import Unauthorized

class CustomDjangoAuthorization(DjangoAuthorization):

    def read_detail(self, object_list, bundle):
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)

        # now we check here for specific permission
        if not bundle.request.user.has_perm('any_permission'):
            raise Unauthorized("You are not allowed to access that resource.")

        return result

rawDescription: how to limit GET access to resources using DjangoAuthorization() in tastypie

description: Limit GET access to resources using DjangoAuthorization() in tastypie


code:
for name, average in sorted(player_averages.items(), key=lambda x: x[1]):
    print(name, average)

rawDescription: Line spacing not working

description: Line spacing not working


code:
def tree(D, x):
    return [] if x is None else [x] + tree(D, D[x])

rawDescription: How to perform recursion in python dictionary

description: Perform recursion in python dictionary


rawDescription: Split on delimiter except when followed by space


rawDescription: Arduino - python read serial layout

description: Arduino - python read serial layout


code: c = a

rawDescription: Copying mutable lists in python

description: Copying mutable lists in python


code:
a = array.array('i', [1, 3, 2])
a = numpy.array(a)

rawDescription: How to sort an integer array in-place in Python?

description: Sort an integer array in-place in Python


rawDescription: Python - Remove accents from all files in folder


rawDescription: Matching @user with regex

description: Matching @user with regex


code:
encoded = list(Encoded_Team)
plaintext = list(Team)
changes = []
while encoded != plaintext:
    print("\nThe encoded team is {0}\n".format("".join(encoded)))
    old = input("Which letter would you like to replace? ")
    indices = [i for i, c in enumerate(encoded) if c == old]
    new = input("What letter would you like to replace it with? ")
    for i in indices:
        encoded[i] = new
    changes.append((old, new, indices))

rawDescription: Deleting from a python array and restoring to previous state


code:
lista = [i for i in range(10)]

with open("file.txt","a")  as file:
    file.write("\n")
    file.write("".join(str(lista)))

rawDescription: Python won't write small object to file but will with large object


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


rawDescription: Time-series boxplot in pandas

description: Time-series boxplot in pandas


code:
def touchopen(filename, *args, **kwargs):
    # Open the file in R/W and create if it doesn't exist. *Don't* pass O_TRUNC
    fd = os.open(filename, os.O_RDWR | os.O_CREAT)

    # Encapsulate the low-level file descriptor in a python file object
    return os.fdopen(fd, *args, **kwargs)

rawDescription: How to open (read-write) or create a file with truncation possible?

description: Open (read-write) or create a file with truncation possible


code:
from scipy.spatial import cKDTree as KDTree
import pandas as pd

# for each row in df2, we want to join the nearest row in df1
# based on the column "d"
join_cols = ['d']
tree = KDTree(df1[join_cols])
distance, indices = tree.query(df2[join_cols])
df1_near_2 = df1.take(indices).reset_index(drop=True)

left = df1_near_2.rename(columns=lambda l: 'x_' + l)
right = df2.rename(columns=lambda l: 'y_' + l)
merged = pd.concat([left, right], axis=1)

rawDescription: Merge/Join 2 DataFrames by complex criteria


code: ID, Date, League, Team, Goals

rawDescription: Calculate previous results in PostgreSQL


code:
possible_dupes = [size for size in images if len(images[size]) > 1]
for size in possible_dupes:
    hashes = defaultdict(list)
    for fname in images[size]:
        m = md5.new()
        hashes[ m.update( file(fname,'rb').read(10000) ).digest() ] = fname
    for k in hashes:
       if len(hashes[k]) <= 1: continue
       for fname in hashes[k][1:]:
           os.remove(fname)

rawDescription: Is it possible to detect duplicate image files?


code:
def random_split(items, size):
    sample = set(random.sample(items, size))
    return sorted(sample), sorted(set(items) - sample)

rawDescription: Random split list, keeping the original order in new lists


code:
exclude = set(100, 30, 20)
l = [t for t in l if t[0] not in exclude]

rawDescription: How to check for a value in a list of tuples?

description: Check for a value in a list of tuples


rawDescription: nan in interp1d scipy

description: Nan in interp1d scipy


code:
def collide(self, adjTiles): # adjTiles was returned from scanTiles()
    for tile in adjTiles:
        if tile:             # if a tile actually exists, it continues
            if tile.type == 'wall': # tile type can either be 'ground' or 'wall'
                if self.rect.colliderect(tile.rect1):
                    return True # if there is a collision, it returns 'True'

rawDescription: Python, Pygame, and collision detection efficiency


code:
metaInfo = [{"featureClass":"fc1",
             "abstract":"text goes here",
             "description":"text goes here",
             "tags":["tag1","tag2","tag3"]},
            {"featureClass":"fc2",
             "abstract":"text goes here",
             "description":"text goes here",
             "tags":["tag1","tag2","tag3"]},...]

rawDescription: updating metadata for feature classes programatically using arcpy

description: Updating metadata for feature classes programatically using arcpy


rawDescription: Slicing a sparse scipy matrix to subsample for every 10th row and column


rawDescription: How to test if a dictionary contains certain keys

description: Test if a dictionary contains certain keys


code:
X
A
np.dot(X, A)

rawDescription: Compute each element of matrix

description: Compute each element of matrix


code:
with Timeout(5, False):
    data = sock.recv()

rawDescription: How do I detect a socket disconnection? / How do I call socket.recv with a timeout?

description: Detect a socket disconnection? / How do I call socket.recv with a timeout


code:
def lingregress(data, x_name, y_name):
    x = data[x_name]
    y = data[y_name]
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
    r_sq = r_value ** 2

    plt.scatter(x,y)
    plt.xlabel(x_name)
    plt.ylabel(y_name)
    plt.title('{x_name} vs. {y_name}'.format(x_name=x_name, y_name=y_name))
    plt.plot(x,intercept + slope * x,c='r')

    print('The slope is %.2f with R squared of %.2f' % (slope, r_sq))

lingregress(data, 'Sbet', 'Length')

rawDescription: Set matplotlib plot axis to be the dataframe column name


code: url = request.POST.get("iframeurl", "")

rawDescription: Django: getting src attribute of iframe on views.py


rawDescription: Applying functions to multidimensional numpy arrays without loops


code: self.HealthTotal = tk.Label(..., width=16)

rawDescription: How to place buttons in a very specific place?

description: Place buttons in a very specific place


code:
from itertools import product

repl = {
    'bee': 'BETA',
    'zee': 'ZETA',
    'dee': 'DELTA'
}
source_string = 'bee foo zee bar bee'
p = product(*((x, repl[x]) if x in repl else (x,) for x in source_string.split()))
for x in p:
    print(x)

rawDescription: Generate all possible replacements

description: Generate all possible replacements


code:
class C(Base1, Base2):
    def create(self):
        pass

rawDescription: Class Inheritence Naming in Python

description: Class Inheritence Naming in Python


code:
from tkinter import *

class Call(object): # CamelCase name for class

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

        root = Tk()
        options = ["1", "2", "3"]

        self.var = StringVar()

        self.label = Label(root, text='Test')
        self.label.grid(row=4, column=3)

        OptionMenu(root, self.var, *options, command=self.change_label).grid(row=0, column=3)

        root.mainloop()

    def change_label(self, event):
        self.label['text'] = 'Test ' + self.var.get()

a = Call('')

rawDescription: Add value from drop down list to tkinter GUI once item is selected? Python


code: return x.col2 in x.col1

rawDescription: check str.contains in pandas using string from series

description: Check str.contains in pandas using string from series


code:
Foo.ham = 'eggs'
dir(Foo)
Foo().ham

rawDescription: How does __slots__ avoid a dictionary lookup?


code: np.where((vals == (0, 1)).all(axis=1))

rawDescription: Find matching rows in 2 dimensional numpy array


code: re.match(r"^e$", unidecode("é"))

rawDescription: Regex - match a character and all its diacritic variations (aka accent-insensitive)


code:
import Tkinter as tk

class Example():
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("some application")

        # menu left
        self.menu_left = tk.Frame(self.root, width=150, bg="#ababab")
        self.menu_left_upper = tk.Frame(self.menu_left, width=150, height=150, bg="red")
        self.menu_left_lower = tk.Frame(self.menu_left, width=150, bg="blue")

        self.test = tk.Label(self.menu_left_upper, text="test")
        self.test.pack()

        self.menu_left_upper.pack(side="top", fill="both", expand=True)
        self.menu_left_lower.pack(side="top", fill="both", expand=True)

        # right area
        self.some_title_frame = tk.Frame(self.root, bg="#dfdfdf")

        self.some_title = tk.Label(self.some_title_frame, text="some title", bg="#dfdfdf")
        self.some_title.pack()

        self.canvas_area = tk.Canvas(self.root, width=500, height=400, background="#ffffff")
        self.canvas_area.grid(row=1, column=1)

        # status bar
        self.status_frame = tk.Frame(self.root)
        self.status = tk.Label(self.status_frame, text="this is the status bar")
        self.status.pack(fill="both", expand=True)

        self.menu_left.grid(row=0, column=0, rowspan=2, sticky="nsew")
        self.some_title_frame.grid(row=0, column=1, sticky="ew")
        self.canvas_area.grid(row=1, column=1, sticky="nsew")
        self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew")

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

        self.root.mainloop()

Example()

rawDescription: Tkinter: grid or pack inside a grid?

description: Tkinter: grid or pack inside a grid


code:
import numpy as np
import numpy.linalg as LA
import scipy.optimize as optimize

A = np.array([[1, 3, 4], [5, 6, 9], [1, 2, 3]])
b = np.array([1, 2, 1])
x = LA.solve(A, b)

rawDescription: Solving system using linalg with constraints


code:
NONE = ''

Columns = 7
Rows = 6

def new_game_board() -> [[str]]:
   board = []
   for row in range(Rows):
       board.append([])
       for col in range(Columns):
           board[-1].append(NONE)
   return board

def print_board(board):
   print(''.join('%3i' % i for i in range(1, 1 + len(board[0]))))
   for item in board:
       print(''.join('%3s' % (v if v else '*') for v in item))

gb = new_game_board()
print_board(gb)

rawDescription: Printing list of list formating

description: Printing list of list formating


code:
def walk(ast):
    yield ast
    for arg in getattr(ast, 'args', []):
        for node in walk(arg):
            yield node

write_curve = next(node for node in walk(rpn_to_ast(rpn)) if node.token.ttype == 'function' and node.token.tvalue == 'WriteCurve')
print(write_curve.args[2].token.tvalue)
R10C3

rawDescription: parsing excel style formula

description: Parsing excel style formula


code:
var = 'I need to be accessed by id!'
address = id(var)
print(address)
var2 = [x for x in globals().values() if id(x)==address]

rawDescription: How to access variable by id in Python?

description: Access variable by id in Python


code:
with cd(run("echo $TEST")):
  run("program")

rawDescription: Using environment variables in Fabric

description: Using environment variables in Fabric


code: mystring = mystring.replace(",", "")

rawDescription: How do I replace commas in a string

description: Replace commas in a string


code:
import operator
bestNAS = max(averageNAS.items(), key=operator.itemgetter(1))

rawDescription: Finding the highest value

description: Finding the highest value


code:
with open('students.csv', 'w') as st_file:
    writer = csv.writer(st_file)
    for a in Attendee.objects.filter(profile__status='student'):
        st_file.writerow(a.event_id, a.content_type, a.object_id, a.profile, ...)

rawDescription: Move /migrate django data into new table


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


code:
class MyClass:
    @classmethod
    def foo(cls, arg):
        # Here I can reference the class to work on things related to it
        # even if it is being accessed by an object of this class
        pass

    @staticmethod
    def bar(arg):
        # This one behaves as a pure function unaware of the class it is
        # located on; even if it is accessed by an object of this class
        pass

    def baz(arg):
        # This one is tricky. Because it has no "self", it should crash
        # when accessed by an object of the class but not on the class
        # itself!
        pass

rawDescription: Difference between calling classmethod or regular method from another classmethod


code:
select(A, (1, None), (None, 3, 2))
select(A, (1, None), (None, None, -1))

rawDescription: python select range from list of list

description: Python select range from list of list


code: [d for d in inputlist if any(d.itervalues())]

rawDescription: remove dictionaire from list if ALL values are empty string

description: Remove dictionaire from list if ALL values are empty string


code: ['junk', 'nested stuff']

rawDescription: Python 3 replacement for deprecated compiler.ast flatten function


code:
from collections import Counter

merged = Counter(dict(list1))
merged.update(dict(list2))

rawDescription: What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples?


rawDescription: Number permutations in python iterative

description: Number permutations in python iterative


code:
def worker(shared_dict):
    # Do some processing and get an integer
    result_int = some_other_code()
    shared_dict[result_int] = 1

rawDescription: Can a set() be shared between Python processes?


rawDescription: How to parse this json in Python

description: Parse this json in Python


code: {{ video.pub_date|timesince }}

rawDescription: How to display "This many months ago" in Django using Humanize?

description: Display "This many months ago" in Django using Humanize


code: Y = Q(name__in=must_include_list)

rawDescription: Django: extend queryset or exclude from exclude method


rawDescription: find an element in a list with 'in' keyword and return that element

description: Find an element in a list with 'in' keyword and return that element


code:
# create dataframe from list of rows and pass column order (would be random otherwise)
df = pd.DataFrame.from_records(listOfRows, columns=['messageId', 'status', 'priority', 'streetName', 'streetLength', 'linkId', 'direction'])
print(df)

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


rawDescription: Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins


code:
from collections import namedtuple

class Point(namedtuple("Point", "x y")):
    __slots__ = ()

    def interpolate(self, other, ratio = 0.5):
        return Point(x = self.x * (1.0-ratio) + other.x * float(ratio), \
                     y = self.y * (1.0-ratio) + other.y * float(ratio))

rawDescription: Drawing a clamped uniform cubic B-spline using Cairo


code:
x = "((A:[c1]0.1,B:[c2]0.2),C:[c2]0.3);"
r = []
index = 0
while True:
    m = regex.search(x, index)
    if not m:
       break
    r.append(m.groups())
    index = m.end(7)-1
r

rawDescription: Unable to get regex to capture last group


code:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind("/path/to/socket")
s.listen(100)
while True:
    conn, addr = s.accept()
    do_something(conn, addr)

rawDescription: Can I open UNIX POSIX ports from Python?

description: Open UNIX POSIX ports from Python


rawDescription: forced conversion of non-numeric numpy arrays with NAN replacement

description: Forced conversion of non-numeric numpy arrays with NAN replacement


rawDescription: Python list comprehension to return edge values of a list


code: a = stocks.split('\n')

rawDescription: Convert list of ticker symbols into list in Python


code: print("The length of '%s' is %s" % (word, word_length))

rawDescription: How do I include quotation marks in a print statement if I am using a variable

description: Include quotation marks in a print statement if I am using a variable


code:
import re
r = re.compile(r"\bfoo bar\b")
re.sub(line_old,line_new)

rawDescription: Open every text file in directory then replace particular line in each


code:
# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

rawDescription: How to use subprocess module in python

description: Use subprocess module in python


code: isinstance(mylock, thread.LockType)

rawDescription: python - AttributeError: 'module' object has no attribute 'lock'

description: Python - AttributeError: 'module' object has no attribute 'lock'


code:
def prepend_urls(self):
    return [
        create_detail_url(r"/user", "group_user", "group_user"),
    ]

rawDescription: How does tastypie handle comlex url?

description: How does tastypie handle comlex url


code:
class CustomUserAdmin(UserAdmin):
    form = MyUserChangeForm

rawDescription: Change verbose_name for is_superuser Django


code:
def read_text_file(filename):
    with open(filename) as file_object:
        result = file_object.read()

    return result

teams_txt = read_text_file('teams.txt')

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

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


rawDescription: numpy boolean array with 1 bit entries

description: Numpy boolean array with 1 bit entries


code:
def total_purchase_price(stocks):
    res = []
    for block in stocks:
        shares = block[2]
        purchase_price = block[1]
        res += [shares * purchase_price]
    return res

rawDescription: Understanding how to multiply specific values in tuples in Python


code:
import collections
letters = collections.Counter('google')

rawDescription: Counting each letter's frequency in a string


rawDescription: How to implement high speed, consistent sampling?

description: Implement high speed, consistent sampling


rawDescription: Join a list of lists together into one list in Python


code:
from lxml import etree
from pprint import pprint
data = """

Title One

40.531.3

Title Two

12.182.0

"""
d = etree.HTML(data)
#d.xpath('//h1[following-sibling::*[1][local-name()="p"]]')
results = {}
for h in d.xpath('//h1[following-sibling::*[1][local-name()="p"]]'):
  r = results.setdefault(str(h.text),[])
  r += [ str(x) for x in h.xpath('./following-sibling::*[1][local-name()="p"]/a/text()') ]
pprint(results)

rawDescription: Regex matching items following a header in HTML


code:
int_times = [datetime.datetime.time(datetime.datetime.strptime(t, '%H:%M')) for t in ints[4]]
ext_times = [datetime.datetime.time(datetime.datetime.strptime(t, '%H:%M')) for t in exts[4]]
int_dist = [d for d in ints[3]]
ext_dist = [d for d in exts[3]]

rawDescription: Python 3.4 reading from CSV formats

description: Python 3.4 reading from CSV formats


code: {key: d1[key] for key in d1 if d1[key] > 0}

rawDescription: Filter values of dictionary

description: Filter values of dictionary


code:
prof = Profile()

progname = 'myscript.py'
sys.path.insert(0, os.path.dirname(progname))
modname, _ = os.path.splitext(os.path.basename(progname))
__import__(modname, globals(), locals(), [], 0)
with open(progname, 'rb') as fp:
    code = compile(fp.read(), progname, 'exec')
globs = {
        '__file__': progname,
        '__name__': '__main__',
        '__package__': None,
        '__cached__': None,
        }
prof.runctx(code, globs, None)
prof.create_stats()
print(len(prof.stats))

rawDescription: Why is number of function calls different on second time?


code: U, s, V = np.linalg.svd(A)

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


rawDescription: Reading formatted text using python

description: Reading formatted text using python


code:
def blink(pin):
    GPIO.output(pin, GPIO.LOW)
    time.sleep(.2)
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(.2)
    GPIO.output(pin, GPIO.LOW)
    time.sleep(.2)
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(.2)
    GPIO.output(pin, GPIO.LOW)
    time.sleep(.2)
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(4)

rawDescription: Continually blink an LED when a button is pressed on a raspberry pi?


code:
from flask_login import login_required

app.view_functions['_uploads.uploaded_file'] = login_required(app.view_functions['_uploads.uploaded_file'])

rawDescription: File download authentication in flask-uploads


code:
class EmailChangeForm(Form):
    email = ...
    old_password = CharField(..., widget=Password())

    def __init__(self, user, data=None):
        self.user = user
        super(EmailChangeForm, self).__init__(data=data)

    def clean_old_password(self):
        password = self.cleaned_data.get('password', None)
        if not self.user.check_password(password):
            raise ValidationError('Invalid password')

rawDescription: check_password() from a user again

description: Check_password() from a user again


code:
df = series.reset_index('date')
df2007 = df.loc[dateindex.year==2007]
df = df.join(df2007, rsuffix='_2007')
df = df[['date', 'val_2007']]
df = df.set_index(['date'], append=True)
df = df.swaplevel(0,1).sort_index()

rawDescription: Pandas: Select from date in MultiIndex

description: Pandas: Select from date in MultiIndex


code:
def getInt(msg):
    return int(raw_input(msg))

row = getInt('Which row? ')
col = getInt('Which col? ')

rows[row-1][col] = 'a'

rawDescription: Change a specific element of a list in python?


code:
s1 = "A blah blah blah."             # match A
s2 = "Blah blah blah. A blah blah."  # match A
s3 = "Blah blah blah A."             # don't match 'A'
import re
re.search("(^|\. )A", s1)
re.search("(^|\. )A", s2)
re.search("(^|\. )A", s3)

rawDescription: How do I group a character followed by a space in a Python regex?

description: Group a character followed by a space in a Python regex


code:
d.day
d.month

rawDescription: How to get relevant month and date by inputting only the day of year in python

description: Get relevant month and date by inputting only the day of year in python


code:
def __init__(self, cr, uid, name, context):
    super(class_name, self).__init__(cr, uid, name, context=context)
    self.localcontext.update({
           'time': time,
           '_get_total': self._get_total,
    })

rawDescription: How to sum calculated in qweb report odoo

description: Sum calculated in qweb report odoo


code: words = [x for x in re.split(r'\)?[, .]\(?', line) if x]

rawDescription: Python: Splitting a string into words, saving separators


rawDescription: Using tkinter Entries for variables in external functions


code:
with open('foo.txt') as f:
    dic = {}
    for line in f:
        dic[line.strip()] = next(f).strip()
        next(f);next(f)  #Drop next two lines
from pprint import pprint
pprint(dic)

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

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


code: [fn for name, fn in WidgetFrobber.__dict__.iteritems() if "FrobAttempt" in name]

rawDescription: Using Introspection To Find An Object's Methods, Then Filtering


code:
def mr_e_max_grad(y, alpha, grad, B):

    BY = np.take(B, y+1)
    valid_mask = (y * alpha < BY)
    values = -y * grad
    values[~valid_mask] = np.min(values) - 1.0
    GMaxI = values.max()
    GMax_idx = values.argmax()
    return GMax_idx, GMaxI

rawDescription: How to vectorize finding max value in numpy array with if statement?

description: Vectorize finding max value in numpy array with if statement


code: o.b = objectify.E.b('newtext', atr='someatr')

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

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


code:
def test_parser(self):
    parser = parse_args(['-l', '-m'])
    self.assertTrue(parser.long)
    # ...and so on.

rawDescription: How do you write tests for the argparse portion of a python module?

description: Write tests for the argparse portion of a python module


code:
df['t'] = pd.to_datetime(df['t']) # Make sure pandas treats t as times.
myplot(df, [1, 4], ['A', 'B', 'C'])
plt.tight_layout() # cleans up the spacing of the plots

rawDescription: Pandas: interpolate missing rows and plot multiple series in dataframe


code:
# Fix style glitches
_gtk_styles = """
    # Use the default GtkEntry style for GtkEntry widgets in treeview headers.
    widget "*.treeview-header-entry" style "entry"
"""
gtk.rc_parse_string(_gtk_styles)

# Columns
_columns = [
    (0, "Title"),
    (1, "Description")
    # etc.
]

# Create tree-view.
items_view = gtk.TreeView(self.items_store)
items_view.show()

# Setup treeview columns.
renderer = gtk.CellRendererText()
for column in _columns:
    column_index, column_title, column_filter = column
    column_view = gtk.TreeViewColumn(None, renderer, text=column_index)
    column_view.set_clickable(True)

    column_widget = gtk.VBox()
    column_widget.show()

    column_align = gtk.Alignment(0, 0, 0, 0)
    column_align.show()
    column_widget.pack_start(column_align)
    column_label = gtk.Label(column_title)
    column_label.show()
    column_align.add(column_label)

    column_entry = gtk.Entry()
    column_entry.set_name('treeview-header-entry')
    column_entry.show()
    column_widget.pack_start(column_entry)

    column_view.set_widget(column_widget)
    items_view.append_column(column_view)

# Setup column headers.
columns = items_view.get_columns()
for column in columns:
    column_widget = column.get_widget()
    column_header = find_closest_ancestor(column_widget, gtk.Button)
    if column_header:
        column_header.connect('focus-in-event', propagate_focus_in_event)
        column_header.connect('button-press-event', propagate_button_press_event)
        column_header.set_focus_on_click(False)

rawDescription: PyGTK Entry widget in TreeViewColumn header


code:
def checkvals(v):
    return all(x in (4,5,6,7,8) for x in v[1].value_counts().values)

def checkall(trials):
    return all(checkvals(v) for k, v in pd.DataFrame(zip(trials, trials[1:])).groupby(0))

while not checkall(trials):
    np.random.shuffle(trials)

rawDescription: Python factor level combinations

description: Python factor level combinations


code: df.groupby('id').filter(lambda x: len(x) > cutoff)

rawDescription: Pandas Dataframe selecting groups with minimal cardinality


code:
def to_the_number(n):
    digits=list(map(int,n))
    assert(len(digits))==10
    done = False
    while not done:
        done = True
        for i in range(10):
            if digits[i]!=digits.count(i):
                digits[i]=digits.count(i)
                print(digits)
                done = False
    return ''.join(map(str, digits))

rawDescription: How can I speed up my solution to this self-describing number puzzle?

description: Speed up my solution to this self-describing number puzzle


code: bananaxxxxxxxxxgestrawberryxxxxxxxar

rawDescription: String coverage optimization in Python

description: String coverage optimization in Python


code: lyric = ''.join([tag.text for tag in lyric])

rawDescription: issue extracting html page's string using bs4

description: Issue extracting html page's string using bs4


code:
s = "Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
r = re.compile(r'(?:[^,(]|\([^)]*\))+')
r.findall(s)

rawDescription: How to split a string by commas positioned outside of parenthesis?

description: Split a string by commas positioned outside of parenthesis


code:
with strduping(mybuf) as newbuf:
    do_stuff(newbuf)
    do_more_stuff(newbuf)
# again, automatically freed here

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


code:
import re
re.sub(r'[^\x00-\x7f]',r'', s)

rawDescription: Remove all hex characters from string in Python


code: df = df.set_index('id')

rawDescription: Generating new time series index from existing data set in Pandas


code:
from utilities_dir.utility_1 import  *
from utilities_dir.utility_2 import  a_specific_function

rawDescription: How do I use external python utility files in a Django project?

description: Use external python utility files in a Django project


code:
def hello():
    ...

decorator = decorator_factory(...)
hello = decorator(hello)

rawDescription: Understanding the difference between these two decorators


code:
for clade in tree.find_clades():
    if clade.count_terminals() > 1:
        leafs = clade.get_terminals()
        if len(set([t.name for t in leafs])) == 1:
            # All the leafs in this clade have the same name.
            #  Cut them all except the first one.
            for leaf in leafs[1:]:
                tree.prune(leaf)

rawDescription: Condensing phyloxml phylogenetic trees

description: Condensing phyloxml phylogenetic trees


code:
def pick(seq, indices):
    return tuple([seq[i] for i in indices])

columns = [1, 3]
maximum = max(columns)
Counter(pick(item, columns) for item in a if len(item) > maximum)

rawDescription: Searching for a word pattern in a Python dataset


rawDescription: Python calculate large number wrong

description: Python calculate large number wrong


rawDescription: How do I use integer arithmetic to convert fractions into floating point numbers in python?

description: Use integer arithmetic to convert fractions into floating point numbers in python


code:
import objgraph
objgraph.show_growth()

rawDescription: Why is this lxml.etree.HTMLPullParser leaking memory?


code:
from pyspark.sql.types import *
from pyspark.mllib.linalg import VectorUDT

# Lets assume we have only a vector
raw = transformed.select("features_raw")

# Dictionary equivalent to transformed.schema.fields[-1].metadata shown abov
meta = ...
schema = StructType([StructField("features", VectorUDT(), metadata=meta)])

sqlContext.createDataFrame(raw.rdd, schema)

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

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


code:
def func(a, b=None):
    if b is None:
        try:
            b = fancy_function()
        except FancyException:
            b = 4
    return a + b

rawDescription: python function in which a parameter is external if mentioned or internal if it is not mentioned

description: Python function in which a parameter is external if mentioned or internal if it is not mentioned


code:
python
monty
spam
foo

rawDescription: For loop with custom steps in python

description: For loop with custom steps in python


code:
def write_lines_to_file(lines, filename):
    file_handle_eff = open_file(filename).on(
        lambda file_handle:
            sequence(map(partial(write_data, file_handle), lines)).on(
                lambda _: close_file(file_handle)))

rawDescription: Python: writing files in functional programming style


code:
df.head()
df.tail()

rawDescription: Converting PANDAS dataframe from monthly to daily


code:
db.test.update({"x": "42"}, {"$set": {"a": "21"}},True)
#True => Upsert is True

rawDescription: How do I do a get_or_create in pymongo (python mongodb)?

description: Do a get_or_create in pymongo (python mongodb)


code:
import nltk.tokenize.punkt
import pickle
import codecs
tokenizer = nltk.tokenize.punkt.PunktSentenceTokenizer()
text = codecs.open("someplain.txt","r","utf8").read()
tokenizer.train(text)
out = open("someplain.pk","wb")
pickle.dump(tokenizer, out)
out.close()

rawDescription: training data format for nltk punkt

description: Training data format for nltk punkt


code:
if not d.viewkeys() >= {'amount', 'name'}:
    raise ValueError

rawDescription: python: what is best way to check multiple keys exists in a dictionary?

description: Python: what is best way to check multiple keys exists in a dictionary


rawDescription: QFileDialog opening two dialogs

description: QFileDialog opening two dialogs


code: {",".join(x.items): x.freq for x in result}

rawDescription: python 2.7 : create dictionary from list of sets

description: Python 2.7 : create dictionary from list of sets


code:
freqWords('CTGGAT', 2)
# Counter({'GG': 1, 'TG': 1, 'GA': 1, 'CT': 1})

rawDescription: How to store parts of a string into a dictionary

description: Store parts of a string into a dictionary


code:
import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

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

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

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


code:
dmin=len(trans[0])
for i in xrange(len(trans)):
    for j in xrange(i+1,len(trans)):
            dist=hamdist(trans[i][:-1], trans[j][:-1])
            if dist is not None and dist < dmin:
                    dmin = dist

rawDescription: Finding Minimum hamming distance of a set of strings in python


code:
#### FOR TRAINING DATA ####
stop = stopwords.words('english')

# Reads the training data.
traindir = '/home/alvas/my_movie_reviews'
mr = CategorizedPlaintextCorpusReader(traindir, r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*', encoding='ascii')

# Converts training data into tuples of [(words,label), ...]
documents = [([w for w in mr.words(i) if w.lower() not in stop and w not in string.punctuation], i.split('/')[0]) for i in mr.fileids()]
# Extract training features.
word_features = FreqDist(chain(*[i for i,j in documents]))
word_features = word_features.keys()[:100]
# Assuming that you're using full data set
# since your test set is different.
train_set = [({i:(i in tokens) for i in word_features}, tag) for tokens,tag  in documents]

#### TRAINS THE TAGGER ####
# Train the tagger
classifier = NaiveBayesClassifier.train(train_set)

#### FOR TESTING DATA ####
# Now do the same reading and processing for the testing data.
testdir = '/home/alvas/test_reviews'
mr_test = CategorizedPlaintextCorpusReader(testdir, r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*', encoding='ascii')
# Converts testing data into tuples of [(words,label), ...]
test_documents = [([w for w in mr_test.words(i) if w.lower() not in stop and w not in string.punctuation], i.split('/')[0]) for i in mr_test.fileids()]
# Reads test data into features:
test_set = [({i:(i in tokens) for i in word_features}, tag) for tokens,tag  in test_documents]

#### Evaluate the classifier ####
for doc, gold_label in test_set:
    tagged_label = classifier.classify(doc)
    if tagged_label == gold_label:
        print("Woohoo, correct")
    else:
        print("Boohoo, wrong")

rawDescription: Testing the NLTK classifier on specific file


code:
import pandas as pd

data = pd.DataFrame({'test_data': [1,2,3,4,5]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

pd.core.format.header_style = None

data.to_excel(writer, sheet_name='test', index=False)

workbook  = writer.book
worksheet = writer.sheets['test']

font_fmt = workbook.add_format({'font_name': 'Arial', 'font_size': 10})
header_fmt = workbook.add_format({'font_name': 'Arial', 'font_size': 10, 'bold': True})

worksheet.set_column('A:A', None, font_fmt)
worksheet.set_row(0, None, header_fmt)

writer.save()

rawDescription: pandas xlsxwriter, format header

description: Pandas xlsxwriter, format header


code:
class ParseIPNets(argparse.Action):
    """docstring for ParseIPNets"""
    def __init__(self, option_strings, dest, nargs=None, **kwargs):
        super(ParseIPNets, self).__init__(option_strings, dest, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None, first=[True]):
        if first[0]:
            namespace.user_nets.clear()
            first[0] = False
        location, subnet = values.split(':')
        namespace.user_nets[location] = subnet

parser.add_argument('--add-net',
                    action=ParseIPNets,
                    dest='user_nets',
                    help='Nets subnets for users. Can be used multiple times',
                    default={"user1": "198.51.100.0/24"})

args = parser.parse_args()

rawDescription: Custom parsing function for any number of arguments in Python argparse


code: hell.brick_list = len(lister)*[Brick()]

rawDescription: Accessing attributes of a list of objects in python


code:
DOWNLOADER_MIDDLEWARES = {
    'scrapy.contrib.downloadermiddleware.retry.RetryMiddleware': None,
    'myproject.middlewares.CustomRetryMiddleware': 500,
}

rawDescription: Scrapy: collect retry messages

description: Scrapy: collect retry messages


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


code:
class Artist(db.Model):
    __tablename__ = 'artists'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    suggestions = db.relationship('Suggestion', backref='artist')

class Suggestion(db.Model):
    __tablename__ = 'suggestions'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'))

    def __repr__(self):
        return '<Suggestion %r>' % (self.artist.name,)

rawDescription: Foreign key model in model's __repr__()

description: Foreign key model in model's __repr__()


code:
import os
os.path.abspath('/foo/bar/test/')
os.path.abspath('/foo/bar/test')

rawDescription: Extracting Directory from Path with Ending Slash


code:
class Event(models.Model):
    ALERT   = "alert"
    WARNING = "warning"
    ERROR   = "error"
    EVENT_TYPES = (
        (ALERT,   "Alert"),
        (WARNING, "Warning"),
        (ERROR,   "Error"),
    )

    YELLOW = "FF6A00"
    ORANGE = "FFE800"
    RED    = "FF0000"
    COLOURS = (
        (YELLOW, "Yellow"),
        (ORANGE, "Orange"),
        (RED,    "Red"),
    )

    event_type = models.CharField(max_length=16, choices=EVENT_TYPES, default=ALERT)
    event_colour = models.CharField(max_length=6, choices=COLOURS, default=YELLOW)

rawDescription: Where to store color information in a web application?


code:
def get_or_create_or(cls, session, **kwargs):
    instance = session.query(cls).filter(or_filter_by_conditions(**kwargs)).first()
    # rest

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

description: Make a get_or_create using OR with SQLAlchemy


code:
def uv_centroids(mesh, map = 'map1'):
    results = dict()
    for f in range(cmds.polyEvaluate(mesh, f=True)):
        cmds.select("%s.f[%s]" % (mesh, f), r = True)
        uu, vv = cmds.polyEvaluate(  bc2=True, uvs=map)
        uu = sum(uu) / 2.0
        vv =sum(vv) / 2.0
        results[uu,vv] = f
    return results

rawDescription: re-ordering polygon face index in maya

description: Re-ordering polygon face index in maya


code: reverse =lambda s:s and s[-1]+reverse(s[:-1])or s

rawDescription: Reverse String Function in Python (Primitive Steps)


code:
from pyramid.asset import abspath_from_asset_spec
import pystache
import os

def pystache_renderer_factory(info):
    template = os.path.join(abspath_from_asset_spec('myproj:templates', False),
                            info.name)
    f = open(template)
    s = f.read()
    f.close()
    def _render(value, system):
        return pystache.render(s, value)
    return _render

rawDescription: How to change the template engine in Pyramid?

description: Change the template engine in Pyramid


rawDescription: Python regex removing non alpha numeric characters from string except brackets


code:
from operator import add

total = (times
  .map(lambda x: (get_key(x), 1))
  .reduceByKey(add)
  .values()
  .sum())

time_range = get_key(end) - get_key(start) + 1.0

mean = total / time_range

mean
## 1.8

rawDescription: Using Apache-Spark to analyze time series


code:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])

rawDescription: Use Python to launch Excel file

description: Use Python to launch Excel file


code:
def get_estimated_sample_statistics( source_iter ):
    """Precondition: at the ESTIMATED SAMPLE STATISTICS line"""
    for line in source_iter:
        if len(line.strip()) == 0: continue
    assert line.strip() == "MEANS/INTERCEPTS/THRESHOLDS"
    for data in get_means_intercepts_thresholds( source_iter ):
        yield data
    while True:
        if len(line.strip()) == 0: continue
        if line.strip() != "SLOPES": break
        for data in get_slopes( source_iter ):
            yield data

rawDescription: Parsing blockbased program output using Python


code:
using_loop          : 43.56
using_P2            : 12.64
using_poly          :  0.03

rawDescription: Faster way to attach 2d polynomial coefficients to terms in Python?


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

rawDescription: Python; Dictionary iteration

description: Python; Dictionary iteration


code: df.loc['length (mm)']

rawDescription: How to read specific rows from excel file using pandas

description: Read specific rows from excel file using pandas


code:
import dump #this does nothing if it's already loaded
stat = os.stat(dump_filename)
if(stat.mtime > dump.mtime):
    reload(dump)
    dump.mtime = stat.mtime

rawDescription: Maintain a large dictionary in memory for Django-Python?


rawDescription: pydoc.render_doc() adds characters - how to avoid that?

description: Pydoc.render_doc() adds characters - how to avoid that


code: [[False for _ in range(10)] for _ in range(22)]

rawDescription: Defining large list-within- list array

description: Defining large list-within- list array


code:
from itertools import chain, izip

zipped = (izip(*ele) for ele in izip(*next(izip(*structure))))
print (list(chain.from_iterable(izip(*zipped))))

[(1, 13), (4, 16), (2, 14), (5, 17), (3, 15), (6, 18)]

rawDescription: Nested list comprehension in Python

description: Nested list comprehension in Python


code:
coordstest = np.vstack([np.random.uniform(150, 220, 20),
                        np.random.uniform(150, 220, 20)]).T

rawDescription: Localized random points using numpy and pandas


code:
def validate(validation, not_valid_warning=None):
    if not hasattr(validation, '__call__'):
        raise TypeError("validation must be callable")
    def wrapper(f):
        def wrapped(*args):
            while True:
                p = f(*args)
                if validation(p):
                    break
                if not_valid_warning:
                    print(not_valid_warning)
            return p
        return wrapped
    return wrapper

@validate(lambda x: x < 10 or x > 100)
def v_input(*args):
    return __builtins__.input(*args)

# Example..........
if __name__ == "__main__":
    v_input("Enter a number less than 10 or more than 100: ")

rawDescription: How do I check a value entered?? Python 3.4

description: Check a value entered?? Python 3.4


code:
from twython import Twython
t = Twython()
res = t.search(q='python')
res.keys()
from pprint import pprint
pprint(res[u'results'][0])
res[u'results'][0]['id_str']

rawDescription: Getting a tweet's ID with Twython?

description: Getting a tweet's ID with Twython


code:
import sys
if not hasattr(sys, "setdefaultencoding"):
    reload(sys)
sys.setdefaultencoding("utf-8")

rawDescription: Is it possible to represent non-ASCII characters?


rawDescription: Delete specific spaces from a string Python


code: grad_expr = T.grad(cost=expr, wrt=[x1, x2])

rawDescription: Defining a function with a loop in Theano


code: [line for line in cell_lines if "KIDNEY" in line]

rawDescription: Text search elements in a big python list


code:
import calendar
l=list(list(calendar.month_abbr))
OrderedDict(sorted(month.items(),key=lambda x:l.index(x[0])))

rawDescription: Ordereddict Merge by Month, and Week python


code: help (e.itersiblings)

rawDescription: How to extract text from html conditionally in beautifulsoup

description: Extract text from html conditionally in beautifulsoup


rawDescription: Prevent doctest incorrect failure when unordered output is invovled


code:
def updateVariableList(self):
    variable_list = [self.a, self.b]

rawDescription: Python list of variables inside a class

description: Python list of variables inside a class


code: pip3 --version

rawDescription: how to run pip for python 3 and python 2

description: Run pip for python 3 and python 2


code:
render_partial = web.template.render('templates/', globals=template_globals)
template_globals.update(render=render_partial)

rawDescription: how to get cookie in template webpy

description: Get cookie in template webpy


code:
import pickle
try:
   password = pickle.load(open("Hello.p", "rb"))[1]
   username = pickle.load(open("Hello.p", "rb"))[0]
except IndexError: #Sees if the password is not there
   print("There is no information for those credentials")
password
username

rawDescription: Python User Registration

description: Python User Registration


code: import MyModule.MySubModule.myclass

rawDescription: how to init system's path variable in python projects

description: Init system's path variable in python projects


code:
new_min = -5
new_range = 5 + 0.9999999999 - new_min
output = [int((n - old_min) / old_range * new_range + new_min) for n in input]

rawDescription: How to normalize a list of positive and negative decimal number to a specific range

description: Normalize a list of positive and negative decimal number to a specific range


rawDescription: Best way to remove controls from a wx panel

description: Remove controls from a wx panel


rawDescription: pandas and category replacement

description: Pandas and category replacement


code: df = df[['qux', 'bar', 'foo']]

rawDescription: Insert column in multiindex data frame

description: Insert column in multiindex data frame


code:
from lxml import etree
s = """

    Reply #3 -

    05/13/09  2:02am

"""
doc = etree.HTML(s)

def first(sequence,default=None):
  for item in sequence:
    return item
  return default

rawDescription: Parse the date string from html in lxml

description: Parse the date string from html in lxml


code:
class MatricesPanel(wx.Panel):
    def __init__(self, parent):
        super(MatricesPanel, self).__init__(parent)

        sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.outputsMatrix = self.addEmptyGrid(sizer)
        self.inputsMatrix = self.addEmptyGrid(sizer)

        addRowsButton = wx.Button(self, -1, " Add Rows")
        addRowsButton.Bind(wx.EVT_BUTTON, self.addRows)
        sizer.Add(addRowsButton)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        self.Layout()

    def initResize(self, ev = None):
        self.inputsMatrix.SetSize((500, 500))
        self.outputsMatrix.SetSize((500, 500))
        self.Layout()

    def addEmptyGrid(self, sizer):
        matrix_ = wx.grid.Grid(self)
        matrix_.SetRowLabelSize(0)
        matrix_.SetColLabelSize(0)
        matrix_.CreateGrid(1,1)
        sizer.Add(matrix_)
        return matrix_

    def addRows(self, ev=None):
        self.inputsMatrix.AppendRows(1)
        self.outputsMatrix.AppendRows(1)
        self.Layout() #refresh the frame

rawDescription: Placing two wx Grids side by side

description: Placing two wx Grids side by side


code: libraries=["externlib"]   # Without the 'lib' prefix and the '.so' extension...

rawDescription: Using Cython To Link Python To A Shared Library


code:
d = { 0 : [1, 2, 3] , 1 : [2, 3, 4], 2: [5, 6, 7]}
for key in d.keys():
    orig_vals=d[key]
    new_vals=[]
    for val in orig_vals:
        try:
            new_vals+=d[val]
        except KeyError:
            pass
    d[key] = list(set(new_vals)-set(orig_vals))

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


code:
import elasticsearch
es = elasticsearch.Elasticsearch(['localhost'])

rawDescription: Elasticsearch python API: Delete documents by query


code: not any(t in s for t in allstrings if t != s)

rawDescription: How to select the finest granularity of string items in a list

description: Select the finest granularity of string items in a list


code:
a
xygrid[I[1],:]

rawDescription: Python rounding of random floats to nearest points on a 2D uniform mesh grid


code: np.logical_or(f < min_freq, f > max_freq)

rawDescription: How to convert complex numbers back into "normal" numbers after performing FFT

description: Convert complex numbers back into "normal" numbers after performing FFT


code:
mydict={'__tablename__':stored['tablename'],
        '__table_args__':{'autoload':True},}

MyObj=type(stored['objectname'],(Base,),mydict)
print(MyObj)
# <class '__main__.MyObject'>
print(MyObj.__base__)
# <class '__main__.Base'>
print(MyObj.__tablename__)
# my_internal_table_name
print(MyObj.__table_args__)
# {'autoload': True}

rawDescription: Dynamic Class Creation in SQLAlchemy

description: Dynamic Class Creation in SQLAlchemy


code:
class PrintAndLog(object):
    def __init__(self, fileOrPath): # choose which makes more sense
        self._file = ...

    def write(s):
        sys.stdout.write(s)
        self._file.write(s)

    def close(self):
        self._file.close()
    # insert wrappers for .flush, .writelines

_old_stdout = sys.stdout
sys.stdout = PrintAndLog(f)
... # print and stuff
sys.stdout = _old_stdout

rawDescription: Can I write to terminal and a given file with one command in Python?

description: Write to terminal and a given file with one command in Python


code: pos = dict( (n, n) for n in G.nodes() )

rawDescription: Remove rotation effect when drawing a square grid of MxM nodes in networkx using grid_2d_graph


code:
g = data.groupby(...)
size = g.size()
size[size > 3]

rawDescription: Pandas groupby: get size of a group knowing its id (from .grouper.group_info[0])


rawDescription: Python, split array by gradient of dataset


code:
import datetime as dt
import time
import calendar
date=dt.datetime(2010,12,1,0,0,0)
date
date_utc=dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))
date_utc
date_local=dt.datetime.fromtimestamp(calendar.timegm(date_utc.timetuple()))
date_local

rawDescription: How to convert EST/EDT to GMT?

description: Convert EST/EDT to GMT


code:
curs.executemany('insert into mytable (mycolumn) values (?)', excel_results)
conn.commit()

rawDescription: Python: Adding excel file to an access database


code:
import pandas as pd
import matplotlib.pyplot as plt

result = [{0: 21, 1: 7, 2: 67, 3: 12, 4: 15, 5: 7, 6: 54, 7: 49, 8: 50, 9: 31,
           10: 6, 11: 2, 12: 8, 13: 2, 14: 2, 15: 1, 16: 35, 17: 2, 18: 1, 19:
           4, 20: 2, 21: 4, 22: 3, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1,
           29: 1},
          {0: 2, 1: 5, 2: 2, 3: 3, 4: 1, 5: 2, 6: 3, 7: 2, 8: 1, 9: 1, 10: 1,
           11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1}]

df = pd.DataFrame([(level,val) for level, dct in enumerate(result)
                   for val in dct.values()],
                  columns=['level', 'size'])
groups = df.groupby(['level'])
fig, ax = plt.subplots()
for level, grp in groups:
    size_count = grp['size'].value_counts()
    ax.plot(size_count.index, size_count, markersize=12, marker='o',
            linestyle='', label='level {}'.format(level))
ax.legend(loc='best', numpoints=1)
ax.set_xlabel('community size')
ax.set_ylabel('number of communities')
ax.grid(True)
plt.show()

rawDescription: How to dynamically update a plot in a loop?

description: Dynamically update a plot in a loop


code:
A = [1,2,3,4,5,6,7,8,9,0]

B = [4,5,6,7]
C = [7,8,9,0]
D = [4,6,7,5]

def is_slice_in_list(s,l):
    len_s = len(s) #so we don't recompute length of s on every iteration
    return any(s == l[i:len_s+i] for i in xrange(len(l) - len_s+1))

rawDescription: Check if all elements of one array is in another array


code:
from xml.sax.saxutils import unescape

entry=body[0]

rawDescription: How to convert < into < in lxml, Python?

description: Convert < into < in lxml, Python


rawDescription: python, add lists to csv by columns, with list extracted dynamically from other data

description: Python, add lists to csv by columns, with list extracted dynamically from other data


code:
def SomeFuncInFilename():
    Hello() # uses function from your scope

rawDescription: Is there a way to import an embedded python script into IronPython as a python module?


code:
import re
line = re.sub(r"(?i)^.*interfaceOpDataFile.*$", "interfaceOpDataFile %s" % fileIn, line)

rawDescription: Python string.replace regular expression


code: filter(lambda x:x not in sublst,lst)

rawDescription: Finding the differences between two nested lists


rawDescription: Python: Scapy: How to read IP flags

description: Python: Scapy: How to read IP flags


code:
class OccupationAutocomplete(OrderedAutocomplete):
    model = models.Occupation

    ordered_search_fields = [
        {'search_fields': ['^title'], 'split_words':False},
        {'search_fields': ['title'], 'split_words':True},
        ]
autocomplete_light.register(OccupationAutocomplete)

rawDescription: Force django-autocomplete=light to return 'best' matches first


rawDescription: Populating a list with elements from different lists in Python


rawDescription: Encoding passed argument for serial.write python


rawDescription: Match C++ Strings and String Literals using regex in Python


code:
patches = [mpl.patches.Rectangle(xy[i], dx[i], dy[i],         # I dont want
                                 ec=None, lw=0, fc=colors[i]) # visible edges.
            for i in range(mesh.shape[0])
          ]

rawDescription: Log Scale Matplotlib PatchCollection Colors


code: result = r > I.reshape(I.shape[0],I.shape[1],1)

rawDescription: How to efficiently use a index array as a mask to turn a numpy array into a boolean array?

description: Efficiently use a index array as a mask to turn a numpy array into a boolean array


rawDescription: python array of decimals into binary numbers efficienty

description: Python array of decimals into binary numbers efficienty


code:
import types
return types.MethodType(eval(attrname), self)

rawDescription: Hide deprecated methods from tab completion


rawDescription: Regex: Matching the closest value backwards


code:
class Likelihood():
    def __init__(self, x, y):
        self.range = [{} for i in range(x)] # without default values
        # if you need default values, use this code or numpy.zeros(shape=(x,y))
        #self.range = [[0 for j in range(y)] for i in range(x)]

class MyDataType():
    def __init__(self, dimension_1, dimension_2):
        self.likelihood = Likelihood(dimension_1, dimension_2)

ocd = [0, 1, MyDataType(100, 100)]

# copy-paste your code here:
ocd[2].likelihood.range[1][0]=[-5219, -5191, 11.7];
ocd[2].likelihood.range[1][1]=[-5180, -5057, 56.5];

print(ocd[2].likelihood.range[1][0])

rawDescription: variable in python

description: Variable in python


code:
mainfile.py
from filex import f
f()

rawDescription: python: use command line argument from file A in file B

description: Python: use command line argument from file A in file B


rawDescription: Pandas comparison with variable number of columns


code:
def gmm_js(gmm_p, gmm_q, n_samples=10**5):
    X = gmm_p.sample(n_samples)
    log_p_X, _ = gmm_p.score_samples(X)
    log_q_X, _ = gmm_q.score_samples(X)
    log_mix_X = np.logaddexp(log_p_X, log_q_X)

    Y = gmm_q.sample(n_samples)
    log_p_Y, _ = gmm_p.score_samples(Y)
    log_q_Y, _ = gmm_q.score_samples(Y)
    log_mix_Y = np.logaddexp(log_p_Y, log_q_Y)

    return (log_p_X.mean() - (log_mix_X.mean() - np.log(2))
            + log_q_Y.mean() - (log_mix_Y.mean() - np.log(2))) / 2

rawDescription: KL-Divergence of two GMMs

description: KL-Divergence of two GMMs


code:
grouped = df.groupby("c3")[["c1", "c2"]]
grouped.apply(lambda x: print(x,"\n","--")) # just for display purposes

rawDescription: Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns


code: df = pd.read_csv("mwe.csv", index_col=0, parse_dates=[0])

rawDescription: Weird behavior specifying date limits with pandas


code:
class GetBlobstoreUrl(BaseHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload/')
        self.response.out.write(upload_url)

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads()
        blob_info = upload_files[0]

rawDescription: Store uploaded file data in Blob

description: Store uploaded file data in Blob


code:
from enum import Enum
class Fruit(Enum):
    Apple = 4
    Orange = 5
    Pear = 6

Fruit(5)

rawDescription: How to convert int to Enum in python?

description: Convert int to Enum in python


code:
rules = [
    Rule(SgmlLinkExtractor(allow=[r'same regex_rule']), callback='parse_item', follow=True),
    # more rules .....
]

def parse_item(self, response):

    yield self.parse_artist(response)
    yield self.parse_album(response)

rawDescription: Scrapy CrawlSpider rules with multiple callbacks


rawDescription: Scraping for text between nondescript tags


rawDescription: Python: how to group pandas Data Frame in a certain time window?


code:
actor_movie = sc.parallelize([
    ("actor 1", "movie 1"),
    ("actor 1", "movie 3"),
    ("actor 1", "movie 3"),
    ("actor n", "movie 2")
])

swap = lambda x: (x[1], x[0])

rawDescription: PySpark - create pair RDD with two keys that share the same value


code: data = dict((x['name'], x) for x in original_data)

rawDescription: python - access list element by key

description: Python - access list element by key


code: {{ item.code|replace_underscores }}

rawDescription: Google appengine string replacement in template file


code:
if '*NoCover*' in dc_files:
    dc_files.remove('*NoCover*')

rawDescription: Python Remove Item from list

description: Python Remove Item from list


rawDescription: Python string formatting - old `%` vs new `str.format`


code:
import email, getpass, imaplib, os, re
import matplotlib.pyplot as plt

rawDescription: Extract information from Gmail with Python


rawDescription: Python Regular Expression of long complex string


code:
import multiprocessing
from multiprocessing.managers import SyncManager

def Manager():
    m = SyncManager()
    m.start()
    return m

class Dog():
    def __init__(self, name = "joe"):
        self.name = name
    def bark(self):
        print("woof")

SyncManager.register("Dog", Dog)

mg = Manager()
dt = dict()
lp = mg.list()
lp.append(dt)
print(lp)
dt["a"] = 1
dt["b"] = 2
lp[0] = dt
print(lp)
dt = dict()
lab = mg.Dog("carl")
print(lab)
pup = mg.Dog("steve")
print(pup)
dt[lab] = 1
dt[pup] = 2
lp[0] = dt
# Their ids don't change
print(lp)

rawDescription: Unable to use multiprocessing manager.dict() to share object instance


code:
['%s %s'%(i,x) for i,j in zip(ul,ll) for x in j]
[(i,x) for i,j in zip(ul,ll) for x in j]
list(zip(ul,ll))

rawDescription: How to Transpose Column Values to Row Values in Python


code: GTK_LOCALE_DATA = os.path.join("share", "locale")

rawDescription: Bundling GTK resources with py2exe

description: Bundling GTK resources with py2exe


code:
worddict = {'example1': 1, 'example2': 0, 'example3': 7}
seconddict = {'firstitem': 1, 'seconditem': 1, 'thirditem':9}

categories = {'example1': ['firstitem', 'thirditem'],
              'example2': ['seconditem', 'thirditem'],
              'example3': ['thirditem']}

accumulate_by_category(worddict, seconddict, categories)
print(seconddict) # {'seconditem': 1, 'firstitem': 2, 'thirditem': 17}

rawDescription: Searching a dictionary for a key, adding the value of that key's value to another key value pair


rawDescription: Time Zones in python for program

description: Time Zones in python for program


rawDescription: What is difference between {:.4e} and {:2.4} in Python scientific notation


code:
from itertools import groupby
from operator import itemgetter

by_b = itemgetter('b')
newdictList = [ next(x[1]) for x in groupby(sorted(mydictList, key=by_b), key=by_b) ]

rawDescription: Removing dictionaries from a list on the basis of duplicate value of key


code:
element = HTML.ElementFromURL(url)
alltext = element.xpath('string(//table[contains(@class, "mg-b20")]/tr[3]/td[2]//a)')

for item in alltext:
    Log("text = %s" % item);

rawDescription: XPath for selecting multiple HTML `a` elements


code:
g = my_data.groupby("Category")
counts_and_means = g["Category"].agg(np.count_nonzero).to_frame(name="Count")
counts_and_means

rawDescription: Pandas: Best idioms for renaming, reordering columns while aggregating


rawDescription: Pandas, order of groupby and projection

description: Pandas, order of groupby and projection


code: members = members + temp_list['data'] # Add latest pulled data to our list

rawDescription: Python recursive function variable scope


code:
def __getattr__(self, name):
    return lambda value: self.set({name:value})

rawDescription: Mapping obj.method({argument:value}) to obj.argument(value)


code: x['abc']

rawDescription: Implementing a Patricia Trie for use as a dictionary


code:
from random import choice
from pprint import pprint

arr = []

def create_string(x):
    for i in xrange(10):       # 10 random populations
        arr.append([])
        for j in xrange(x):  # population size
            v = ''.join(choice(('0','1')) for _ in range(10))
            arr[-1].append(v)
    return arr

a = create_string(5)
pprint(a)

rawDescription: Binary string in Python issues

description: Binary string in Python issues


code: length_key = len(d['key'])  # length of the list stored at `'key'` ...

rawDescription: How to find length of dictionary values

description: Find length of dictionary values


code:
import inspect
import sys
class Foo(object): pass

from json import *
inspect.getmembers(sys.modules[__name__], inspect.isclass)
[c for c in inspect.getmembers(sys.modules[__name__], inspect.isclass) if c[1].__module__ == __name__]

rawDescription: Get a list of classes, defined within a script


code: choice = choice.strip()

rawDescription: Why does my code work in python shell but not when I double click the py file


rawDescription: Flipped an array and reversing every second row


code:
ABC.f4 = MethodType(func, None, ABC)
a.f4(1)

rawDescription: Python: calling a function as a method of a class


code:
application = webapp.WSGIApplication([
    ...
    ('/i', DownloadImage),
    ...
], debug=True)

rawDescription: Python app engine: how to save a image?

description: Python app engine: how to save a image


rawDescription: pandas: How do I split text in a column into multiple rows?

description: Pandas: How do I split text in a column into multiple rows


rawDescription: Filter out rows/columns with zero values in MultiIndex dataframe


code:
class TimeSet(set):
    def add(self, item, timeout):
        set.add(self, item)
        t = threading.Thread(target=timeout_set_remove, args=(self, item, timeout))
        t.start()

def timeout_set_remove(my_set, item, timeout):
    time.sleep(timeout)
    os.remove(str(item))
    my_set.remove(item)

rawDescription: Remove old temporary files when user is logged out


code:
class BlogResource(ModelResource):
    model = Blog

urlpatterns = patterns('',
    url(r'^Blog/$', ListOrCreateModelView.as_view(resource=BlogResource)),
    url(r'^Blog/(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=BlogResource)),
)

rawDescription: Django Rest Framework using the url to load specified models


rawDescription: how to find the line number where specific text exists?

description: Find the line number where specific text exists


rawDescription: Plot bar graph using multiple groupby count in panda


code:
import pprint
import random

from collections import defaultdict

ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']

deck = zip(ranks * 4, suits * 13)

def test(trials=100000):
    draws = defaultdict(int)

    for i in range(trials):
        draws[random.choice(deck)] += 1

    return {card: float(value) / trials for card, value in draws.iteritems()}

pprint.pprint(test(100000))

rawDescription: Optimize Class Simulation Code?

description: Optimize Class Simulation Code


code:
import wx
from enum import Enum

from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub

import logging

#####
#   The control events that the Controller can process
#   Usually this would be in a module imported by each of M, V and C
#   These are the possible values for the "event" parameter of an APP_EVENT message

class AppEvents(Enum):
    APP_EXIT = 0
    APP_ADD_WORKPLACE = 1
    APP_ADD_CUSTOMER = 2
    CUSTOMER_DEPOSIT = 3
    CUSTOMER_WITHDRAWAL = 4
    CUSTOMER_EARN = 5
    PERSON_WORK = 6
    EARN_REVENUE = 7

#################
#
#   View
#

class MainWindow(wx.Frame):

    def __init__(self,  title):
        wx.Frame.__init__(self, None, -1, title)

        self._log = logging.getLogger("MVC Logger")
        self._log.info("MVC View - separate workspace: starting...")

        self._bankStatusDisplay = None
        self._customerUIs = {}
        self._workplaceUIs = {}

        # this is where we will put display elements - it's up to the controller to add them
        self._sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(self._sizer)

        # but we do need one button immediately...
        add_workplace_button = wx.Button(self, label="Add Workplace")
        self._sizer.Add(add_workplace_button)
        self._sizer.Layout()

        self.Bind(wx.EVT_BUTTON, self._OnAddWorkplaceClick, add_workplace_button)

        # These are the events that cause us to update our display
        pub.subscribe(self._OnCustomerBalanceChange, "CUSTOMER_BALANCE_EVENT")
        pub.subscribe(self._OnBankBalanceChange, "BANK_BALANCE_EVENT")

        self.Show()

    def _OnAddWorkplaceClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.APP_ADD_WORKPLACE)

    def AddWorkplace(self, workplace):
        self._workplaceUIs[workplace.name] = WorkplaceInterface(self, workplace)

    def AddBank(self, bank):
        if not(self._bankStatusDisplay):
            self._bankStatusDisplay = BankStatusDisplay(self, bank)
            self._sizer.Add(self._bankStatusDisplay)
            self._sizer.Layout()
        else:
            raise Exception("We can only handle one bank at the moment")

    def AddCustomer(self, customer):
        self._customerUIs[customer.name] = CustomerInterface(self, customer)

    def AddWorkplace(self, workplace):
        self._theWorkplaceUI = WorkplaceInterface(workplace)

    def _OnCustomerBalanceChange(self, value):
        customer = value
        self._customerUIs[customer.name].UpdateBalance()

    def _OnBankBalanceChange(self):
        self._bankStatusDisplay.Update()

class BankStatusDisplay(wx.Panel):
    def __init__(self, parent, bank):
        wx.Panel.__init__(self, parent, style = wx.RAISED_BORDER)

        self._bank = bank

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self, label="Bank Funds")

        balance_display = wx.TextCtrl(self)
        balance_display.SetEditable(False)
        balance_display.SetValue('$' + str(bank.Funds()))

        sizer.Add(label, 0, wx.EXPAND | wx.ALL)
        sizer.Add(balance_display, 0, wx.EXPAND | wx.ALL)

        self.SetSizer(sizer)

        self._balanceDisplay = balance_display

    def Update(self):
        self._balanceDisplay.SetValue('$' + str(self._bank.Funds()))

class CustomerInterface(wx.Frame):
    def __init__(self, parent, customer):
        wx.Frame.__init__(self, None, -1, customer.name, size = (200,300))

        self._customer = customer
        self._standardTransaction = 5 # how much customers try to deposit and withdraw

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self, label=customer.name)

        self._balanceDisplay = wx.TextCtrl(self)
        self._balanceDisplay.SetEditable(False)
        self._balanceDisplay.SetValue('$' + str(customer.CashInHand()))

        deposit_button = wx.Button(self, label="Deposit $" + str(self._standardTransaction))
        withdraw_button = wx.Button(self, label="Withdraw $" + str(self._standardTransaction))
        earn_button = wx.Button(self, label="Earn Money")

        sizer.Add(label, 0, wx.EXPAND | wx.ALL)
        sizer.Add(self._balanceDisplay, 0, wx.EXPAND | wx.ALL)

        sizer.Add(deposit_button, 0, wx.EXPAND | wx.ALL)
        sizer.Add(withdraw_button, 0, wx.EXPAND | wx.ALL)
        sizer.Add(earn_button, 0, wx.EXPAND | wx.ALL)

        self.Bind(wx.EVT_BUTTON, self._OnDepositClick, deposit_button)
        self.Bind(wx.EVT_BUTTON, self._OnWithdrawClick, withdraw_button)
        self.Bind(wx.EVT_BUTTON, self._OnEarnClick, earn_button)

        self.SetSizer(sizer)
        self.Show()

    def _OnDepositClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.CUSTOMER_DEPOSIT, value = (self._customer, self._standardTransaction))

    def _OnWithdrawClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.CUSTOMER_WITHDRAWAL, value = (self._customer, self._standardTransaction))

    def _OnEarnClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.CUSTOMER_EARN, value = self._customer)

    def UpdateBalance(self):
        self._balanceDisplay.SetValue('$' + str(self._customer.CashInHand()))

class WorkplaceInterface(wx.Frame):
    def __init__(self, workplace):
        wx.Frame.__init__(self, None, -1, workplace.name, size = (200,200))

        self._workplace = workplace

        self._panel = wx.Panel(self, style = wx.RAISED_BORDER)

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self._panel, label="Funds")

        self._balanceDisplay = wx.TextCtrl(self._panel)
        self._balanceDisplay.SetEditable(False)
        self._balanceDisplay.SetValue('$' + str(workplace.Funds()))

        revenue_button = wx.Button(self._panel, label="Earn Revenue")

        sizer.Add(label, 0, wx.EXPAND | wx.ALL)
        sizer.Add(self._balanceDisplay, 0, wx.EXPAND | wx.ALL)

        sizer.Add(revenue_button, 0, wx.EXPAND | wx.ALL)

        self._panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self._OnRevenueClick, revenue_button)

        pub.subscribe(self._OnBalanceChange, "WORKPLACE_BALANCE_EVENT")

        self.Show()

    def _OnRevenueClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.EARN_REVENUE, value = (self._workplace))

    def _OnBalanceChange(self):
        self._balanceDisplay.SetValue('$' + str(self._workplace.Funds()))

rawDescription: How to keep the controller alive

description: Keep the controller alive


code: file <- open('record.txt')

rawDescription: How to convert column data from text file into list in Python?

description: Convert column data from text file into list in Python


code:
from os.path import join

filepath = 'C:\\Users\\Josh\\Documents\\Programming'
infile = join(filepath, 'data.txt')
infile = open(infile,"r")

rawDescription: Accelerometer Data write to file then graph Matplotlib (3 subplots [x, y, z])


code:
h1_val = sess.run(weights['h1'])

fp = open('NN_for_Dymola.txt', 'w')

#############################
fp.write("********** W1 **********\n")

fp.write("[")
for i in range(n_hidden_1):
    fp.write("{"),
    if i == n_hidden_1-1:
        for j in range(n_input):
            if j == n_input - 1:
                fp.write( '%1.10f' % h1_val[j,i] ),
            else:
                fp.write( '%1.10f,' % h1_val[j,i] ),
        fp.write( '}' ),
    else:
        for j in range(n_input):
            if j == n_input - 1:
                fp.write( '%1.10f' % h1_val[j,i] ),
            else:
                fp.write( '%1.10f,' % h1_val[j,i] ),
        fp.write( '},' ),
fp.write( ']' )

fp.close()

rawDescription: How to quickly print Tensorflow results to TXT?

description: Quickly print Tensorflow results to TXT


code:
from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

rawDescription: How to group a list into inclusive sequential n-tuples

description: Group a list into inclusive sequential n-tuples


code:
from sympy import *
x, y  = symbols('x y')
solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])

rawDescription: From Matlab to Python - Solve function

description: From Matlab to Python - Solve function


code:
#!/usr/bin/python
from time import sleep
import RPi.GPIO as GPIO
import os
while True:
   if not os.path.exists("open_gate.txt"):continue
   os.remove("open_gate.txt")   # FILE DELETE !!! so we dont re-enter
   with open("log.txt","w") as f:
     print >>f,"Opening GATE @ %s"%(time.strftime("%x %X"),)
     GPIO.setmode(GPIO.BOARD)
     print >>f, "Set Mode To %s"%(GPIO.BOARD,)
     GPIO.setup(11, GPIO.OUT)
     print >>f, "SET 11 to %s"%(GPIO.OUT)
     GPIO.output(11, False)
     print >> f,"output low signal 11"
     sleep(0.4)
     GPIO.output(11, True)
     print >> f,"output high signal to 11"
     sleep(1.6)
     GPIO.output(11, False)
     print >> f,"output low signal 11"
     sleep(1)
     print >> f,"Competed TASK"

rawDescription: Cannot execute python script from php

description: Cannot execute python script from php


rawDescription: Neatly pass positional arguments as args and optional arguments as kwargs from argpase to a function


code:
from Bio import SeqIO
from random import sample
with open("foo.fasta") as f:
    seqs = SeqIO.parse(f,"fasta")
    print(sample(list(seqs), 2))

rawDescription: How to randomly extract FASTA sequences using Python?

description: Randomly extract FASTA sequences using Python


code:
result = []
for elem in a_list:
    result.append(a_func(elem))

rawDescription: for line in f: why is there a difference when replacing in lists?

description: For line in f: why is there a difference when replacing in lists


code:
def addition_range(start, end):
    return [(lambda x, i=i: x + i) for i in range(start, end)]

rawDescription: Generator and actual variable values

description: Generator and actual variable values


code:
import tkinter as tk

class SubWindow(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        x = tk.Text(self)
        x.pack(expand=1, fill='both')

class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self)
        self.win1 = SubWindow(self)
        self.win1.pack(side="left", expand=1, fill=tk.BOTH)
        self.win2 = SubWindow(self)
    self.win2.pack(side="right", expand=1, fill=tk.BOTH)

if __name__ == "__main__":
    main = MainWindow()
    main.mainloop()

rawDescription: Can you combine two tkinter tk widgets?

description: Combine two tkinter tk widgets


code: Transitions[0,i,j] = sum([Transitions[0,i,k] for k in range(1,i+1,1)])

rawDescription: Sum values of a dictionary

description: Sum values of a dictionary


rawDescription: Automate the Boring Stuff, Chapter 6 Table Printer


code: 'this is a sentence. this is another.'.capitalize()

rawDescription: Title case for a paragraph

description: Title case for a paragraph


code:
all_mentions.columns.name = 'at_number'
all_mentions.index.name = 'tweet'  # this is timestamp in your example

rawDescription: Split a Pandas 'findall' result list into multiple items, to group by uniques


rawDescription: How to delete from an arbitrarilly deeply nested dictionary

description: Delete from an arbitrarilly deeply nested dictionary


code:
ALABAMA = 'Alabama'
...

STATES = ((ALABAMA, ALABAMA), ...)

rawDescription: How to read a data file containing survey form options into models.py

description: Read a data file containing survey form options into models.py


code:
def get_indices_simple(data):
    return [np.where(data == i) for i in range(0, data.max() + 1)]

rawDescription: faster alternative to numpy.where?

description: Faster alternative to numpy.where


rawDescription: Scanning two integers separated by an unknown character


code:
class Foo:
    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def __lt__ (self, other):
        if self.a == other.a:
            return self.b < other.b
        return self.a < other.b

    def __gt__ (self, other):
        return other.__lt__(self)

    def __eq__ (self, other):
        return self.a == other.b and self.b == other.b

    def __ne__ (self, other):
        return not self.__eq__(other)

rawDescription: Python equivalent of Java's compareTo()

description: Python equivalent of Java's compareTo()


code:
c += 2
print(fc())  # note the (), calling the function

rawDescription: Python Variables and Equations

description: Python Variables and Equations


code:
for i in range(len(self.OBJECTS)):
    #img = Texture(see op)
    img = self.OBJECTS[i].IMAGE
    print(img)
    e = None
    if self.OBJECTS[i].zOrder == 4: # is isometric image
        # tx and ty are translated positions for screen2iso. See Below
        if ((self.tx >= 0 and self.tx < self.SETTING['MAP_WIDTH']) and (self.ty >= 0 and self.ty < self.SETTING['MAP_HEIGHT'])):
            # map_x and map_y are starting points for the map its self.
            ix, iy = self.screen2iso(
                (x - (self.map_x + (self.SETTING['TILE_WIDTH'] / 2))),
                (y - (self.map_y))
            )
            imgx, imgy = self.screen2iso(
                (img.x - (self.map_x + (self.SETTING['TILE_WIDTH'] / 2))),
                (img.y - (self.map_y))
            )
            if (imgx+2) == ix:
                if (imgy+1) == iy:
                    e = self.OBJECTS[i]
                else:
                    continue
            else:
                continue
    else: # Not an isometric image
        if x > img.x and x < (img.x + img.rect[2]):
            if y > img.y and y < (img.y + img.rect[3]):
                #is click inside of visual area of image?
                if self.getCordInImage(x, y, self.OBJECTS[i].IMAGE):
                    if self.getAlphaOfPixel(self.OBJECTS[i]) != 0:
                        e = self.OBJECTS[i]
                else:
                    continue
            else:
                continue
        else:
            continue
    if e != None:
        if self.CLICKED['zOrder'] < e.getZ():
            self.CLICKED['zOrder'] = e.getZ()
            self.CLICKED['e'] = e
        else:
            continue
    else:
        continue

rawDescription: Python pygame Detect if mouse is over non transparent part of surface


code:
def repeat_or(a, n=4):
    m = np.isnan(a)
    k = m.copy()

    # lenM and lenK say for each mask how many
    # subsequent Trues there are at least
    lenM, lenK = 1, 1

    # we run until a combination of both masks will give us n or more
    # subsequent Trues
    while lenM+lenK < n:
        # append what we have in k to the end of what we have in m
        m[lenM:] |= k[:-lenM]

        # swap so that m is again the small one
        m, k = k, m

        # update the lengths
        lenM, lenK = lenK, lenM+lenK

    # see how much m has to be shifted in order to append the missing Trues
    k[n-lenM:] |= m[:-n+lenM]

    return k

rawDescription: Extend numpy mask by n cells to the right for each bad value, efficiently


code:
first = None
for d in L:
    if 'firstname' in d and 'lastname' in d:
        first = d
        break

rawDescription: Get to nested dictionary in list

description: Get to nested dictionary in list


code:
def shift_hsv(arr, delta_h, delta_, delta_v):
    r, g, b, a = np.rollaxis(arr, axis=-1)
    h, s, v = rgb_to_hsv(r, g, b)
    h =+ delta_h
    s += delta_s
    v += delta_v
    r, g, b = hsv_to_rgb(h, s, v)
    arr = np.dstack((r, g, b, a))
    return arr

rawDescription: Changing the color of an image based on RGB value


code:
res = test.delay(1)
res.ready()  # before finishing task
res.ready()  # after finishing task

rawDescription: celery issuing tasks from subtasks

description: Celery issuing tasks from subtasks


code: return {'/' + key + '/': val for key, val in dictionary.items()}

rawDescription: Cannot get dictionary keys to look like i want them to


code: Counter(item for items in sentences for item in items.split()).most_common(10)

rawDescription: How to create a list from splitting a list elements in python?

description: Create a list from splitting a list elements in python


code:
def extension(path):
    name, ext = os.path.splitext(path)
    return ext[1:]

rawDescription: Is there another better way to get file ext from a given path in python


code:
import urllib.request
urllib.request

rawDescription: Python can't find installed modules

description: Python can't find installed modules


code: {'A{}'.format(i + 1): v for i, v in enumerate(sorted(x for x in os.listdir("T:\\") if certain_condition(x)))}

rawDescription: Creating a dictionary with comprehensions?


code:
import requests

url = "http://nppes.viva-it.com/NPPES_Data_Dissemination_{}_{}.zip"
r = requests.get(url.format("March", 2015))

rawDescription: Python Downloading Data File from Web-Scraped URL


rawDescription: find tangent vector at a point for discrete data points

description: Find tangent vector at a point for discrete data points


rawDescription: Dictionary with sorted unique values

description: Dictionary with sorted unique values


rawDescription: QT python connect passing arguments to function


code:
from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
excel.Visible = True #if you want to see it
sheet = excel.Workbooks.open('Book1').Sheets('Sheet1')
# get value from a cell:
sheet.Cells(1, 1).value

# get range
sheet.Range('A1:A2000')

# etc. google about vlookup and other functionalities. You can run anything you would in excel through python here, it's just an API

rawDescription: Querying an Excel spreadsheet and returning results? But which program?


code:
import random

def randomLine(file_object):
    "Retrieve a random line from a file, reading through the file once"
    lineNum = 0
    selected_line = ''

    while 1:
        aLine = file_object.readline(  )
        if not aLine: break
        lineNum = lineNum + 1
        # How likely is it that this is the last line of the file?
        if random.uniform(0,lineNum)<1:
            selected_line = aLine
    file_object.close(  )
    return selected_line

rawDescription: pick a random line from a very big file, from command line

description: Pick a random line from a very big file, from command line


code:
a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']
b = ['boo', 'aaa', 'bii']
a_sep = [x.split('/')[1] for x in a]
idxs = [i for i, x in enumerate(a_sep) if x in b]
idxs
[a[i] for i in idxs]

rawDescription: Cross-list comprehension in Python

description: Cross-list comprehension in Python


rawDescription: Splitting Lists elements further

description: Splitting Lists elements further


code:
L = map(int, S)  # makes S into a sequence of integers in one step
if sum(L) % 10 != 0:  # % calculates the remainder, which should be 0
    return False

rawDescription: Credit card check exercise python

description: Credit card check exercise python


code: berries = 'strawberries, bilberry, blackberry'

rawDescription: Web2py custom forms and for loop

description: Web2py custom forms and for loop


code: GetIntegerSlice(123456, 3, 4)

rawDescription: Get part of an integer in Python

description: Get part of an integer in Python


code:
bs, jn = [1, 2], [3, 4]
list(itertools.chain(x for x in [bs, jn]))

rawDescription: lambda - 'QuerySet' object has no attribute 'xxx'

description: Lambda - 'QuerySet' object has no attribute 'xxx'


code:
class OtherVideos(BoxLayout):

    main = ObjectProperty()

    def __init__(self, *args, **kwargs):
        super(OtherVideos,self).__init__(*args, **kwargs)
        self.loadVideos()
    ...

rawDescription: Kivy - Why Label does not update?

description: Kivy - Why Label does not update


code:
from collections import Counter
from string import punctuation

def content_text(text):
    stopwords = set(nltk.corpus.stopwords.words('english')) # 0(1) lookups
    with_stp = Counter()
    without_stp  = Counter()
    with open(text) as f:
        for line in f:
            spl = line.split()
            # update count off all words in the line that are in stopwrods
            with_stp.update(w.lower().rstrip(punctuation) for w in spl if w.lower() in stopwords)
               # update count off all words in the line that are not in stopwords
            without_stp.update(w.lower().rstrip(punctuation)  for w in spl if w  not in stopwords)
    # return a list with top ten most common words from each
    return [x for x in with_stp.most_common(10)],[y for y in without_stp.most_common(10)]
wth_stop, wthout_stop = content_text(...)

rawDescription: Print 10 most frequently occurring words of a text that including and excluding stopwords


code:
{
    '61': u'motorbikes',
    '5': u'boats',
    '4': u'cars',
    '17': u'planes',
    '40': u'submarines'
}

rawDescription: Parsing a web form using Beautifulsoup 4 and Python 2.7


code: x, = unpacker(b'\xff\xff\xce')

rawDescription: Translating Array Manipulation in C++ to Python


code: perms = ['{}{}{}'.format(pre, delimiter, ''.join(p)) for p in permutations(post)]

rawDescription: python 2.7 permutation of string starting from index

description: Python 2.7 permutation of string starting from index


code: s = set('ABCDE')

rawDescription: Statistical counting in Python

description: Statistical counting in Python


code: dirs = [d for d in dirs if d not in dirExclude and not re.search(exre, d)]

rawDescription: Create list using regex inputs

description: Create list using regex inputs


code:
def get_users(log):
    f = open(log)
    # Read header line
    h = f.readline().strip().replace('\'', '').split('\t')
    ix_profile = h.index('profile.type')
    ix_user = h.index('profile.id')

    assert ix_user < ix_profile

rawDescription: Optimize this python log-parsing code

description: Optimize this python log-parsing code


rawDescription: python/mongodb Updating and Structure in subtrees

description: Python/mongodb Updating and Structure in subtrees


rawDescription: Python cant get full path name of file

description: Python cant get full path name of file


code:
import ast
import json
import re

pat = re.compile(r"""(?P<key>\w+)\s*:\s*(?P<value>.+)$""")

data_dict = {}
with open('log.txt', 'rU') as f:
    braces = 0
    for line in (line.strip() for line in f):
        if braces > 0:
            match = pat.search(line)
            if match and len(match.groups()) == 2:
                key = match.group('key')
                value = ast.literal_eval(match.group('value'))
                data_dict[key] = value
        elif '{' in line:
            braces += 1
        elif '}' in line:
            braces -= 1
        else:
            pass  # ignore line

print(json.dumps(data_dict, indent=4))

rawDescription: Parsing a file that looks like JSON to a JSON


code:
def user_info(username):
    from ldap_settings import *
    ...

rawDescription: web2py application configuration file

description: Web2py application configuration file


code:
trans = pd.DataFrame(columns=strings, index=strings)
g_dfm = dfm[dfm['group']==1]

for s1 in strings:
    for s2 in strings:
        events = g_dfm[(g_dfm['event']==s1) & (g_dfm['event_t1']==s2)]
        trans.ix[s1, s2] = len(events)

trans = trans.astype(float).div(trans.sum(axis=1), axis=0)
trans = trans.fillna(0)

rawDescription: Estimating transition probabilities (pandas)