code:
import pandas as pd
import numpy as np

#array_size = 10

#--- Generate Data and create toy Dataframe ---
array_size = 750
np.random.seed(1)
data = np.random.randint(0, 1000000, array_size**2)
data = data.reshape((array_size, array_size))
df = pd.DataFrame(data, columns=['c'+str(i) for i in range(1, (array_size)+1)])
df.index = df.columns

#--- Transpose the dataframe to more familiarly sort by columns instead of rows ---
df = df.T

#--- Rank values in dataframe using max method where highest value is rank 1 ---
df = df.rank(method='max', ascending=False)

#--- Create empty dataframe to put data into ---
new_df = pd.DataFrame()

#--- For loop for each column to get top ranks less than 5, sort them, reset index, drop i column
for i in df.columns:
  s = df[i][df[i] < 5].sort_values().reset_index().drop(i, axis=1)
  new_df = pd.concat([new_df, s.T])

#--- The new_df index will say 'index', this reassigns the transposed column names to new_df's index
new_df.index = df.columns
print(new_df)

rawDescription: How to get the column name using values in a dataframe?

description: Get the column name using values in a dataframe


code:
import re

pattern = re.compile('^12\d+$')

Schema(And(str, lambda x: pattern.match(x) is not None))

rawDescription: Python object validation thanks to a Schema


code:
def initialize(self, *args, **kwargs):
    _connections[id(self)] = self
    super(ConnectNamespace, self).initialize(*args, **kwargs)

def disconnect(self, *args, **kwargs):
    del _connections[id(self)]
    super(ConnectNamespace, self).disconnect(*args, **kwargs)

rawDescription: How to emit SocketIO event on the serverside

description: Emit SocketIO event on the serverside


code:
import json
json_str = r'''
{
    "publisher": "\"O'Reilly Media, Inc.\""
}
'''  # raw string to prevent the \" from being interpreted by Python
json.loads(json_str)

rawDescription: Python breaks parsing json with characters \"


rawDescription: How would I search a .txt file for something between <> python


code: my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])

rawDescription: Python - set list range to a specific value


code:
pygame.init()
screen = pygame.display.set_mode((640, 480))

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

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == MOUSEBUTTONDOWN:
            # draw background first (however)
            screen.fill((0,0,0))

            # draw your other layers (mouse image)

            # draw the circle
            color = (255,255,255)
            posx,posy = pygame.mouse.get_pos()
            pygame.draw.circle(screen, color, (posx,posy), 50)

    pygame.display.update()

rawDescription: Why won't pygame draw a circle?

description: Why won't pygame draw a circle


code:
for x in range(1):
    if not check1():
        break
    if not check2():
        break
    if not check3():
        break
    do_something()

rawDescription: How can I write C's do-while(0) in Python?

description: Write C's do-while(0) in Python


code:
self.application = tornado.web.Application([
    (r"/test", SomeHandler, {"ref_object" : self.ref_object}),
])

rawDescription: Tornado Get Reference to Instance Variable in RequestHandler


rawDescription: Python signals and slots between classes


code:
import pandas
from StringIO import StringIO

pathToFile = 'test/file.txt'
f = open(pathToFile)
s = StringIO()
cur_ID = None
for ln in f:
    #replace multiply spaces to one ;
    ln = ';'.join(ln.split())
    if  ln.startswith('BD;'):
        ln = ln.replace('BD;', 'BD ')
    if  (ln.startswith('19')) | (ln.startswith('20')):
        continue;
    s.write(ln + '\n')
s.seek(0)

df = pandas.read_csv(s, skiprows=3, sep=';', names=['0','1','2','3','TOT'])

rawDescription: Assigning columns to a pandas dataframe constructed from a string


code:
from __future__ import division, print_function

import sys
import time
import multiprocessing as mp
import numpy as np
from scipy.integrate import odeint

def lorenz(q, t, sigma, rho, beta):
    x, y, z = q
    return [sigma*(y - x), x*(rho - z) - y, x*y - beta*z]

def solve(ic):
    t = np.linspace(0, 200, 801)
    sigma = 10.0
    rho = 28.0
    beta = 8/3
    sol = odeint(lorenz, ic, t, args=(sigma, rho, beta), rtol=1e-10, atol=1e-12)
    return sol

if __name__ == "__main__":
    ics = np.random.randn(100, 3)

    print("multiprocessing:", end='')
    tstart = time.time()
    num_processes = 5
    p = mp.Pool(num_processes)
    mp_solutions = p.map(solve, ics)
    tend = time.time()
    tmp = tend - tstart
    print(" %8.3f seconds" % tmp)

    print("serial:         ", end='')
    sys.stdout.flush()
    tstart = time.time()
    serial_solutions = [solve(ic) for ic in ics]
    tend = time.time()
    tserial = tend - tstart
    print(" %8.3f seconds" % tserial)

    print("num_processes = %i, speedup = %.2f" % (num_processes, tserial/tmp))

    check = [(sol1 == sol2).all()
             for sol1, sol2 in zip(serial_solutions, mp_solutions)]
    if not all(check):
        print("There was at least one discrepancy in the solutions.")

rawDescription: Multiple scipy.integrate.ode instances

description: Multiple scipy.integrate.ode instances


code: {w:tuple(k for (k,v) in d.items() if v == w) for w in l}

rawDescription: Combining Keys in Dictionary into tuples in a list


code:
import urllib2
urllib2.__file__
import sys
sys.__file__

rawDescription: How can you find where python imported a particular module from?

description: Find where python imported a particular module from


code:
def format(d):
    children = []
    for (key, value) in d.iteritems():
        children += [{"name":key, "children":format(value)}]
    return children

rawDescription: Structuring Plain Text to JSON

description: Structuring Plain Text to JSON


code:
def formatbyte(n):
  return "%02Xh" % n

def formatword(n):
  return "%04Xh" % n

rawDescription: Strategy pattern in Python when a "strategy" consists of more than one function


rawDescription: Python Pandas Dataframe - Groupby and Average based on Condition


code: df

rawDescription: Counting occurrence of a word in a column of a tsv file using python


code: last_lines = d.groupby('A').apply(lambda g: g.index[-1])

rawDescription: Splitting Pandas Dataframe with groupby and last


rawDescription: Generating a new order for a list of lists in python


code:
def countreademail(view):
    def wrapper(request, *args, **kwargs):
        exists, myid = myexists(request)
        kwargs['unreadcount'] = messagescount(myid)[0]
    return view(request, *args, **kwargs)
return wrapper

rawDescription: Appending render with decorator in Django


code:
with open("in.txt") as f:
    for line in f:
        if line.startswith("DATE/USER:"):
            spl = line.split()
            if len(spl) == 3:
                print(spl[2])

rawDescription: Python: How to skip lines that have extra characters while using Regular Expressions?


code: def f(x): return 2*x

rawDescription: Assign multiple functions to a single variable?


rawDescription: Take OrderedDictionary as an argument and apply random.gauss(mean,std)


code:
import re
CARRIS_REGEX=r'(\d+)	([\s\w\.\-]+)	(\d+:\d+)	(\d+m)	'
pattern = re.compile(CARRIS_REGEX, re.UNICODE)
mailbody = open("test.txt").read()
for match in pattern.finditer(mailbody):
    print(match)
print()
for match in pattern.findall(mailbody):
    print(match)

rawDescription: Different behavior between re.finditer and re.findall


code:
file = open('D:\\mydirectory\\soggetti.txt','r')
file_pf = open("D:\\mydirectory\\file_pf.txt","w")
file_pg = open("D:\\mydirectory\\file_pg.txt","w")
file_pf.close()
file_pg.close()

p_lines = []
g_lines = []
with file:
    for line in file:
        fields = line.split("|")
        if fields[3] == "P":
            p_lines.append(line)
        elif fields[3] == "G":
            g_lines.append(line)
file.close()

file_pf = open("D:\\mydirectory\\file_pf.txt","w")
file_pf.writelines(p_lines)
file_pf.close()

file_pg = open("D:\\mydirectory\\file_pg.txt","w")
file_pg.writelines(g_lines)
file_pg.close()

rawDescription: Python: faster method to read and create file


code: urllib.urlencode({'p': [1, 2, 3]}, doseq=True)

rawDescription: Python Dictionary to URL Parameters

description: Python Dictionary to URL Parameters


code: result = line.split(';')

rawDescription: Python: Manipulate an array

description: Python: Manipulate an array


rawDescription: Creating a "normal" line chart in amcharts.js with arrays?


code:
_,s = min( (len( values[s]), s)
            for s in squares
            if len(values[s]) > 1
        )

rawDescription: Underscore _ as variable name in Python

description: Underscore _ as variable name in Python


code: print("\n".join("1" if m > 20 else "-1" for m in get_lengths(k)))

rawDescription: if the get_lengths(k) more than 20 then do something else do something

description: If the get_lengths(k) more than 20 then do something else do something


code:
def find_closest(A, target):
    #A must be sorted
    idx = A.searchsorted(target)
    idx = np.clip(idx, 1, len(A)-1)
    left = A[idx-1]
    right = A[idx]
    idx -= target - left < right - target
    return idx

rawDescription: Finding the nearest value and return the index of array in Python


code: indexDict[word] = indexDict.setdefault(word, []) + [count]

rawDescription: Creating an index of words

description: Creating an index of words


code: DATE_FORMAT = '%a, %d %b %Y %H:%M:%S UTC'

rawDescription: How to convert to a Python datetime object with JSON.loads?

description: Convert to a Python datetime object with JSON.loads


code:
import numpy as np

def shift_bit_length(x):
    return 1<<(x-1).bit_length()

def padpad(data, iterations = 1):
    narray = data
    for i in xrange(iterations):
        length = len(narray)
        diff = shift_bit_length(length + 1) - length
        if length % 2 == 0:
            pad_width = diff / 2
        else:
            # need an uneven padding for odd-number lengths
            left_pad = diff / 2
            right_pad = diff - left_pad
            pad_width = (left_pad, right_pad)
        narray = np.pad(narray, pad_width, 'constant')
    return narray

rawDescription: Zero-padding data until its length is equal to a power of 2


code: disp = stereo.compute(imgL, imgR).astype(np.float32) / 16.0

rawDescription: put 3D world coordinates in 2D array

description: Put 3D world coordinates in 2D array


code:
def main ():
    images=['test1.img','test2.img','test3.img']
    ROOT="/local/mnt/workspace"
    target="wc3123"
    for image in images:
        #Construct ROOT + "/out/target/product/" + target + "/test1.img
        #for each image mentioned in imageslist remove if it exist"
        test1= ROOT + "out/target/product/" + target + "/" + image
        check_call("rm -rf %s" %test1,shell=True)

rawDescription: Removing images mentioned in a list

description: Removing images mentioned in a list


code:
from A import *
foo
_bar

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


rawDescription: All pairs of pairs python

description: All pairs of pairs python


code:
from concurrent.futures import ThreadPoolExecutor, as_completed
from time import sleep
from random import random

job_count = 10

def is_even(x):
    return x % 2 == 0

def do_something(i):
    "All odd jobs complete before even jobs"
    if not is_even(i):
        return i
    sleep(0.1 + random())
    return i

with ThreadPoolExecutor(max_workers=job_count) as executor:
    successful_result = None
    futures = [executor.submit(do_something, i) for i in range(job_count)]

    for future in as_completed(futures):
        result = future.result()
        if is_even(result):
            successful_result = result
            break

print("the first successful result was:", successful_result)

rawDescription: Run a function only by the thread that is the first one to reach it's calling


rawDescription: How to import resource file in PyQt and build with pyinstaller?

description: Import resource file in PyQt and build with pyinstaller


code:
import numpy as np
# create exaple data where sum exceeds 255
a = np.arange(118,130,dtype = np.uint8)
b = a.copy()
res = np.add(a,b, dtype = np.uint16);
mask = res > 255
res[mask] = 255
res = np.uint8(res)

rawDescription: bounded sum or difference of arrays in numpy

description: Bounded sum or difference of arrays in numpy


code:
class MacroInput(object):
    def __init__(self, protein, carb, fat):
        self.protein, self.carb, self.fat = protein, carb, fat

    def sum(self):
        return self.protein + self.carb + self.fat

rawDescription: How to pass multiple values of different types to different functions

description: Pass multiple values of different types to different functions


code:
my_df.groupby(['A', 'B']).count()
len(my_df.groupby(['A', 'B']).groups)

rawDescription: How to find subgroups statistics in pandas?

description: Find subgroups statistics in pandas


code: w.bind("<KeyRelease>", onkeyrelease)

rawDescription: How to tell if a key has been released in tkinter

description: Tell if a key has been released in tkinter


code: u = set.intersection(s1, s2, s3)

rawDescription: how best do I find the intersection of multiple sets in python?

description: How best do I find the intersection of multiple sets in python


code: import os

rawDescription: Python - Copying only new files into another directory


code: self.gps = gps()

rawDescription: How to get inheritance to work from parent to child class python34

description: Get inheritance to work from parent to child class python34


code:
from heapq import heappush, heappushpop

heap = []
for x in [18, 85, 36, 57, 2, 45, 55, 1, 28, 73, 95, 38, 89, 15, 7, 61]:
    calculation_result = x + 1 # Dummy calculation
    if len(heap) < 10:
        heappush(heap, calculation_result)
    else:
        heappushpop(heap, calculation_result)

top10 = sorted(heap, reverse=True) # [96, 90, 86, 74, 62, 58, 56, 46, 39, 37]

rawDescription: Pythonic way to store top 10 results

description: Pythonic way to store top 10 results


code:
db.DSP.ensureIndex({type:"hash", fields: ['data[*].type']});
db.DSP.ensureIndex({type:"hash", fields: ['data[*].name']});

rawDescription: How to improve the retrieve Query performance in ArangoDB 2.7 with increasing the number of documents within a single collection

description: Improve the retrieve Query performance in ArangoDB 2.7 with increasing the number of documents within a single collection


code:
import string
s = string.ascii_letters
s
s[25]
-(len(s)-25)
s[-(len(s)-25)]

rawDescription: How do you find the negative index of a position if you know the index?

description: Find the negative index of a position if you know the index


code:
c=sparse.coo_matrix((data, (cols, rows)),shape=(3,3)).todok().tocsc()
c.A

rawDescription: Ignoring duplicate entries in sparse matrix


code:
globals.sys = sys_modules.sys = __import__('sys')
globals.sys.ps1 = 'something else '

rawDescription: Python import and module scoping (specifically sys.ps1)


code:
import cv2
import numpy as np

mode = ""
Schwelle =0

def nothing(x):
    pass

def read_pixel(event,x,y,flags,param):
    global mode, Schwelle
    if event == cv2.EVENT_MOUSEMOVE:
        if mode == "Analyse":
            ix,iy = x,y
            font = cv2.FONT_HERSHEY_SIMPLEX
            img2=img.copy()
            cv2.putText(img2,str(ix)+" "+str(iy)+": "+str(img[y,x]),(50,50), font, 1,(255,255,255),2,cv2.LINE_AA)
            cv2.imshow('image',img2)
    elif event == cv2.EVENT_RBUTTONDOWN:
        if mode == "Analyse":
            mode=""
            Schwelle=img[y,x]
            cv2.createTrackbar('Schwelle','image',Schwelle,255,nothing)
        else:
            mode = "Analyse"
    elif event == cv2.EVENT_LBUTTONDOWN:
        Schwelle= img[y,x]

img =cv2.imread('image.png',0)
cv2.namedWindow('image')
cv2.setMouseCallback('image',read_pixel)
cv2.createTrackbar('Schwelle','image',128,255,nothing)

while(1):
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

    if mode != "Analyse":
        Schwelle = cv2.getTrackbarPos('Schwelle','image')
        ret,thresh1 = cv2.threshold(img,Schwelle,255,cv2.THRESH_BINARY)
        cv2.imshow('image',thresh1)

cv2.destroyAllWindows()

rawDescription: Convert different shades of a color in an image to one color


code:
harmonic = np.arange(4)
var1 = 2

rawDescription: Preventing nested list output from a for-loop / list comprehension when appending new values to an Array


code: course = Course.objects.get(slug=slug)

rawDescription: Current field values from session in Django


rawDescription: Python, Sort List

description: Python, Sort List


code:
w = w[order]
v = v[order]

rawDescription: Numpy "sort like" function

description: Numpy "sort like" function


code:
start = subparsers.add_parser("start")
start.add_argument("--foo")

rawDescription: Using argparse to create custom command line formats


code: a + a

rawDescription: How to increase the performance for estimating `Pi`in Python

description: Increase the performance for estimating `Pi`in Python


code: print >>OutputFile, "Something to print"

rawDescription: Saving data into a text file

description: Saving data into a text file


rawDescription: parse string into columns python pandas /xa0 in stead of white space

description: Parse string into columns python pandas /xa0 in stead of white space


code:
b = np.empty((6,),dtype=object)
b[:] = list(a.reshape(-1,2))
b = b.reshape(2,3)

rawDescription: Convert a numpy array to an array of numpy arrays


code:
def test_if_ascii(text):
    if isinstance(test, str):
        raise TypeError('hey man, dont feed me unicode plz')
    return all(32 <= ord(c) <= 126 for c in text)

rawDescription: How to decode() with a subset of 'ascii'?

description: Decode() with a subset of 'ascii'


code:
cbcdefghi
cdcdefghi
cdedefghi
cdefefghi

rawDescription: python replace records in variable

description: Python replace records in variable


code: llong = range(longmin + longstepx, longmax + longstepx, longstepx)

rawDescription: Loop through list and changing indexes

description: Loop through list and changing indexes


code:
phrase = "This is - no doubt - punctuated"
[word.strip(string.punctuation) for word in phrase.split(" ")]

rawDescription: Removing single quotation marks while preserving apostrophes Python, NLTK


code:
import itertools
headers = set(itertools.chain.from_iterable(counts_to_display.values()))

rawDescription: How to write defaultdict in more pythonic way?

description: Write defaultdict in more pythonic way


code:
from collections import Counter
counts = Counter((k[1], v) for k, v in dictA.iteritems())
print(counts)

rawDescription: Python: Counting repeating values of a dictionary


rawDescription: Python - regex not escaping parentheses in alphanumeric string with symbols and a variable passed in to method


code:
for attr in kwargs.viewkeys() & self.attrs:
    setattr(self, attr, kwargs[attr])

rawDescription: Python - short syntax and list comprehension and iterations


code:
def create(self, args):
    username = args['username']
    ...

rawDescription: How to get all parameters into a data structure (list/dict/etc) in webapp2

description: Get all parameters into a data structure (list/dict/etc) in webapp2


code:
from mainwindowfilename import mainwindowclassname
from toolbarfilename import toolbarsclassname
from menubarfilename import menubarclassname

rawDescription: How could I make a good application architecture in Python with PyQt?


code: birth_dates = reverse(list(map(date_string, filter(is_over_13, birthdays))))

rawDescription: Map two functions together in Functional Programming paradigm


code:
import tkinter as tk
import tkinter.filedialog
import traceback
import tkinter.ttk as ttk

from pygments import lex
from pygments.lexers import PythonLexer

import sys
import os

class TextLineNumbers(tk.Canvas):
    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")
        while True:
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
            i = self.textwidget.index("%s+1line" % i)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

        self.comment = False

class Tab:
    def __init__(self, parent, filename, parentwindow):
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.parentwindow = parentwindow
        self.language = "Python"
        self.parent = parent
        self.filename = filename
        self.tab1 = ttk.Frame(parent)
        self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))

        self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.linenumbers = TextLineNumbers(self.tab1, width=55)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        parent.add(self.tab1, text=filename)
        self.bottomLabel()

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)
        self.text.bind("<KeyRelease>", self.keypress)
        self.text.bind("<Button-1>", self.keypress)

    def deafultHighlight(self, argument):
        self.content = self.text.get("1.0", tk.END)
        self.lines = self.content.split("\n")

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", self.row + ".0")
            data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def highlight(self, argument):
        self.content = self.text.get("1.0", tk.END)

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", "1.0")
            data = self.text.get("1.0", self.text.index(tk.INSERT))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def keypress(self, argument):
        self.updateBottomLabel()
        self.deafultHighlight("argument")

    def _on_change(self, event):
        self.linenumbers.redraw()

    def bottomLabel(self):
        self.positionAndLanguage = tk.Label(self.parentwindow, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
        self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)

    def updateBottomLabel(self):
        self.row = self.text.index(tk.INSERT).split(".")[0]
        self.column = self.text.index(tk.INSERT).split(".")[1]
        self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)

class Arshi(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.language = "Python"
        self.row = "0"
        self.column = "0"
        self.startCol = 0
        self.tabs = []
        self.notebook = ttk.Notebook(self)

        self.menubar()
        #self.bottomLabel()
        self.createtext()

    def deafultHighlight(self, argument):
        self.content = self.text.get("1.0", tk.END)
        self.lines = self.content.split("\n")

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", self.row + ".0")
            data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def highlight(self, argument):
        self.content = self.text.get("1.0", tk.END)

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", "1.0")
            data = self.text.get("1.0", self.text.index(tk.INSERT))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def keypress(self, argument):
        self.updateBottomLabel()
        self.deafultHighlight("argument")

    def configureTags(self, text):
        text.tag_configure("Token.Keyword", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Constant", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Declaration", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Namespace", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Pseudo", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Reserved", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Type", foreground="#CC7A00")

        text.tag_configure("Token.Name.Class", foreground="#003D99")
        text.tag_configure("Token.Name.Exception", foreground="#003D99")
        text.tag_configure("Token.Name.Function", foreground="#003D99")

        text.tag_configure("Token.Operator.Word", foreground="#CC7A00")

        text.tag_configure("Token.Comment", foreground="#B80000")

        text.tag_configure("Token.Literal.String", foreground="#248F24")

    def createtext(self):
        self.notebook.pack(fill=tk.BOTH, expand=True)
        t = Tab(self.notebook, self.fileName, self)
        self.tabs.append(t)

    def addtab(self):
        t = Tab(self.notebook, self.fileName, self)
        self.tabs.append(t)

    def removetab(self):
        numberOfTabs = self.notebook.index("end")

        if numberOfTabs > 1:
            tabIndex = self.notebook.index(self.notebook.select())
            self.notebook.forget(tabIndex)

    def run(self):
        pass

    def menubar(self):
        self.menu = tk.Menu(self)
        self.master.config(menu=self.menu)

        self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.fileMenu.add_command(label="New             Ctrl+N", command=self.newFile)
        self.fileMenu.add_command(label="Open            Ctrl+O", command=self.openFile)
        self.fileMenu.add_command(label="Save            Ctrl+S", command=self.saveFile)
        self.fileMenu.add_command(label="Save As         Ctrl+Shift+S", command=self.saveAsFile)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="New Window", command=self.addtab)
        self.fileMenu.add_command(label="Close Window", command=self.removetab)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit            Alt+F4", command=self.close)
        self.menu.add_cascade(label="File", menu=self.fileMenu)

        self.runMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.runMenu.add_command(label="Run", command=self.run)
        self.menu.add_cascade(label="Run", menu=self.runMenu)

    def bottomLabel(self):
        self.positionAndLanguage = tk.Label(self, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
        self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)

    def updateBottomLabel(self):
        self.row = self.text.index(tk.INSERT).split(".")[0]
        self.column = self.text.index(tk.INSERT).split(".")[1]
        self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)

    def newFile(self):
        self.addtab()

    def openFile(self):
        try:
            self.fileName = tk.filedialog.askopenfilename() #Asks user to open file
            with open(self.fileName, 'r') as file:
                self.content = file.read() #Reads content typed
            self.text.delete(0.0, tk.END)
            self.text.insert(0.0, self.content)
            self.highlight(self)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexpected error occured.")

    def deleteContent(self, file):
        file.seek(0)
        file.truncate()

    def saveFile(self):
        self.content = self.text.get(0.0, tk.END)

        try:
            with open(self.fileName, 'w') as file:
                self.deleteContent(file)
                file.write(self.content)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexpected error occured.")

    def saveAsFile(self):
        self.content = self.text.get(0.0, tk.END)

        try:
            self.fileName = tk.filedialog.asksaveasfilename()
            if self.fileName != None:
                with open(self.fileName, 'w') as file:
                    file.write(self.content)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexcepted error occured.")

    def close(self):
        try:
            os._exit(0)
        except:
            print(sys.exc_info()[0])

    def _on_change(self, event):
        self.linenumbers.redraw()

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Arshi")
    root.geometry("1024x600")
    window = Arshi(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Line numbers and Syntax Highlighting don't work on different tabs


code:
from itertools import islice, chain

def to_chunks(iterable, chunksize):
    it = iter(iterable)
    while True:
        first = next(it)
        # Above raises StopIteration if no items left, causing generator
        # to exit gracefully.
        rest = islice(it, chunksize-1)
        yield chain((first,), rest)

with open('filename.txt') as f:
    for chunk in to_chunks(f, 10):
        for line in chunk:
            ...

rawDescription: Python - Reading chunks and break if there is no lines


code:
log = open('some file.txt', 'a')
log.write('some text, as header of the file\n')
log.flush()  # <-- here's something not to forget!
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

rawDescription: append subprocess.Popen output to file?

description: Append subprocess.Popen output to file


code:
from re import findall
text = "one,two;three.four:"
findall("(?:^|\W)\w*", text)

rawDescription: Split string based on regexp without consuming characters


rawDescription: Extracting integers from a string of ordered pairs in Python?


code:
from subprocess import call
call(["cygstart", "http://www.google.com"])

rawDescription: Why can't I open a webbrowser with webbrowser.open("www.python.org") on Cygwin?


code:
def multirange(counts):
    counts = np.asarray(counts)
    # Remove the following line if counts is always strictly positive.
    counts = counts[counts != 0]

    counts1 = counts[:-1]
    reset_index = np.cumsum(counts1)

    incr = np.ones(counts.sum(), dtype=int)
    incr[0] = 0
    incr[reset_index] = 1 - counts1

    # Reuse the incr array for the final result.
    incr.cumsum(out=incr)
    return incr

rawDescription: How to efficiently concatenate many arange calls in numpy?

description: Efficiently concatenate many arange calls in numpy


rawDescription: Reduce by key in python

description: Reduce by key in python


rawDescription: Add calculated row to pandas DataFrame

description: Add calculated row to pandas DataFrame


code:
b = df.pivot('USERNAME', 'REQUEST_TYPE')
b.columns = ['{0}_{1}'.format(*col) for col in b.columns]

rawDescription: Pandas: pivot a dataframe

description: Pandas: pivot a dataframe


code:
#ifndef INFINITY
#define INFINITY 0
#endif

rawDescription: How to represent inf or -inf in Cython with numpy?

description: Represent inf or -inf in Cython with numpy


code:
[{'desc': ['smth', 'smthelse2', 'smthelse3'], 'id': 1},
 {'desc': ['smthelse'], 'id': 2}]

rawDescription: python list of dictionaries find duplicates based on value

description: Python list of dictionaries find duplicates based on value


code: text(x, y, s, fontsize=12)

rawDescription: Putting text in top left corner of matplotlib plot


code: results = db.session.query(User, last_entry).outerjoin(last_entry, User.email == last_entry.c.email)

rawDescription: Reference query results with outerjoin in Flask/SQLAlchemy/jinja


code:
def extractTuple(s):
    s = s.strip()
    n = len(s)
    p = s[1:n-1].split(',')
    return (p[0].strip(),p[1].strip())

def dictFromFile(fname):
    f = open(fname)
    lines = f.read().split('\n')
    f.close()
    d = {}
    for line in lines:
        line = line.strip()
        if line.endswith(','):
            line = line[:len(line)-1]
            k,v = line.split(':')
            d[k] = extractTuple(v)
    return d

rawDescription: Python forming a dictionary from a text file with value being a tuple


code:
import sys
print(sys.executable)

rawDescription: How do I know the location of the python executable from within the python script?

description: Know the location of the python executable from within the python script


rawDescription: select from list B k distinct elements that are not in list A in python?

description: Select from list B k distinct elements that are not in list A in python


rawDescription: Pandas dataframe read large number as string


code: np.count_nonzero((blocks == 255).all(axis=(-1, -2)))

rawDescription: How to count the elements in a Numpy stride-tricks blocks?

description: Count the elements in a Numpy stride-tricks blocks


code:
A=np.arange((12)).reshape(2,6)
A

rawDescription: Creating columns with numpy Python

description: Creating columns with numpy Python


code:
from itertools import permutations

patterns = set(''.join(per) for per in permutations('AGUCN'))
unilist = []

for line in f2:
    if line.strip() in patterns:
        unilist.append(next(f2).strip())

rawDescription: Look ahead without itertools

description: Look ahead without itertools


code:
l=[list(combinations(range(10),i)) for i in range(1,11)]
sum(map(len,l))

rawDescription: How to calculate the number of all possible combinations for a range of numbers from 1 to N?

description: Calculate the number of all possible combinations for a range of numbers from 1 to N


code: G = nx.from_numpy_matrix(y, create_using=nx.DiGraph())

rawDescription: Reading a networkx graph from a csv file with row and column header


code: [['mcgoga12', 'password'], ['shelby12', 'password1']]

rawDescription: Parsing a text file with Python and split()


code: cmds.setAttr('{0}.weightList[0].weights[0:{1}]'.format(deformerNode, VertexNb), *weight, size=len(weight))

rawDescription: How to change the weights of a deformer from a script in Maya?

description: Change the weights of a deformer from a script in Maya


code:
foo = Foo()
foo.bar()
foo.eep()
foo.c = 30
foo.eep()

rawDescription: Python Suite, Package, Module, TestCase and TestSuite differences


code:
class Family(models.Model):
    pass # your fields here

class Child(models.Model):
    family = models.ForeignKey(Family)

rawDescription: Reverse lookup on Django m2m field?

description: Reverse lookup on Django m2m field


code:
a = np.array(["a", "b", "c"], dtype=object)
b = np.array(["x", "y", "z"], dtype=object)
c = a + b
c

rawDescription: Combine all elements of two arrays python


code:
from bs4 import BeautifulSoup

data = """

test0

test1

test2

empty

"""

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

for elm in soup.select("div[class^=product_item]"):
    if "emptyItem" in elm["class"]:  # skip elements having emptyItem class
        continue

    print(elm.get_text())

rawDescription: Python Beautifulsoup Find_all except

description: Python Beautifulsoup Find_all except


code:
from __future__ import division
import math
math.pow(27, 1/3)

rawDescription: Extracting of the arithmetic root of arbitrary degree


rawDescription: UnicodeDecodeError while using json.dumps()


code:
import kivy
kivy.require('1.0.7')

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty, BooleanProperty
from kivy.lang import Builder

Builder.load_string('''
<Scroller>
    # root is Scroller here
    # create a new ObjectProperty in kv that holds the ref to Gridlayout
    # so you can access the instance in python code
    view: glayout
    GridLayout:
        id: glayout
        cols: 1
        size_hint: (1, None)
        height: self.minimum_height

<Field>
    canvas.before:
        Color:
            rgba: (0.2, 0.2, 0.2, 1) if self.bg else (0.1, 0.1, 0.1, 1)
        Rectangle:
            # binding properties is done implicitly and instructions aren't
            # piled up while doing that.
            pos: self.pos
            # self here refers to Field as `self` is supposed to refer to the
            # Widget not the drawing instruction
            size: self.size
    rows: 1
    padding: 10
    size: (0, 60)
    size_hint: (1, None)
    Label:
        text: root.name
    Button:
        text: 'test button'
        size: (200, 0)
        size_hint: (None, 1)
''')

class Main(App):

    def build(self):
        self.root = GridLayout(rows = 1)
        self.root.add_widget(Scroller())
        return self.root

class Scroller(ScrollView):
    def __init__(self, **kwargs):
        super(Scroller, self).__init__(**kwargs)
        for i in range(20):
            # access self.view that was set in kv
            self.view.add_widget(
                                Field(
                                    name = 'Test field {}'.format(i),
                                    bg = i%2 is 0))

class Field(GridLayout):

    # use  kivy's Properties so it becomes easier to observe and apply changes
    # as a plus these can also be directly used in kv. As a advantage of using this now
    # you can change name and bg dynamically and the changes should be reflected on
    # screen
    name = ObjectProperty('Test field uninitialized')

    bg = BooleanProperty(False)

if __name__ in ('__main__', '__android__'):
    app = Main()
    app.run()

rawDescription: Kivy background in scroll view

description: Kivy background in scroll view


code:
scriptPath = sys.path[0]
toolDataPath = os.path.join(scriptPath, "ToolData")

rawDescription: Resolving mixed slashes from sys.path and os.path.join


code:
a
b
pd.DataFrame(list(product(a,b)), columns=['col1', 'col2'])

rawDescription: Join unique values into new data frame (python, pandas)


code:
p = subprocess.Popen(['spam', 'eggs'])
ps = psutil.Process(p.pid)
p.wait()
print('spam used {}s of system time'.format(ps.cpu_times().system))

rawDescription: measure elapsed time, amount of memory and cpu used by the extern program

description: Measure elapsed time, amount of memory and cpu used by the extern program


code: image.objects.extra(select={'favorited': 'EXISTS(SELECT * FROM app_favorite WHERE image_id = app_image.id AND user_id = %s)'}, select_params=[current_user.pk])

rawDescription: Displaying images, and next to every image display if it has been favorited by the user


rawDescription: How to take the logarithm with base n in numpy?

description: Take the logarithm with base n in numpy


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mode')
p = parser.parse_args()
print(p)

rawDescription: Passing empty string to argparse

description: Passing empty string to argparse


code:
mm.__bases__
type(mm1).__bases__
type(mm1).__bases__[0] is mm

rawDescription: Why does type(mock.MagicMock()) == mock.MagicMock returns False?


code: dfs = [corn.loc[date:date+pd.Timedelta(days=29)] for date in samples]

rawDescription: Advanced array/dataframe slicing (numpy/pandas)


rawDescription: Does lexical scope have a dynamic aspect?


code:
# concatenate data for PCA
samples = np.concatenate((class1_sample, class2_sample), axis=0)

# mean values
mean_x = mean(samples[:,0])
mean_y = mean(samples[:,1])
mean_z = mean(samples[:,2])

#eigenvectors and eigenvalues
eig_val, eig_vec = np.linalg.eig(cov_mat1)

################################
#plotting eigenvectors
################################

fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(111, projection='3d')

ax.plot(samples[:,0], samples[:,1], samples[:,2], 'o', markersize=10, color='g', alpha=0.2)
ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.5)
for v in eig_vec:
    #ax.plot([mean_x,v[0]], [mean_y,v[1]], [mean_z,v[2]], color='red', alpha=0.8, lw=3)
    #I will replace this line with:
    a = Arrow3D([mean_x, v[0]], [mean_y, v[1]],
                [mean_z, v[2]], mutation_scale=20,
                lw=3, arrowstyle="-|>", color="r")
    ax.add_artist(a)
ax.set_xlabel('x_values')
ax.set_ylabel('y_values')
ax.set_zlabel('z_values')

plt.title('Eigenvectors')

plt.draw()
plt.show()

rawDescription: Putting arrowheads on vectors in matplotlib's 3d plot


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout

Builder.load_string("""
<Boxes>:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        ScreenManager:
            size_hint: 1, .9
            id: _screen_manager
            Screen:
                name: 'screen1'
                BoxLayout:
                    orientation: 'vertical'
                    padding: 50
                    BoxLayout:
                        orientation: 'horizontal'
                        Button:
                            text: "1"
                    BoxLayout:
                        orientation: 'horizontal'
                        Button:
                            text: "2"
                        Button:
                            text: "3"
                        Button:
                            text: "4"
                    BoxLayout:
                        orientation: 'horizontal'
                        Button:
                            text: "5"
                        Button:
                            text: "6"
                    BoxLayout:
                        orientation: 'horizontal'
                        Button:
                            text: "7"
                        Button:
                            text: "8"
                        Button:
                            text: "9"
                        Button:
                            text: "10"
            Screen:
                name: 'screen2'
                Label:
                    text: 'Another Screen'
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'bottom'
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, .1
            Button:
                text: 'Go to Screen 1'
                on_press: _screen_manager.current = 'screen1'
            Button:
                text: 'Go to Screen 2'
                on_press: _screen_manager.current = 'screen2'""")

class Boxes(FloatLayout):
    pass

class TestApp(App):
    def build(self):
        return Boxes()

if __name__ == '__main__':
    TestApp().run()

rawDescription: Making a layout with variable number of columns per row in kivy?


code:
#coding: utf-8
import string
text = u"Montréal, über, 12.89, Mère, Françoise, noël, 889"
allowed_letters = string.printable
name_has_accented = [letter for letter in text if not letter in allowed_letters]
if name_has_accented:
    text = "".join(convert(text))
print(text)

rawDescription: How to detect ASCII characters on a string in python

description: Detect ASCII characters on a string in python


rawDescription: Python Dictionary Adding Values

description: Python Dictionary Adding Values


rawDescription: Avoiding a for-loop to remove a slice of the list


code:
class TestOriginal(unitest.TestCase):
    @patch.object(module_under_test, 'A')
    def test_Original_method(self, mocked_A):
        mocked_A.return_value = 42
        result = module_under_test.B()
        mocked_A.assert_called_with()
        self.assertEqual(result, 420)

rawDescription: Patch a method outside python class

description: Patch a method outside python class


code:
def keep_this_element(element):
    return element[0].startswith('img')   # returns True for ('img...', '...')

new_list = filter(keep_this_element, l)   # keeps only elements that return True

rawDescription: Finding in elements in a tuple and filtering them


code: [['instrumentos-musicales-126030594.htm', 'liquidacion-muebles-y-electrodomesticos-127660457.htm'], ['INSTRUMENTOS MUSICALES', 'LIQUIDACION,  MUEBLES Y ELECTRODOMESTICOS']]

rawDescription: JSON Python Lists

description: JSON Python Lists


code:
# ...

import print_all

# ...

def main():
    print_all.main("updates.gz")

rawDescription: Python - How to call the main fuction of a module in another module?


rawDescription: Difference between lists in Python

description: Difference between lists in Python


code:
def __init__(self, dbapiName, *connargs, **connkw):
    adbapi.ConnectionPool.__init__(self, dbapiName, *connargs, **connkw)

def runMultiQuery(self, *args, **kw):
    return self.runInteraction(self._runMultiQuery, *args, **kw)

def _runMultiQuery(self, trans, *args, **kw):
    result = trans.execute(*args, **kw)
    result_list = []
    for item in result:
        if item.with_rows:
            result_list.append(item.fetchall())
    return result_list

rawDescription: Using MySQL.connector with Twisted Python to execute multiple queries


code:
class Node:

    def __init__(self, item, left=None, right=None):

        self.item = item
        self.left = left
        self.right = right

    def internals_impl(self):
        leaves = []
        internals = []
        if self.left == None and self.right == None:
            leaves.append(self.item)
        else:
            if self.left:
                itls = self.left.internals_impl()
                internals.extend(itls)
            if self.right:
                itls = self.right.internals_impl()
                internals.extend(itls)
            internals.append(self.item)
        return internals

    def internals(self):
        nodes = self.internals_impl()
        return len(nodes),nodes

if(__name__ == "__main__"):

    tree = Node(10,Node(3, Node(4)),Node(7, Node(8)))
    print(tree.internals())

rawDescription: Internals of a tree

description: Internals of a tree


code:
chr(0xff)
ord('\xff')

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


code:
import binascii
import struct
struct.pack('d', 0.0)
binascii.hexlify(struct.pack('d', 0.0))
binascii.hexlify(struct.pack('d', 1.0))
binascii.hexlify(struct.pack('d', 123.456))

rawDescription: BitConverter.DoubleToInt64Bits equivalent in python


code: command = [SCRIPT, "R", ">", OUT_FILE, "2>", "/dev/null"];

rawDescription: stop execution of a bashscript when parent python script is killed

description: Stop execution of a bashscript when parent python script is killed


code:
([x for x in 1.0.__class__.__base__.__subclasses__()
   if x.__name__ == 'catch_warnings'][0]()
   )._module.__builtins__['__import__']('os').system('echo hi!')

rawDescription: Regex include the negative lookbehind

description: Regex include the negative lookbehind


code:
t = datetime.timedelta(seconds=1)
t

t1 + t
k = t1 + t

rawDescription: what would be the python code to add time to a specific timestamp?

description: What would be the python code to add time to a specific timestamp


code:
myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

rawDescription: Writing to a file in a for loop

description: Writing to a file in a for loop


code:
def myview(request):
    svg_data = generate_some_svg_data()
    return HttpResponse(svg_data, content_type="image/svg+xml")

rawDescription: Open link contents in django template

description: Open link contents in django template


rawDescription: Cumulative numbers in python dictionaries


code:
import itertools
list(itertools.product((2006,2007,2008), (1,2)))

rawDescription: Get all available combinations of two fields through the Django ORM?


code:
import sys
x = 2
sys.getsizeof(x)
sys.getsizeof(sys.getsizeof)
sys.getsizeof('this')
sys.getsizeof('this also')

rawDescription: In-memory size of a Python structure

description: In-memory size of a Python structure


code: arr1 = arr - means[:,None]

rawDescription: NumPy vectorised method for computing covariance with population means (for survey data)


code:
from flask import Flask, render_template
from flask.ext.assets import Environment, Bundle

app = Flask(__name__)

assets = Environment(app)
assets.url = app.static_url_path
scss = Bundle('foo.scss', 'bar.scss', filters='pyscss', output='all.css')
assets.register('scss_all', scss)

rawDescription: Using sass with Flask and jinja2

description: Using sass with Flask and jinja2


code: # Note: `add_path_resolver` is experimental.  The API could be changed.

rawDescription: Parse YAML and assume a certain path is always a string


rawDescription: Pandas: transform a DataFrame by splitting each value into multiple values


code: first, last = MyModel.allocate_ids(100, parent=p)

rawDescription: How to guarantee the uniqueness of gae datastore Name/ID?

description: Guarantee the uniqueness of gae datastore Name/ID


code:
id_to_pos = {key: i for i, key in enumerate(req_ids)}
sorted(res_result, key=lambda d: id_to_pos[d['id']])

rawDescription: How can I order a list of dictionaries based on another list which has the key?

description: Order a list of dictionaries based on another list which has the key


code:
def get_how_many_match(value_to_match, list_of_dice):
    count = 0
    for dice in list_of_dice:
        if dice == value_to_match:
           count += 1
    return count

rawDescription: check if two values of lists have the same numbers return how many are same

description: Check if two values of lists have the same numbers return how many are same


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

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


code:
def batch_gumbel_max_sample(a, max_gumbel_noise = 1.0):
    matrix_U = -1.0*tf.log(-1.0*tf.log(tf.random_uniform(tf.shape(a),
                            minval = 0.0, maxval = max_gumbel_noise)))
    return tf.argmax(tf.sub(a, matrix_U), dimension = 1)

rawDescription: Implementing seq2seq with sampled decoder outputs


code:
import matplotlib.pyplot as plt

lists = [data[project]["tweets"] for project in data] # Collect all lists into one
sum_list = [sum(x) for x in zip(*lists)] # Create a list with sums of tweets for each day

plt.plot(sum_list) # Create a plot for sum_list
plt.show() # Show the plot

rawDescription: How to plot histogram of multiple lists?

description: Plot histogram of multiple lists


code: otherclass_obj = OtherClass(classa_init_args, classb_init_args, classc_init_args)

rawDescription: python memory consumption and performance related to classes

description: Python memory consumption and performance related to classes


code:
import re

def make_email(i):
    def email(scanner, token):
        print('{t}: Send to email{i}'.format(t=token, i=i))
    return email

scanner = re.Scanner(
    [(pat, make_email(i))                                    # 2
     for i, pat in enumerate((r"^[a-e]\w+", r"^[f-j]\w+"))]  # 1
    + [(r"\s+", None)],
    flags=re.IGNORECASE|re.MULTILINE)

scanner.scan("""\
Albert
Barry
Carrie
David
Erin
Franklin
Geoff
Harold
Isadore
Jay""")

rawDescription: Properly mapping first names to emails?

description: Properly mapping first names to emails


code: f.write("\t".join(["\ningredient: ", ingredient, quant, unit]))

rawDescription: python 3 - find and replace all numbers in a text file

description: Python 3 - find and replace all numbers in a text file


code:
def hi_function(name):
   return 'Hello %s'%(name)

rawDescription: py2exe with different parts of apps

description: Py2exe with different parts of apps


rawDescription: Unable to parse json in python

description: Unable to parse json in python


rawDescription: How to specify multiple return types using type-hints

description: Specify multiple return types using type-hints


code: desc_div = result.find('span', {'class': 'st'})

rawDescription: Updated approach to Google search with python


code:
if card1 == "yes":
    card1thread = Thread(target = cardf1)
    card1thread.start()

rawDescription: Basic Python Threading Behavior

description: Basic Python Threading Behavior


code:
AGE = raw_input("Enter your age: ")
GENDER = raw_input("Enter your gender (m/f): ")
HEIGHT = raw_input("Enter your height in cm: ")

vdf = vertica.select_dataframe("""
    INSERT INTO stats (
        age,
        gender,
        height
    )
    VALUES
    (
        '%s',
        '%s',
        '%s'
    )
""" % ( AGE, GENDER, HEIGHT ))

rawDescription: Python arguments inside triple quotes

description: Python arguments inside triple quotes


code:
doc.xpath('//*[contains(text(), "PRICE:")]/\
          ancestor::*[not(self::strong|self::bold|self::italic)][1]')

rawDescription: Fetch partial string matched html tag using xpath


code:
#For loop to calculate metrics
for x in range(0,HMDrr.SLOPE.count()):
    values = calc_linear(x)
    HMDrr.SLOPE[x] = values[0]
    HMDrr.INTERCEPT[x] = values[1]

rawDescription: How do I use row index to create a function based calculated column

description: Use row index to create a function based calculated column


rawDescription: Pattern match in file

description: Pattern match in file


code:
y.iloc[:, numeric].sum()
y.iloc[:, ~numeric].min()

rawDescription: Combining multiple data types in pandas DataFrame


code:
elem = driver.find_element_by_xpath(
     '//label[@for="Rooms"]/parent::td/following-sibling::td')

rawDescription: Selenium/Python: Find <label for=""> element with no other attributes


code: struct.unpack('BBB', packet)

rawDescription: How to capture all characters in binary string without python interpreting it

description: Capture all characters in binary string without python interpreting it


code:
soup = BeautifulSoup(html)
myTitle = soup.html.head.title

rawDescription: Python fetching <title>

description: Python fetching <title>


code: wb = xlrd.open_workbook(url, file_contents=data)

rawDescription: Process File in memory using python

description: Process File in memory using python


code:
def my_view(request, city, state, filters):
    # Split into a list ['name', 'value', 'name', 'value']. Note we remove the
    # first character of the string as it will be a slash.
    split = filters[1:].split('/')

    # Map into a dictionary {'name': 'value', 'name': 'value'}.
    filters = dict(zip(split[::2], split[1::2]))

    # Get the values you want - the second parameter is the default if none was
    # given in the URL. Note all entries in the dictionary are strings at this
    # point, so you will have to convert to the appropriate types if desired.
    radius = filters.get('radius', None)
    company = filters.get('company', None)

    # Then use the values as desired in your view.
    context = {
        'city': city,
        'state': state,
        'radius': radius,
        'company': company,
    }
    return render_to_response('my_view.html', context)

rawDescription: django - regex for optional url paramaters

description: Django - regex for optional url paramaters


code:
self.ToggleButtonObj = wx.ToggleButton(self, -1, 'ButtonLabel')
self.ToggleButtonObj.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggleClick)

def OnToggleClick(self,event):
    if self.ToggleButtonObj.GetValue():
         self.ToggleButtonObj.SetBackgroundColour('#color1')
    else:
         self.ToggleButtonObj.SetBackgroundColour('#color2')

rawDescription: How do I set the color of a toggle button in wxpython?

description: Set the color of a toggle button in wxpython


rawDescription: wxPython widgets are one on top of the other

description: WxPython widgets are one on top of the other


code: li.append((3, 'three'))

rawDescription: How to pass tuple as argument in Python?

description: Pass tuple as argument in Python


code:
def make_filter(ex):
    def do_filter(path):
        pat = r'.+\.(' + ex + ')$'
        match = re.search(pat, path)
        return match and match.group(1) == ex
    return do_filter

filter(make_filter('txt'), files)

rawDescription: Python: Passing functions with arguments to a built-in function?


code:
import unicodedata
stripped = u"".join([c for c in unicodedata.normalize('NFKD', input_str)
    if not unicodedata.combining(c)])

rawDescription: Delete weird ANSI character and convert accented ones using Python


code:
value_map = dict(values)
matches = [(name, value_map[name]) for name in set(names) if name in value_map]

rawDescription: Find co-occurrences of two lists in python


code:
def first_found(l):
    seen = set()
    for k, v in l:
        if k not in seen:
            yield (k, v)
        seen.add(k)

rawDescription: Keep firstly found duplicate items in a list


code:
def f1():
   [item for item in my_list if any(x in item for x in bad)]

def f2():
   [i for e in bad for i in my_list if e in i]

timeit.Timer(f1).timeit()
timeit.Timer(f2).timeit()

rawDescription: Check if list item contains items from another list


code:
_format_changes = (
    ('MMMM', '%B'),
    ('MMM',  '%b'), # note: the order in this list is critical
    ('MM',   '%m'),
    ('M',    '%m'), # note: no exact equivalent
    # etc etc
    )

def conv_format(s):
    for c, p in _format_changes:
        # s.replace(c, p) #### typo/braino
        s = s.replace(c, p)
    return s

rawDescription: Python datetime format like C# String.Format


code:
import numpy as np
list_xc = []
list_yc = []
for i in np.arange(10):
    list_xc.append(xc)
    list_yc.append(yc)
mat_xc = np.asarray(list_xc)
mat_yc = np.asarray(list_yc)
mat_f = np.column_stack((mat_xc, mat_yc))

rawDescription: Create 2d Array in Python Using For Loop Results


code:
class Terminator(BoxLayout):
    def DelButton(self):
        for child in [child for child in self.children if child.text != "Delete"]:
            self.remove_widget(child)

rawDescription: kivy access child id

description: Kivy access child id


code:
id_map = {}
id_map["Bracelets"] = "178785"
id_map["Earrings"] = "177591"
id_map["Kids Earrings"] = "177591"
# etc

rawDescription: python if...elif always not working

description: Python if...elif always not working


rawDescription: Printing Extended-Ascii Characters In Python 3 In Both Windows and Linux


code:
b = [a[0]]
for item in a[1:]:
    b.append(b[-1] + item)

b

rawDescription: Discrete Integration if List of Values

description: Discrete Integration if List of Values


code: min(positions, key=lambda x: x[0]**2 - x[1])

rawDescription: Python finding minimum values of functions of list items, but returning the list item


code:
document = view.get_dom_document()
nodes = document.get_elements_by_tag_name('*')
for i in range(nodes.get_length()):
    node = nodes.item(i)
    if isinstance(node, WebKit.DOMHTMLInputElement) or isinstance(node, WebKit.DOMHTMLTextAreaElement):
        native.add_event_listener(pythonToC(node), focused, blurred)

rawDescription: Can't find DOMEventTarget.add_event_listener in Python


rawDescription: Python regexp to match numbers with spaces


code:
#!/usr/bin/env python
from datetime import datetime, timedelta

def get_times(unit, relative_start, relative_end):
    relative_start, relative_end = [timedelta(**{unit+'s': v})
                                    for v in [relative_start, relative_end]]
    now = datetime.utcnow() # or datetime.now(timezone.utc).astimezone()
    return now + relative_start, now + relative_end

rawDescription: Compare times with python

description: Compare times with python


code:
word = "help"
scrambled = ['p','e','h','l']
list(word)
sorted(scrambled, key=word.index)

rawDescription: Sorting string into identical words

description: Sorting string into identical words


rawDescription: IPython with own scope?

description: IPython with own scope


rawDescription: Merge Duplicates based on column?

description: Merge Duplicates based on column


code: dict1.update({k: v for k, v in dict2.items() if v})

rawDescription: Appending python dictionaries, without replacing if the value is empty


code:
class Foo(object):
    @property
    def foo(self):
        return 'foo'
    echo = with_descriptor_defaults(foo)(mk_foobar)

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
import sys, termios
termios.tcsetattr(sys.stdin.fileno(),termios.TCSADRAIN, previous_mode )

rawDescription: How can I determine when a user is in the process of entering something as an input in Python?

description: Determine when a user is in the process of entering something as an input in Python


code: sometext, message1, message2, message3

rawDescription: variadic / arbitrary number of *args or ** kwargs in str.format() in Python

description: Variadic / arbitrary number of *args or ** kwargs in str.format() in Python


code: df.apply(lambda x: x / x.max(), axis=1)

rawDescription: Assigning to a Row in Pandas

description: Assigning to a Row in Pandas


code:
import six
from collections import OrderedDict

class UserHyperLinkedRelatedField(serializers.HyperLinkedRelatedField):

    @property
    def choices(self):
        queryset = self.get_queryset()
        if queryset is None:
            return {}

        return OrderedDict([
            (
                six.text_type(self.to_representation(item)),
                six.text_type(item.get_full_name())
            )
            for item in queryset
        ])

rawDescription: How do I customize the text of the select options in the api browser?

description: Customize the text of the select options in the api browser


code: flux = map(float, raw_input("Enter flux values separated by spaces ").strip().split(" "))

rawDescription: Enter many numbers using raw_input()

description: Enter many numbers using raw_input()


rawDescription: How to make Checkbutton which is automatically checked using gtk

description: Make Checkbutton which is automatically checked using gtk


code:
result = grequests.map(request)
content = '\n'.join(r.content for r in result) # raw content
text = '\n'.join(r.text for r in result)       # decoded content

rawDescription: Python: How can i send multiple HTTP requests and receive the response?


code:
lista=['1','2','3','4']
lista = [int(element) for element in lista]
lista

rawDescription: Modifing element in array using for and in


code:
updateFileName(filename, "sixty", reset=True)
updateFileName(filename, "sixty", decrease=True)
updateFileName(filename, "sixty")

rawDescription: Python-How can i change part of a row in a CSV file?


code: plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

rawDescription: Bin size in Matplotlib (Histogram)

description: Bin size in Matplotlib (Histogram)


rawDescription: how to calculate the norm of a vector in a large mxnx3 array?

description: Calculate the norm of a vector in a large mxnx3 array


code:
class Root(object):
    def __getitem__(self, key):
        if key in ['Red', 'Green']:
            return ColorCategory(key)
        elif key in ['4', '5']:
            return SizeCategory(key)

class ColorCategory(object):
    ...

class SizeCategory(object):
    ...

rawDescription: In Pyramid, using traversal, how do create dynamic urls?


code:
from collections import Counter

with open('numbers.txt','r') as infile:
    hist = Counter(int(line) for line in infile)

rawDescription: incrementing list values Python 3

description: Incrementing list values Python 3


code: df.loc[msk, ['EntryDate', 'ExitDate']]

rawDescription: Comparing Pandas Dataframe Rows & Dropping rows with overlapping dates


code:
class ThemeSerializer(serializers.ModelSerializer):
    levels = MultiSourceField(source=[
        PuzzleLevelSerializer(source="puzzlelevel_set"),
        ImageAndWordLevelSerializer(source="imageandwordlevel_set")
    ])

    class Meta:
        model = Theme
        fields = ("offset", "finished", "levels",)

rawDescription: django REST framework multi source field

description: Django REST framework multi source field


code: signal = real + 1j * imag

rawDescription: how to load 4-bit data into numpy array

description: Load 4-bit data into numpy array


code:
class Page(Base):
    id = sa.Column(sa.Integer, primary_key=True)
    slug = sa.Column(sa.String, index=True, unique=True)
    title = sa.Column(sa.String)
    body = sa.Column(sa.String)

rawDescription: How to mimic the url aliasing functionality of mod_rewrite with Pyramid (Python Framework)?

description: Mimic the url aliasing functionality of mod_rewrite with Pyramid (Python Framework)


code:
sequence = self.env['ir.sequence'].next_by_code('sale.order.line')
for rec in self:
    rec.niu = sequence

rawDescription: How to create an incremental field (sequence) that is validated with a method (def)

description: Create an incremental field (sequence) that is validated with a method (def)


code:
def show_multiples(low, high, num):
    even_count = 0
    odd_count = 0
    even_sum = 0
    odd_sum = 0

    for value in range(high, low-1, -1):
        if value % num:
            continue
        if value % 2 == 0:
            even_count += 1
            even_sum += value
        else:
            odd_count += 1
            odd_sum += value
        print(value),
    print

    print("{} even numbers total {}".format(even_count, even_sum))
    print( "{} odd numbers total {}".format(odd_count, odd_sum))

def main():
    high = int(input('Enter the high integer for the range: ')) # Enter the high integer
    low = int(input('Enter the low integer for the range: '))   # Enter the lower integer
    num = int(input('Enter the @integer for the multiples: '))   # Enter integer to find multiples

    show_multiples(low, high, num)

if __name__ == "__main__":
    main()

rawDescription: Count even and odd numbers and the totals (python)


code: {elt[0] : (elt[1], elt[2]) for elt in [elt.split(',') for elt in all_examples[:n]]}

rawDescription: create a dictionary for a certain range in Python

description: Create a dictionary for a certain range in Python


code:
fieldnames=registers['fields']['name'][0]
registers['fields']['name']
registers['fields']['name']=fieldnames
registers['fields']['name']
registers['fields']

rawDescription: Placing a numpy record array inside another record array python


code: set(a).intersection(b, c)

rawDescription: Python: how to find common values in three lists


code:
with open('path/to/file') as infile:
    allNums = [[int(num) for num in line.strip().split()[1:]] for line in infile]

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


rawDescription: re.findall printing the full text on a line of tekst

description: Re.findall printing the full text on a line of tekst


code: from itertools import product, izip

rawDescription: Punnett Square Function: Matching Items in Lists


rawDescription: Python speed testing - Time Difference - milliseconds


rawDescription: Python/PySide: How can i destroy a terminated thread object?


code:
def sieve_using_set(b):
    seq_primes=list(range(2, b + 1))
    sieve_set=set(range(2, b + 1))
    c=0
    while (seq_primes[c]**2)<b:
        k=c
        while seq_primes[k]<=(b/seq_primes[c]):
            sieve_set.discard(seq_primes[k] * seq_primes[c])
            k+=1
        c+=1
    return list(sorted(sieve_set))

rawDescription: Sieve of eratosthenes using dictionaries in python


rawDescription: Initialize all variables to a common value except one TBD variable


code: lo, hi = sorted([heappop(tree), heappop(tree)])

rawDescription: Huffman encoding issue

description: Huffman encoding issue


code:
for c in candidates:
    modname = os.path.splitext(c)[0]
    try:
        module=__import__(modname)   #<-- You can get the module this way
    except (ImportError,NotImplementedError):
        continue
    for cls in dir(module):          #<-- Loop over all objects in the module's namespace
        cls=getattr(module,cls)
        if (inspect.isclass(cls)                # Make sure it is a class
            and inspect.getmodule(cls)==module  # Make sure it was defined in module, not just imported
            and issubclass(cls,base)):          # Make sure it is a subclass of base
            # print('found in {f}: {c}'.format(f=module.__name__,c=cls))
            classList.append(cls)

rawDescription: Dynamic importing of modules followed by instantiation of objects with a certain baseclass from said modules


code:
from repoze.who.api import get_api

who_api = get_api(request.environ)
creds = {}
creds['login'] = yourusername
creds['password'] = yourpassword
authenticated, headers = who_api.login(creds)

rawDescription: How do I log a user in using repoze.who?

description: Log a user in using repoze.who


code:
class UsefulClass(object):

    def __new__(cls, *args, **kwargs):

        raise NotImplementedError("Create UsefulClass instances only with FactoryClass")

class FactoryClass(object):

    def __new__(cls, *args, **kwargs):
        """Do interesting things here, like modifying args and kwargs
        in a fancy way :) then call the default constructor"""
        instance = object.__new__(UsefulClass, *args, **kwargs)
        instance.__init__(*args, **kwargs)
        return instance

rawDescription: Only creating object through factory class in Python - factory class related


rawDescription: Simple OOP: Python, saving object names via __init__ v2


code:
import os, sys
os.path.dirname(sys.argv[0])

rawDescription: Open (read, write) a file in same directory as main app - python/kivy


code:
...
form = MyFormClass(is_add=True)
...

rawDescription: How to change Submit button text from a view in crispy-forms?

description: Change Submit button text from a view in crispy-forms


code:
def rawstr(s):
    """
    Return the raw string representation (using r'') literals of the string
    *s* if it is available. If any invalid characters are encountered (or a
    string which cannot be represented as a rawstr), the default repr() result
    is returned.
    """
    if any(0 <= ord(ch) < 32 for ch in s):
        return repr(s)

    if (len(s) - len(s.rstrip("\\"))) % 2 == 1:
        return repr(s)

    pattern = "r'{0}'"
    if '"' in s:
        if "'" in s:
            return repr(s)
    elif "'" in s:
        pattern = 'r"{0}"'

    return pattern.format(s)

rawDescription: How do I get the raw representation of a string in Python?

description: Get the raw representation of a string in Python


code:
from itertools import takewhile

lst = [1,2,3,4,5,6,7,8,9,10] # don't use list

tke = takewhile(lambda x: x< 6, lst)

for t in tke:
    print(t)
1
2
3
4
5

rawDescription: How to limit for loop to print first few element from list in terms of their value in python?

description: Limit for loop to print first few element from list in terms of their value in python


code:
class Decontext(object):
    """
    makes a context manager also act as decorator
    """

    def __init__(self, context_manager):
        self._cm = context_manager   # this may be a cm factory or type, but that's OK

    def __enter__(self):
        return self._cm.__enter__()

    def __exit__(self, *args, **kwds):
        return self._cm.__exit__(*args, **kwds)

    def __call__(self, *cm_args, **cm_kwargs):
        try:
            self._cm = self._cm(*cm_args, **cm_kwargs) # try calling the cm like a type
        except TypeError:
            pass
        def decorator(func):
            def wrapper(*args, **kwds):
                with self:
                    return func(*args, **kwds)

            return wrapper
        return decorator

rawDescription: Passing arguments to decontext decorator


code:
import subprocess

p = subprocess.Popen(
    ['ls', '-lat'],
    shell=False,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    stdin=subprocess.PIPE
)
while True:
    line = p.stdout.readline()
    if line == '':
        break
    print(line.strip())  # remove extra ws between lines

rawDescription: Reliable non blocking reads from subprocess stdout


code:
from collections import defaultdict, namedtuple

FruitPerson = namedtuple('FruitPerson','id age email')

d = defaultdict(list)

for sublist in lsta:
    d[sublist[1]].append(FruitPerson(sublist[0],*sublist[2:]))

rawDescription: How to create a new layer of sublists based on a common key within each sublist in order to categorize the sublists?

description: Create a new layer of sublists based on a common key within each sublist in order to categorize the sublists


rawDescription: Scheduling Filter on Database with Time Interval


code: no_primes = sorted(no_primes)

rawDescription: Python Get Access to locals() Back In 2.7 to Prevent Duplicates


code:
import Tkinter as tk

class dropDown():
    def __init__(self, master):

        #background set_up
        image1 = tk.PhotoImage(file="test.gif")
        w = image1.width()
        h = image1.height()
        panel1 = tk.Label(root, image=image1)
        panel1.pack(side='top', fill='both', expand='yes')

        # save the panel's image from 'garbage collection'
        panel1.image = image1

        #Drop down menu
        self.var = tk.StringVar(master)
        self.var.set('Alaska') # initial value

        #Have not used countries list just pasted
        self.option = tk.OptionMenu(master, self.var, 'Alaska','Alberta', 'Australia')
        self.option.pack()

        geomstr="%dx%d+0+0" % (w, panel1.winfo_reqheight()+self.option.winfo_reqheight())
        root.geometry(geomstr)

root = tk.Tk()
root.title('drop down test')
dropDown(root)
root.mainloop()

rawDescription: python - TKinter - Can I send background to back?

description: Python - TKinter - Can I send background to back


rawDescription: Writing 8 bit values to a binary file in python v3.3


code:
class Object1:
    d = 1

    def __str__(self):
        return str(self.d)

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

rawDescription: Python: How can I print out an object as a regular dictionary without reference?


rawDescription: Merging 2 Lists In Multiple Ways - Python


code:
stu += inp.split(' ')
stu

rawDescription: Printing on new line - python

description: Printing on new line - python


code:
transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)]
# [b'SiEn\x00', b'ptvl\x00', b'lsey\x00']

rawDescription: Break bytes object into n equally sized blocks based on index


code:
from itertools import count
def postponed_sieveL(level=0,PData={}):
    '''uses a seperate internal generator (two level form) - sieveL
    modified from
    http://stackoverflow.com/a/10733621, http://stackoverflow.com/a/19391111
    '''
    #this should be fine unless you stop the generator
    #  before it passes the first four primes

    dat=PData.get(level,0)#load any previous data
    if not dat:#no previous data, start from 2
        for i in [2, 3, 5, 7]:
            yield i

        D,C={},9
        ps=sieveL('I',PData)#inner generator
        next(ps)
        p=next(ps)
        psq=p*p

    else:#past the inital primes, load from previous run
        D,C,psq,p=PData[level]
        ps=sieveL('I',PData)#inner generator

    for i in count(C,2):
        if STOP:#set this outside of the generator

        #dict, current index (count value), squared prime and prime
            Internals[level]=[D,i,psq,p]

            w=next(ps)#inform the inner generator that it should stop
            break

        if i in D:
            step=D.pop(i)
        elif i<psq:
            yield i
            continue
        else:
            step=2*p
            p=next(ps)
            psq=p*p
        i+=step
        while i in D:
            i+=step
        D[i]=step

rawDescription: Pausable prime generator

description: Pausable prime generator


code:
args.s
args.d

rawDescription: Accessing argument values for argparse in Python


code:
data = np.tile(np.arange(4), 2)
fig = plt.figure()
ax = fig.add_subplot(121)
cax = fig.add_subplot(122)
cmap = colors.ListedColormap(['b','g','y','r'])
bounds=[0,1,2,3,4]
norm = colors.BoundaryNorm(bounds, cmap.N)
im=ax.imshow(data[None], aspect='auto',cmap=cmap, norm=norm)
cbar = fig.colorbar(im, cax=cax, cmap=cmap, norm=norm, boundaries=bounds,
     ticks=[0.5,1.5,2.5,3.5],)
plt.show()

rawDescription: Setting the limits on a colorbar in matplotlib


code: df.apply(lambda row: row[lists[row.name]].sum(), axis=1)

rawDescription: Python dataframe groupby by dictionary list then sum


code:
s = df.stack()
ii = s[s >= 6].index.tolist()

rawDescription: Extract indexes from Pandas DataFrame

description: Extract indexes from Pandas DataFrame


code:
import json
import ast

# Works if keys satisfy following requirement:
# key == ast.literal_eval(repr(key))
# This is true for tuples having numbers inside.

def dumps(d):
    return json.dumps({repr(key): value for key, value in d.items()})

def loads(s):
    d = json.loads(s)
    return {ast.literal_eval(key): value for key, value in d.items()}

rawDescription: Mapping a table with a compound primary key to a python dictionary


code: df.pivot_table(columns='a', aggfunc=lambda x: np.percentile(x, 50))

rawDescription: pandas pivot_table percentile / quantile

description: Pandas pivot_table percentile / quantile


code:
def mydecorator(f):
    x = 0
    def decorator():
        x += 1 # x is a nonlocal name and cant be modified
        return f(x)
    return decorator

rawDescription: Class decorators vs function decorators

description: Class decorators vs function decorators


code:
def readfile(file):
    for l in file.readlines():
        if pattern in l:
            yield l

for line in readfile(file):
    print(line)

rawDescription: With return get only the one line

description: With return get only the one line


code:
pv = df.pivot_table(index='A',
                    columns=['B', 'C'],
                    aggfunc='size',
                    fill_value=0)
pv

rawDescription: Crosstab in pandas with enforced values

description: Crosstab in pandas with enforced values


code:
game_table = pd.merge(df, df, how='left', on=['player'])
#    game_x player game_y
# 0   gameA      A  gameA
# 1   gameA      A  gameB
# 2   gameB      B  gameB
# 3   gameB      B  gameA
# 4   gameC      C  gameC
# 5   gameC      C  gameD
# 6   gameC      D  gameC
# 7   gameB      A  gameA
# 8   gameB      A  gameB
# 9   gameD      C  gameC
# 10  gameD      C  gameD
# 11  gameA      B  gameB
# 12  gameA      B  gameA

rawDescription: Pandas: calculate overlapping with pivot_table or crosstab


rawDescription: Python flattening my tuple structure

description: Python flattening my tuple structure


code:
def decorated():
    pass

decorated = decorator(decorated)

rawDescription: Catch signals in Flask Blueprint

description: Catch signals in Flask Blueprint


code:
class SingletonABCMeta(ABCMeta):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(SingletonABCMeta, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class GenericLogger(object):
    __metaclass__ = SingletonABCMeta

    @abstractproperty
    def SearchLink(self): pass

class Logger(GenericLogger):
    @property
    def SearchLink(self): return ''

rawDescription: Python implementing Singleton as metaclass , but for abstract classes


rawDescription: Encode string as hex bytes

description: Encode string as hex bytes


code:
u0 = Users(UserName='Lila')
u1 = Users(
    UserName='John',
    sent=[Messages(Message='hi', receiver=u0)]
)

rawDescription: Relationship between two tables one with 2 foreign keys in flask-sqlalchemy


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

class NewUserProcess(Process):
    user = models.ForeignKey(User, blank=True, null=True)

rawDescription: viewflow.io: How can I present a custom form for gathering input for a specific task?

description: Viewflow.io: How can I present a custom form for gathering input for a specific task


rawDescription: Set an array equal to the first half of it's entries in python


code:
cs = [True, False, True]
xs = [1, 2, 3]
ys = [10, 20, 30]

def generator(cs, xs, ys):
    for c, x, y in zip(cs, xs, ys):
        yield x if c else y

print(list(x if c else y for c, x, y in zip(cs, xs, ys)))
print(list(generator(cs, xs, ys)))

rawDescription: Filter with an else clause (numpy.where)


code: newDict = eval(repr(myDict).lower())

rawDescription: Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?


code:
import pandas as pd
import sqlite3
import string

## connect to a db. This db will be created if it does not exist
conn = sqlite3.connect('example.db')
c = conn.cursor()

np.random.seed(123)
## create some random data in a pandas dataframe
n = 1000000
c = 10

rawDescription: Group By operation for large dataset

description: Group By operation for large dataset


code:
import numpy as np
my_array = np.array([10, 20, 30])
new_positions = [2, 0, 1]  # or new_positions = np.array([2, 0, 1])
my_shuffled_array = my_array[new_positions]
my_shuffled_array

rawDescription: Permute a tuple by a list of indices

description: Permute a tuple by a list of indices


rawDescription: Keep the order of list used in $in query in Mongo


code:
def countLetters(search_in, search_for):
    count = 0
    for s in search_in:    # iterate by string char, not by index
        if s==search_for:
            count += 1
    return count

rawDescription: Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string


code:
class Event(db.Model):

    __tablename__ = "event"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    jobs = db.relationship('Job', backref='job_event')

class Job(db.Model):

    __tablename__ = "job"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    event_id = db.Column(db.Integer, db.ForeignKey('event.id'))
    apscheduler_job_id = db.Column(db.TEXT)

rawDescription: How to relate APScheduler JobStore with SQLAlchemy Models (foreign key) - Python Flask

description: Relate APScheduler JobStore with SQLAlchemy Models (foreign key) - Python Flask


code:
from django.db.models.signals import class_prepared

def longer_username(sender, *args, **kwargs):
    # You can't just do `if sender == django.contrib.auth.models.User`
    # because you would have to import the model
    # You have to test using __name__ and __module__
    if sender.__name__ == "User" and sender.__module__ == \
        "django.contrib.auth.models":
        sender._meta.get_field("username").max_length = 75

class_prepared.connect(longer_username)

rawDescription: Made Django's auth track on emails, how to relate username field to email?


code: is_activated.boolean = True

rawDescription: Display tick and cross icons for a property in the Django administration console


rawDescription: All possible combinations of card/poker hands for a set of players


code: {{ event.status }}

rawDescription: Extra data about objects in django templates


code:
import re
data = """
some data ... [my opening pattern
is here
and can be multiline] the data
I want to extract [my ending
pattern which can be
multiline as well] ... more data
"""
re.findall('\[[^]]*\]\s+([^[]+)\s+\[[^]]+\]', data)

rawDescription: How to read a file and extract data between multiline patterns?

description: Read a file and extract data between multiline patterns


rawDescription: Python - sending unicode characters (prefixed with \u) in an HTTP POST request


rawDescription: How to Split Python list every Nth element

description: Split Python list every Nth element


code:
class Foo(object):
    def upper(self, s):
        return s.upper()

def func(s, method, cond):
    if cond:
        return method(s)
    else:
        return s

obj = Foo()
s = 'hello world'

print(func(s, obj.upper, 'hello' in s))
print(func(s, obj.upper, 'goodbye' in s))

rawDescription: Python: Higher Order Functions with Methods


code:
for _ in range(5):
    print(choice('abcdefghijklmnopqrstuvwxyz'), flush=True)

rawDescription: Python asyncio timely event handling

description: Python asyncio timely event handling


code:
df = pd.DataFrame({'index': range(4),
                   'code': ['wrt_10', 'wrt_11', 'wrt_16', 'wrt_14'],
                   'value': [10, 13, 3, 5]})
split = df['code'].str.split('_', expand=True)
split.columns = ['name', 'number']
print(df.join(split))
#      code  index  value name number
# 0  wrt_10      0     10  wrt     10
# 1  wrt_11      1     13  wrt     11
# 2  wrt_16      2      3  wrt     16
# 3  wrt_14      3      5  wrt     14

rawDescription: how to break a vector into two in python

description: Break a vector into two in python


code:
for _ in intersect(input_set, set_1):
    user_score += 1

rawDescription: Finding the intersection between sets and awarding points


code:
def int_to_signed_short(value):
    return -(value & 0x8000) | (value & 0x7fff)

def xy_from_index(index):
    x, y = index & 65535, (index >> 16) + 16
    return map(int_to_signed_short, [x, y])

rawDescription: Python convert int to unsigned short then back to int


code:
def check_customer_name(row):
    if row['customer_name'] == NULL:
        row['customer_name'] = row['contact_name']
    return row

rawDescription: Python functions - pass a full if condition as a parameter


code:
def check_brackets(s):
    counter = 0
    for chr in s:
        if chr == "(":
            counter += 1
        elif chr == ")":
            counter -= 1
            if counter < 0:
                return False
    return counter == 0

rawDescription: Find bracket which are not closed without using regex in python


code:
from StringIO import StringIO
dir(StringIO)
help(StringIO.truncate)

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
dd = {key: [i[1] for i in l if i[0] == key] for (key, value) in l}
dd

rawDescription: Transforming a list

description: Transforming a list


code:
def check_all(substrings, strings):
    """Check all *substrings* are in *strings*."""
    return all(any(substr in s for s in strings) for substr in substrings)

rawDescription: Check if list of 'partial' strings is in list of full strings


code:
m_2 = io.readlines()

print(m_1)
print(m_1==m_2)

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


code: ndb.query(Part.alpha == Alpha.B)

rawDescription: Pass enum to ndb.Model field in python

description: Pass enum to ndb.Model field in python


code:
queryset = Pizza.objects.all().prefetch_related('toppings')
serializer = PizzaSerializer(queryset, many=True)

rawDescription: Correct way to use Django's ORM and Django Rest Framework to serialize a queryset of nested relationships?


code:
import copy
from lxml import etree
import Tkinter as tk

# assumption: the root element of both trees is the same
# note: missing subtrees will only have the parent element highlighted

def element_content_equal(e1, e2):
    # starting point here: http://stackoverflow.com/a/24349916/377366
    try:
        if e1.tag != e1.tag:
            return False
        elif e1.text != e2.text:
            return False
        elif e1.tail != e2.tail:
            return False
        elif e1.attrib != e2.attrib:
            return False
    except AttributeError:
        # e.g. None is passed in for an element
        return False
    return True

def element_is_in_sequence(element, sequence):
    for e in sequence:
        if element_content_equal(e, element):
            return True
    return False

def copy_element_without_children(element):
    e_copy = etree.Element(element.tag, attrib=element.attrib, nsmap=element.nsmap)
    e_copy.text = element.text
    e_copy.tail = element.tail
    return e_copy

# start at the root of both xml trees
parser = etree.XMLParser(recover=True, remove_blank_text=True)
base_root = etree.parse('base.xml', parser=parser).getroot()
test_root = etree.parse('test.xml', parser=parser).getroot()
# each element from the original xml trees will be placed into a merge tree
merge_root = copy_element_without_children(base_root)

# additionally each merge tree element will be tagged with its source
DIFF_ATTRIB = 'diff'
FROM_BASE_ONLY = 'base'
FROM_TEST_ONLY = 'test'

# process the pair of trees, one set of parents at a time
parent_stack = [(base_root, test_root, merge_root)]
while parent_stack:
    base_parent, test_parent, merge_parent = parent_stack.pop()
    base_children = base_parent.getchildren()
    test_children = test_parent.getchildren()

    # compare children and transfer to merge tree
    base_children_iter = iter(base_children)
    test_children_iter = iter(test_children)
    base_child = next(base_children_iter, None)
    test_child = next(test_children_iter, None)
    while (base_child is not None) or (test_child is not None):
        # first handle the case of a unique base child
        if (base_child is not None) and (not element_is_in_sequence(base_child, test_children)):
            # base_child is unique: deep copy with base only tag
            merge_child = copy.deepcopy(base_child)
            merge_child.attrib[DIFF_ATTRIB] = FROM_BASE_ONLY
            merge_parent.append(merge_child)
            # this unique child has already been fully copied to the merge tree so it doesn't go on the stack
            # only move the base child since test child hasn't been handled yet
            base_child = next(base_children_iter, None)
        elif (test_child is not None) and (not element_is_in_sequence(test_child, base_children)):
            # test_child is unique: deep copy with base only tag
            merge_child = copy.deepcopy(test_child)
            merge_child.attrib[DIFF_ATTRIB] = FROM_TEST_ONLY
            merge_parent.append(merge_child)
            # this unique child has already been fully copied to the merge tree so it doesn't go on the stack
            # only move test child since base child hasn't been handled yet
            test_child = next(test_children_iter, None)
        elif element_content_equal(base_child, test_child):
            # both trees share the same element: shallow copy either child with shared tag
            merge_child = copy_element_without_children(base_child)
            merge_parent.append(merge_child)
            # put pair of children on stack as parents to be tested since their children may differ
            parent_stack.append((base_child, test_child, merge_child))
            # move on to next children in both trees since this was a shared element
            base_child = next(base_children_iter, None)
            test_child = next(test_children_iter, None)
        else:
            raise RuntimeError  # there is something wrong - element should be unique or shared.

# display merge_tree with highlighting to indicate source of each line
#   no highlight: common element in both trees
#   green: line that exists only in test tree (i.e. additional)
#   red: line that exists only in the base tree (i.e. missing)
root = tk.Tk()
textbox = tk.Text(root)
textbox.pack(expand=1, fill=tk.BOTH)
textbox.tag_config(FROM_BASE_ONLY, background='#ff5555')
textbox.tag_config(FROM_TEST_ONLY, background='#55ff55')

# find diff lines to highlight within merge_tree string that includes kludge attributes
merge_tree_string = etree.tostring(merge_root, pretty_print=True)
diffs_by_line = []
for line, line_text in enumerate(merge_tree_string.split('\n')):
    for diff_type in (FROM_BASE_ONLY, FROM_TEST_ONLY):
        if diff_type in line_text:
            diffs_by_line.append((line+1, diff_type))

# remove kludge attributes
for element in merge_root.iter():
    try:
        del(element.attrib[DIFF_ATTRIB])
    except KeyError:
        pass
merge_tree_string = etree.tostring(merge_root, pretty_print=True)

# highlight final lines
textbox.insert(tk.END, merge_tree_string)
for line, diff_type in diffs_by_line:
    textbox.tag_add(diff_type, '{}.0'.format(line), '{}.0'.format(int(line)+1))
root.mainloop()

rawDescription: Highlight differences between two xml files in a Tkinter textbox


code:
import numpy as np
import functools

def takes_1dim_array(func):
    @functools.wraps(func)
    def f(arr, *a, **kw):
        arr = np.asarray(arr).ravel()
        return func(arr, *a, **kw)
    return f

rawDescription: Python Passing List or Numpy Array

description: Python Passing List or Numpy Array


code:
with open('your_file', 'w') as fd:
    for k, v in settings.items():
        fd.write('[{}] {}\n'.format(k, v))

rawDescription: Reading Tags in text File Python

description: Reading Tags in text File Python


code:
class your_class(osv.osv):
    # ...

    def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
        res = super(your_class, self).read_group(cr, uid, domain, fields, groupby, offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
        if 'amount_pending' in fields:
            for line in res:
                if '__domain' in line:
                    lines = self.search(cr, uid, line['__domain'], context=context)
                    pending_value = 0.0
                    for current_account in self.browse(cr, uid, lines, context=context):
                        pending_value += current_account.amount_pending
                    line['amount_pending'] = pending_value
        if 'amount_payed' in fields:
            for line in res:
                if '__domain' in line:
                    lines = self.search(cr, uid, line['__domain'], context=context)
                    payed_value = 0.0
                    for current_account in self.browse(cr, uid, lines, context=context):
                        payed_value += current_account.amount_payed
                    line['amount_payed'] = payed_value
        return res

rawDescription: How to sum other columns when using "Group by" in a Tree View?

description: Sum other columns when using "Group by" in a Tree View


code:
re.search(r'^.*\d', " 5473 & 4835 how to find the index").group()
re.search(r'^.*\d', 'A-121-2 how to find the index').group()

rawDescription: How can I get a string(Mix of digit and char) up to last digit using regex in python?

description: Get a string(Mix of digit and char) up to last digit using regex in python


code:
if formset.is_valid ():
            location = request.POST ['site']
            data = formset.cleaned_data
            request, template, context = getData (request, data, location)    # ====> Created a function to cut down nested if statement
            return render (request, template, context)

rawDescription: Unable to Render Django Template using Method


code:
multiples_of_6 = (not (i % 6) for i in range(1, 10))
any(multiples_of_6)
list(multiples_of_6)

rawDescription: How do Python's any and all functions work?


code:
with open("vegetables","r+") as t:
  data = t.read()
  t.seek(data.index("apples_"))
  t.write("lettuce")

rawDescription: Using 'r+' mode to overwrite a line in a file with another line of the same length


code: merged

rawDescription: Combinatorial explosion while merging dataframes in pandas


code:
class CacheService(object):

    def __init__(self):
        self.data = {}

    def __setitem__(self, key, item):
        self.data[key] = [item, 0]

    def __getitem__(self, key):
        value = self.data[key]
        value[1] += 1
        return value[0]

    def getcount(self, key):
        return self.data[key][1]

rawDescription: python cache dictionary - counting number of hits

description: Python cache dictionary - counting number of hits


rawDescription: Generate all leaf-to-root paths in a dictionary tree in Python


rawDescription: How to extract particular set of value from a file in Python?

description: Extract particular set of value from a file in Python